ccdserver.cpp 982 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield_imp.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include <algorithm>
  40. #include "dafdesc.hpp"
  41. #include "dautils.hpp"
  42. #include "ftbase.ipp"
  43. namespace ccdserver_hqlhelper
  44. {
  45. #include "eclhelper_base.hpp"
  46. }
  47. #include "ccd.hpp"
  48. #include "ccdserver.hpp"
  49. #include "ccdcontext.hpp"
  50. #include "ccdactivities.hpp"
  51. #include "ccdquery.hpp"
  52. #include "ccdstate.hpp"
  53. #include "ccdqueue.ipp"
  54. #include "ccdsnmp.hpp"
  55. #include "ccddali.hpp"
  56. #include "jsmartsock.hpp"
  57. #include "dllserver.hpp"
  58. #include "workflow.hpp"
  59. #include "roxiemem.hpp"
  60. #include "roxierowbuff.hpp"
  61. #include "roxiehelper.hpp"
  62. #include "roxielmj.hpp"
  63. #include "roxierow.hpp"
  64. #include "thorplugin.hpp"
  65. #include "keybuild.hpp"
  66. #include "thorstrand.hpp"
  67. #define MAX_HTTP_HEADERSIZE 8000
  68. #define MIN_PAYLOAD_SIZE 800
  69. #pragma warning(disable : 4355)
  70. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  71. #define PROBE
  72. #ifdef _DEBUG
  73. //#define FAKE_EXCEPTIONS
  74. //#define TRACE_JOINGROUPS
  75. //#define TRACE_SPLIT
  76. //#define _CHECK_HEAPSORT
  77. //#undef PARALLEL_EXECUTE
  78. //#define TRACE_SEEK_REQUESTS
  79. #endif
  80. using roxiemem::OwnedRoxieRow;
  81. using roxiemem::OwnedRoxieString;
  82. using roxiemem::OwnedConstRoxieRow;
  83. using roxiemem::IRowManager;
  84. using roxiemem::ReleaseRoxieRows;
  85. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  86. #if _MSC_VER==1200
  87. #define protected public
  88. #endif
  89. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  90. #define TRACE_STRANDS
  91. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  92. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  93. //=================================================================================
  94. class RestartableThread : public CInterface
  95. {
  96. class MyThread : public Thread
  97. {
  98. Linked<RestartableThread> owner;
  99. public:
  100. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  101. {
  102. }
  103. virtual int run()
  104. {
  105. owner->started.signal();
  106. return owner->run();
  107. }
  108. };
  109. friend class MyThread;
  110. Semaphore started;
  111. Owned<MyThread> thread;
  112. CriticalSection crit;
  113. StringAttr name;
  114. public:
  115. RestartableThread(const char *_name) : name(_name)
  116. {
  117. }
  118. virtual void start(const char *namePrefix)
  119. {
  120. StringBuffer s(namePrefix);
  121. s.append(name);
  122. {
  123. CriticalBlock b(crit);
  124. assertex(!thread);
  125. thread.setown(new MyThread(this, s));
  126. thread->start();
  127. }
  128. started.wait();
  129. }
  130. virtual void join()
  131. {
  132. {
  133. Owned<Thread> tthread;
  134. {
  135. CriticalBlock b(crit);
  136. tthread.setown(thread.getClear());
  137. }
  138. if (tthread)
  139. tthread->join();
  140. }
  141. }
  142. virtual int run() = 0;
  143. };
  144. //================================================================================
  145. //The following don't link their arguments because that creates a circular reference
  146. //But I wish there was a better way
  147. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  148. {
  149. public:
  150. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  151. IMPLEMENT_IINTERFACE
  152. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  153. virtual ICodeContext *queryCodeContext()
  154. {
  155. return ctx->queryCodeContext();
  156. }
  157. virtual void checkAbort()
  158. {
  159. ctx->checkAbort();
  160. }
  161. virtual void notifyAbort(IException *E)
  162. {
  163. ctx->notifyAbort(E);
  164. }
  165. virtual IActivityGraph * queryChildGraph(unsigned id)
  166. {
  167. return ctx->queryChildGraph(id);
  168. }
  169. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  170. {
  171. ctx->noteChildGraph(id, childGraph) ;
  172. }
  173. virtual IRowManager &queryRowManager()
  174. {
  175. return ctx->queryRowManager();
  176. }
  177. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  178. {
  179. ctx->noteStatistic(kind, value);
  180. }
  181. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  182. {
  183. ctx->mergeStats(from);
  184. }
  185. virtual const CRuntimeStatisticCollection &queryStats() const
  186. {
  187. return ctx->queryStats();
  188. }
  189. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  190. {
  191. ctx->CTXLOGva(format, args);
  192. }
  193. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  194. {
  195. ctx->CTXLOGa(category, prefix, text);
  196. }
  197. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  198. {
  199. ctx->logOperatorExceptionVA(E, file, line, format, args);
  200. }
  201. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  202. {
  203. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  204. }
  205. virtual void CTXLOGl(LogItem *log) const
  206. {
  207. ctx->CTXLOGl(log);
  208. }
  209. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  210. {
  211. return ctx->getLogPrefix(ret);
  212. }
  213. virtual unsigned queryTraceLevel() const
  214. {
  215. return ctx->queryTraceLevel();
  216. }
  217. virtual bool isIntercepted() const
  218. {
  219. return ctx->isIntercepted();
  220. }
  221. virtual bool isBlind() const
  222. {
  223. return ctx->isBlind();
  224. }
  225. virtual const QueryOptions &queryOptions() const
  226. {
  227. return ctx->queryOptions();
  228. }
  229. virtual void addSlavesReplyLen(unsigned len)
  230. {
  231. ctx->addSlavesReplyLen(len);
  232. }
  233. virtual const char *queryAuthToken()
  234. {
  235. return ctx->queryAuthToken();
  236. }
  237. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  238. {
  239. return ctx->resolveLFN(filename, isOpt);
  240. }
  241. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  242. {
  243. return ctx->createLFN(filename, overwrite, extend, clusters);
  244. }
  245. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  246. {
  247. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  248. }
  249. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  250. {
  251. return ctx->getLibraryGraph(extra, parentActivity);
  252. }
  253. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed, unsigned _strands) const
  254. {
  255. ctx->noteProcessed(subgraphId, activityId, _idx, _processed, _strands);
  256. }
  257. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  258. {
  259. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  260. }
  261. virtual IProbeManager *queryProbeManager() const
  262. {
  263. return ctx->queryProbeManager();
  264. }
  265. virtual IDebuggableContext *queryDebugContext() const
  266. {
  267. return ctx->queryDebugContext();
  268. }
  269. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  270. {
  271. ctx->printResults(output, name, sequence);
  272. }
  273. virtual void setWUState(WUState state)
  274. {
  275. ctx->setWUState(state);
  276. }
  277. virtual bool checkWuAborted()
  278. {
  279. return ctx->checkWuAborted();
  280. }
  281. virtual IWorkUnit *updateWorkUnit() const
  282. {
  283. return ctx->updateWorkUnit();
  284. }
  285. virtual IConstWorkUnit *queryWorkUnit() const
  286. {
  287. return ctx->queryWorkUnit();
  288. }
  289. virtual IRoxieServerContext *queryServerContext()
  290. {
  291. return ctx->queryServerContext();
  292. }
  293. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  294. {
  295. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  296. }
  297. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  298. {
  299. return ctx->getRowAllocatorEx(meta, activityId, flags);
  300. }
  301. protected:
  302. IRoxieSlaveContext * ctx;
  303. };
  304. //=================================================================================
  305. #define RESULT_FLUSH_THRESHOLD 10000u
  306. #ifdef _DEBUG
  307. #define SOAP_SPLIT_THRESHOLD 100u
  308. #define SOAP_SPLIT_RESERVE 200u
  309. #else
  310. #define SOAP_SPLIT_THRESHOLD 64000u
  311. #define SOAP_SPLIT_RESERVE 65535u
  312. #endif
  313. //=================================================================================
  314. // General activity statistics
  315. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  316. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StNumStrands,
  317. StNumScansPerRow, StNumAllocations, StNumAllocationScans, StKindNone);
  318. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  319. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  320. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  321. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  322. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  323. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  324. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  325. StNumDiskRejected, StKindNone);
  326. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  327. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  328. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  329. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  330. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  331. StNumIndexRowsRead, StKindNone);
  332. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  333. StNumDiskRejected, StKindNone);
  334. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  335. static const StatisticsMapping groupStatistics(&actStatistics, StNumGroups, StNumGroupMax, StKindNone);
  336. static const StatisticsMapping sortStatistics(&actStatistics, StTimeSortElapsed, StKindNone);
  337. //=================================================================================
  338. const static unsigned minus1U = (0U-1U);
  339. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  340. {
  341. protected:
  342. IntArray dependencies; // things I am dependent on
  343. IntArray dependencyIndexes; // things I am dependent on
  344. IntArray dependencyControlIds; // things I am dependent on
  345. StringArray dependencyEdgeIds; // How to describe them to the debugger
  346. unsigned dependentCount; // things dependent on me
  347. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  348. bool optStableInput = true; // is the input forced to ordered?
  349. bool optUnstableInput = false; // is the input forced to unordered?
  350. bool optUnordered = false; // is the output specified as unordered?
  351. unsigned heapFlags;
  352. mutable CriticalSection statsCrit;
  353. mutable __int64 processed;
  354. mutable __int64 started;
  355. mutable __int64 totalCycles;
  356. mutable __int64 localCycles;
  357. public:
  358. IMPLEMENT_IINTERFACE;
  359. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  360. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  361. {
  362. processed = 0;
  363. started = 0;
  364. totalCycles = 0;
  365. localCycles = 0;
  366. dependentCount = 0;
  367. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  368. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  369. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  370. }
  371. ~CRoxieServerActivityFactoryBase()
  372. {
  373. }
  374. StringBuffer &toString(StringBuffer &ret) const
  375. {
  376. return ret.appendf("%p", this);
  377. }
  378. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  379. {
  380. dependencies.append(_source);
  381. dependencyIndexes.append(_sourceIdx);
  382. dependencyControlIds.append(controlId);
  383. dependencyEdgeIds.append(edgeId);
  384. }
  385. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  386. {
  387. if (optStableInput)
  388. return true;
  389. if (optUnstableInput)
  390. return false;
  391. if (optUnordered)
  392. return false;
  393. return consumerOrdered;
  394. }
  395. virtual void noteDependent(unsigned target)
  396. {
  397. dependentCount++;
  398. }
  399. virtual IntArray &queryDependencies() { return dependencies; }
  400. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  401. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  402. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  403. virtual unsigned queryId() const { return id; }
  404. virtual unsigned querySubgraphId() const { return subgraphId; }
  405. virtual ThorActivityKind getKind() const { return kind; }
  406. virtual IOutputMetaData * queryOutputMeta() const
  407. {
  408. return meta;
  409. }
  410. virtual bool isSink() const
  411. {
  412. return false;
  413. }
  414. virtual bool isFunction() const
  415. {
  416. return false;
  417. }
  418. virtual bool isGraphInvariant() const
  419. {
  420. return false;
  421. }
  422. virtual IHThorArg &getHelper() const
  423. {
  424. return *helperFactory();
  425. }
  426. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  427. {
  428. arg.Release();
  429. throwUnexpected();
  430. }
  431. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  432. {
  433. CActivityFactory::mergeStats(from);
  434. }
  435. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  436. {
  437. dbgassertex(!_idx);
  438. if (_processed)
  439. {
  440. CriticalBlock b(statsCrit);
  441. processed += _processed;
  442. }
  443. }
  444. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  445. {
  446. if (_totalCycles.totalCycles || _localCycles)
  447. {
  448. CriticalBlock b(statsCrit);
  449. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  450. totalCycles += _totalCycles.totalCycles;
  451. localCycles += _localCycles;
  452. }
  453. CActivityFactory::mergeStats(fromStats);
  454. }
  455. virtual void noteStarted() const
  456. {
  457. CriticalBlock b(statsCrit);
  458. started ++;
  459. }
  460. virtual void noteStarted(unsigned idx) const
  461. {
  462. throwUnexpected(); // should be implemented/required by multiOutput cases only
  463. }
  464. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  465. {
  466. CriticalBlock b(statsCrit);
  467. if (output == 0)
  468. {
  469. putStatsValue(&edge, "count", "sum", processed);
  470. if (started)
  471. putStatsValue(&edge, "started", "sum", started);
  472. }
  473. else
  474. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  475. }
  476. virtual void getNodeProgressInfo(IPropertyTree &node) const
  477. {
  478. CActivityFactory::getNodeProgressInfo(node);
  479. CriticalBlock b(statsCrit);
  480. if (started)
  481. putStatsValue(&node, "_roxieStarted", "sum", started);
  482. if (totalCycles)
  483. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  484. if (localCycles)
  485. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  486. }
  487. virtual void resetNodeProgressInfo()
  488. {
  489. CActivityFactory::resetNodeProgressInfo();
  490. CriticalBlock b(statsCrit);
  491. processed = 0;
  492. started = 0;
  493. totalCycles = 0;
  494. localCycles = 0;
  495. }
  496. virtual void getActivityMetrics(StringBuffer &reply) const
  497. {
  498. CActivityFactory::getActivityMetrics(reply);
  499. CriticalBlock b(statsCrit);
  500. putStatsValue(reply, "_roxieStarted", "sum", started);
  501. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  502. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  503. }
  504. virtual unsigned __int64 queryLocalCycles() const
  505. {
  506. return localCycles;
  507. }
  508. virtual IQueryFactory &queryQueryFactory() const
  509. {
  510. return CActivityFactory::queryQueryFactory();
  511. }
  512. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  513. {
  514. return CActivityFactory::queryChildQuery(idx, id);
  515. }
  516. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  517. {
  518. CActivityFactory::addChildQuery(id, childQuery);
  519. }
  520. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  521. {
  522. ForEachItemIn(idx, childQueries)
  523. {
  524. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  525. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  526. childGraphs.item(idx).onCreate(colocalArg);
  527. }
  528. }
  529. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  530. {
  531. unsigned match = childQueryIndexes.find(childId);
  532. assertex(match != NotFound);
  533. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  534. graph->onCreate(colocalArg);
  535. return graph.getClear();
  536. }
  537. virtual IRoxieServerSideCache *queryServerSideCache() const
  538. {
  539. return NULL; // Activities that wish to support server-side caching will need to do better....
  540. }
  541. virtual bool getEnableFieldTranslation() const
  542. {
  543. throwUnexpected(); // only implemented by index-related subclasses
  544. }
  545. virtual IDefRecordMeta *queryActivityMeta() const
  546. {
  547. throwUnexpected(); // only implemented by index-related subclasses
  548. }
  549. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  550. {
  551. // Most activities have nothing to say...
  552. }
  553. virtual const StatisticsMapping &queryStatsMapping() const
  554. {
  555. return actStatistics; // Overridden by anyone that needs more
  556. }
  557. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  558. {
  559. return (roxiemem::RoxieHeapFlags)heapFlags;
  560. }
  561. };
  562. class CRoxieServerMultiInputInfo
  563. {
  564. private:
  565. UnsignedArray inputs;
  566. UnsignedArray inputIndexes;
  567. public:
  568. void set(unsigned idx, unsigned source, unsigned sourceidx)
  569. {
  570. if (idx==inputs.length())
  571. {
  572. inputs.append(source);
  573. inputIndexes.append(sourceidx);
  574. }
  575. else
  576. {
  577. while (!inputs.isItem(idx))
  578. {
  579. inputs.append(0);
  580. inputIndexes.append(0);
  581. }
  582. inputs.replace(source, idx);
  583. inputIndexes.replace(sourceidx, idx);
  584. }
  585. }
  586. unsigned get(unsigned idx, unsigned &sourceidx) const
  587. {
  588. if (inputs.isItem(idx))
  589. {
  590. sourceidx = inputIndexes.item(idx);
  591. return inputs.item(idx);
  592. }
  593. else
  594. return (unsigned) -1;
  595. }
  596. inline unsigned ordinality() const { return inputs.ordinality(); }
  597. };
  598. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  599. {
  600. private:
  601. CRoxieServerMultiInputInfo inputs;
  602. public:
  603. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  604. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  605. {
  606. }
  607. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  608. {
  609. inputs.set(idx, source, sourceidx);
  610. }
  611. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  612. {
  613. return inputs.get(idx, sourceidx);
  614. }
  615. virtual unsigned numInputs() const { return inputs.ordinality(); }
  616. };
  617. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  618. {
  619. Owned<IException> wrapped;
  620. ThorActivityKind kind;
  621. unsigned queryId;
  622. public:
  623. IMPLEMENT_IINTERFACE;
  624. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  625. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  626. {
  627. }
  628. virtual int errorCode() const { return wrapped->errorCode(); }
  629. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  630. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  631. };
  632. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  633. {
  634. protected:
  635. unsigned input;
  636. unsigned inputidx;
  637. public:
  638. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  639. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  640. {
  641. input = (unsigned) -1;
  642. inputidx = 0;
  643. }
  644. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  645. {
  646. if (idx != 0)
  647. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  648. if (input != -1)
  649. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, sanitizeSourceFile(__FILE__), __LINE__);
  650. input = source;
  651. inputidx = sourceidx;
  652. }
  653. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  654. {
  655. if (!idx)
  656. {
  657. sourceidx = inputidx;
  658. return input;
  659. }
  660. return (unsigned) -1;
  661. }
  662. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  663. };
  664. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  665. {
  666. protected:
  667. unsigned numOutputs;
  668. unsigned __int64 *processedArray;
  669. bool *startedArray;
  670. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  672. {
  673. numOutputs = 0;
  674. processedArray = NULL;
  675. startedArray = NULL;
  676. }
  677. ~CRoxieServerMultiOutputFactory()
  678. {
  679. delete [] processedArray;
  680. delete [] startedArray;
  681. }
  682. void setNumOutputs(unsigned num)
  683. {
  684. numOutputs = num;
  685. if (!num)
  686. num = 1; // Even sink activities like to track how many records they process
  687. processedArray = new unsigned __int64[num];
  688. startedArray = new bool[num];
  689. for (unsigned i = 0; i < num; i++)
  690. {
  691. processedArray[i] = 0;
  692. startedArray[i] = 0;
  693. }
  694. }
  695. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  696. {
  697. assertex(numOutputs ? idx < numOutputs : idx==0);
  698. CriticalBlock b(statsCrit);
  699. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  700. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  701. }
  702. virtual void resetNodeProgressInfo()
  703. {
  704. CRoxieServerActivityFactory::resetNodeProgressInfo();
  705. CriticalBlock b(statsCrit);
  706. for (unsigned i = 0; i < numOutputs; i++)
  707. {
  708. processedArray[i] = 0;
  709. startedArray[i] = 0;
  710. }
  711. }
  712. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  713. {
  714. assertex(numOutputs ? idx < numOutputs : idx==0);
  715. CriticalBlock b(statsCrit);
  716. processedArray[idx] += _processed;
  717. }
  718. virtual void noteStarted(unsigned idx) const
  719. {
  720. assertex(numOutputs ? idx < numOutputs : idx==0);
  721. CriticalBlock b(statsCrit);
  722. startedArray[idx] = true;
  723. }
  724. };
  725. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  726. {
  727. protected:
  728. bool isInternal;
  729. bool isRoot;
  730. unsigned usageCount;
  731. public:
  732. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  733. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  734. {
  735. usageCount = _usageCount;
  736. isRoot = _isRoot;
  737. isInternal = false; // filled in by derived class constructor
  738. }
  739. virtual bool isSink() const
  740. {
  741. //only a sink if a root activity
  742. return isRoot && !(isInternal && dependentCount && dependentCount==usageCount); // MORE - it's possible for this to get the answer wrong still, since usageCount does not include references from main procedure. Gavin?
  743. }
  744. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  745. {
  746. // There is no meaningful info to return along the dependency edge - we don't detect how many times the value has been read from the context
  747. // Just leave it blank is safest.
  748. }
  749. };
  750. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  751. const char *queryStateText(activityState state)
  752. {
  753. switch (state)
  754. {
  755. case STATEreset: return "reset";
  756. case STATEstarted: return "started";
  757. case STATEstopped: return "stopped";
  758. case STATEstarting: return "starting";
  759. default: return "unknown";
  760. }
  761. }
  762. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  763. class CParallelActivityExecutor : public CAsyncFor
  764. {
  765. public:
  766. unsigned parentExtractSize;
  767. const byte * parentExtract;
  768. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  769. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  770. void Do(unsigned i)
  771. {
  772. activities.item(i).execute(parentExtractSize, parentExtract);
  773. }
  774. private:
  775. IRoxieServerActivityCopyArray & activities;
  776. };
  777. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  778. {
  779. if (instreams.length() != 1)
  780. {
  781. assertex(instreams.length());
  782. if (!junction)
  783. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  784. ForEachItemIn(stream, instreams)
  785. {
  786. junction->setInput(stream, instreams.item(stream));
  787. }
  788. return junction->queryOutput(0);
  789. }
  790. else
  791. return instreams.item(0);
  792. }
  793. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  794. {
  795. if (input)
  796. {
  797. PointerArrayOf<IEngineRowStream> instreams;
  798. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  799. return ensureSingleStream(ctx, instreams, junction);
  800. }
  801. else
  802. return NULL;
  803. }
  804. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  805. {
  806. Owned<IStrandJunction> junction;
  807. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  808. assertex(!junction);
  809. return result;
  810. }
  811. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  812. {
  813. friend class StrandProcessor;
  814. protected:
  815. IFinalRoxieInput *input;
  816. unsigned sourceIdx;
  817. IEngineRowStream *inputStream;
  818. Owned<IStrandJunction> junction;
  819. IHThorArg &basehelper;
  820. IRoxieSlaveContext *ctx;
  821. 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 DECL_EXCEPTION 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)", sanitizeSourceFile(__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", sanitizeSourceFile(__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", sanitizeSourceFile(__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)", sanitizeSourceFile(__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. if (traceLevel > 4)
  9706. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9707. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9708. }
  9709. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9710. virtual bool needsAllocator() const { return true; }
  9711. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9712. {
  9713. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9714. if (combineStreams)
  9715. {
  9716. barrier.setown(createStrandBarrier());
  9717. ForEachItemIn(i, strands)
  9718. barrier->startStrand(queryAggregate(i));
  9719. active.store(1);
  9720. }
  9721. else
  9722. active.store(0);
  9723. }
  9724. virtual void reset() override
  9725. {
  9726. CRoxieServerStrandedActivity::reset();
  9727. barrier.clear();
  9728. calculated = false;
  9729. }
  9730. //Helper functions for the single aggregate case
  9731. const void * getCombinedAggregate()
  9732. {
  9733. if (calculated)
  9734. return NULL;
  9735. calculated= true;
  9736. barrier->waitForStrands();
  9737. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9738. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9739. bool isFirst = true;
  9740. for (unsigned i=0; i < numStrands(); i++)
  9741. {
  9742. const void * next = queryAggregate(i).queryResult();
  9743. if (next)
  9744. {
  9745. if (isFirst)
  9746. {
  9747. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9748. isFirst = false;
  9749. }
  9750. else
  9751. finalSize = helper.mergeAggregate(rowBuilder, next);
  9752. }
  9753. }
  9754. return rowBuilder.finalizeRowClear(finalSize);
  9755. }
  9756. void outputStopped()
  9757. {
  9758. //only called if generating a single result.
  9759. assertex(combineStreams);
  9760. if (barrier)
  9761. {
  9762. requestAbort(); // if strands are still running, abort them
  9763. barrier->waitForStrands();
  9764. }
  9765. else
  9766. {
  9767. ForEachItemIn(i, strands)
  9768. queryAggregate(i).stopStream();
  9769. }
  9770. CRoxieServerStrandedActivity::stop();
  9771. }
  9772. void noteStrandFinished(IRowStream * stream)
  9773. {
  9774. barrier->noteStrandFinished(stream);
  9775. }
  9776. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9777. {
  9778. //The non-ordered aggregate does not need to process the ordered call back information.
  9779. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9780. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9781. return &nullCallback;
  9782. }
  9783. inline AggregateProcessor & queryAggregate(unsigned i)
  9784. {
  9785. return static_cast<AggregateProcessor &>(strands.item(i));
  9786. }
  9787. protected:
  9788. IHThorAggregateArg &helper;
  9789. Owned<IStrandBarrier> barrier;
  9790. IEngineRowStream * combinedStream = nullptr;
  9791. bool isInputGrouped;
  9792. bool abortEarly;
  9793. bool combineStreams = false;
  9794. bool calculated = false;
  9795. };
  9796. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9797. {
  9798. StrandOptions strandOptions;
  9799. public:
  9800. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9801. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9802. {
  9803. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9804. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9805. optStableInput = false;
  9806. }
  9807. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9808. {
  9809. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  9810. }
  9811. };
  9812. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9813. {
  9814. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9815. }
  9816. //=================================================================================
  9817. typedef unsigned t_hashPrefix;
  9818. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9819. {
  9820. IHThorHashAggregateArg &helper;
  9821. RowAggregator aggregated;
  9822. bool eof;
  9823. bool gathered;
  9824. bool isGroupedAggregate;
  9825. public:
  9826. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9827. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9828. isGroupedAggregate(_isGroupedAggregate),
  9829. aggregated(helper, helper)
  9830. {
  9831. eof = false;
  9832. gathered = false;
  9833. }
  9834. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9835. {
  9836. eof = false;
  9837. gathered = false;
  9838. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9839. }
  9840. virtual void reset()
  9841. {
  9842. aggregated.reset();
  9843. CRoxieServerActivity::reset();
  9844. }
  9845. virtual bool needsAllocator() const { return true; }
  9846. virtual const void * nextRow()
  9847. {
  9848. ActivityTimer t(totalCycles, timeActivities);
  9849. if (eof)
  9850. return NULL;
  9851. if (!gathered)
  9852. {
  9853. aggregated.start(rowAllocator);
  9854. bool eog = true;
  9855. loop
  9856. {
  9857. const void * next = inputStream->nextRow();
  9858. if (!next)
  9859. {
  9860. if (isGroupedAggregate)
  9861. {
  9862. if (eog)
  9863. eof = true;
  9864. break;
  9865. }
  9866. next = inputStream->nextRow();
  9867. if (!next)
  9868. break;
  9869. }
  9870. eog = false;
  9871. aggregated.addRow(next);
  9872. ReleaseRoxieRow(next);
  9873. }
  9874. gathered = true;
  9875. }
  9876. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9877. if (next)
  9878. {
  9879. processed++;
  9880. return next->finalizeRowClear();
  9881. }
  9882. if (!isGroupedAggregate)
  9883. eof = true;
  9884. aggregated.reset();
  9885. gathered = false;
  9886. return NULL;
  9887. }
  9888. };
  9889. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9890. {
  9891. public:
  9892. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9893. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9894. {
  9895. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9896. }
  9897. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9898. {
  9899. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  9900. }
  9901. protected:
  9902. bool isGroupedAggregate;
  9903. };
  9904. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9905. {
  9906. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9907. }
  9908. //=================================================================================
  9909. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9910. {
  9911. IHThorDegroupArg &helper;
  9912. bool eof;
  9913. public:
  9914. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9915. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9916. {
  9917. eof = false;
  9918. }
  9919. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9920. {
  9921. eof = false;
  9922. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9923. }
  9924. virtual const void * nextRow()
  9925. {
  9926. ActivityTimer t(totalCycles, timeActivities);
  9927. if (eof)
  9928. return NULL;
  9929. const void * ret = inputStream->ungroupedNextRow();
  9930. if (ret)
  9931. processed++;
  9932. else
  9933. eof = true;
  9934. return ret;
  9935. }
  9936. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9937. {
  9938. ActivityTimer t(totalCycles, timeActivities);
  9939. if (eof)
  9940. return NULL;
  9941. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9942. if (ret)
  9943. processed++;
  9944. else
  9945. eof = true;
  9946. return ret;
  9947. }
  9948. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9949. {
  9950. return input->gatherConjunctions(collector);
  9951. }
  9952. virtual void resetEOF()
  9953. {
  9954. eof = false;
  9955. inputStream->resetEOF();
  9956. }
  9957. IInputSteppingMeta * querySteppingMeta()
  9958. {
  9959. return input->querySteppingMeta();
  9960. }
  9961. };
  9962. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9963. {
  9964. public:
  9965. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9966. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9967. {
  9968. }
  9969. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9970. {
  9971. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  9972. }
  9973. };
  9974. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9975. {
  9976. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9977. }
  9978. //=================================================================================
  9979. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9980. {
  9981. IHThorDiskReadArg &helper;
  9982. bool needTransform;
  9983. bool eof;
  9984. bool anyThisGroup;
  9985. unsigned __int64 rowLimit;
  9986. unsigned __int64 choosenLimit;
  9987. public:
  9988. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9989. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9990. {
  9991. needTransform = helper.needTransform();
  9992. rowLimit = (unsigned __int64) -1;
  9993. choosenLimit = 0;
  9994. eof = false;
  9995. anyThisGroup = false;
  9996. }
  9997. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9998. {
  9999. anyThisGroup = false;
  10000. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10001. if (helper.canMatchAny())
  10002. eof = false;
  10003. else
  10004. eof = true;
  10005. choosenLimit = helper.getChooseNLimit();
  10006. rowLimit = helper.getRowLimit();
  10007. helper.setCallback(NULL); // members should not be called - change if they are
  10008. }
  10009. virtual bool needsAllocator() const { return true; }
  10010. virtual const void * nextRow()
  10011. {
  10012. ActivityTimer t(totalCycles, timeActivities);
  10013. if (eof)
  10014. return NULL;
  10015. if (processed==choosenLimit)
  10016. {
  10017. eof = true;
  10018. return NULL;
  10019. }
  10020. if (needTransform)
  10021. {
  10022. loop
  10023. {
  10024. const void *in = inputStream->nextRow();
  10025. if (!in)
  10026. {
  10027. if (anyThisGroup)
  10028. {
  10029. anyThisGroup = false;
  10030. return NULL;
  10031. }
  10032. in = inputStream->nextRow();
  10033. if (!in)
  10034. {
  10035. eof = true;
  10036. return NULL; // eof...
  10037. }
  10038. }
  10039. unsigned outSize;
  10040. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10041. try
  10042. {
  10043. outSize = helper.transform(rowBuilder, in);
  10044. ReleaseRoxieRow(in);
  10045. }
  10046. catch (IException *E)
  10047. {
  10048. throw makeWrappedException(E);
  10049. }
  10050. if (outSize)
  10051. {
  10052. anyThisGroup = true;
  10053. processed++;
  10054. if (processed==rowLimit)
  10055. {
  10056. if (traceLevel > 4)
  10057. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10058. helper.onLimitExceeded();
  10059. }
  10060. return rowBuilder.finalizeRowClear(outSize);
  10061. }
  10062. }
  10063. }
  10064. else
  10065. {
  10066. const void *ret = inputStream->nextRow();
  10067. if (ret)
  10068. {
  10069. processed++;
  10070. if (processed==rowLimit)
  10071. {
  10072. if (traceLevel > 4)
  10073. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10074. ReleaseClearRoxieRow(ret);
  10075. helper.onLimitExceeded(); // should not return
  10076. throwUnexpected();
  10077. }
  10078. }
  10079. return ret;
  10080. }
  10081. }
  10082. };
  10083. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10084. {
  10085. public:
  10086. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10087. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10088. {
  10089. }
  10090. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10091. {
  10092. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10093. }
  10094. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10095. {
  10096. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  10097. setInput(0, source, sourceIdx);
  10098. else
  10099. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10100. }
  10101. };
  10102. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10103. {
  10104. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10105. }
  10106. //=================================================================================
  10107. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10108. {
  10109. public:
  10110. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10111. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10112. {
  10113. }
  10114. ~CRoxieServerSpillWriteActivity()
  10115. {
  10116. }
  10117. virtual const void *nextRow()
  10118. {
  10119. ActivityTimer t(totalCycles, timeActivities);
  10120. return inputStream->nextRow();
  10121. }
  10122. };
  10123. //==================================================================================
  10124. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10125. {
  10126. protected:
  10127. Owned<IExtRowWriter> outSeq;
  10128. Owned<IOutputRowSerializer> rowSerializer;
  10129. Linked<IFileIOStream> diskout;
  10130. bool blockcompressed;
  10131. bool extend;
  10132. bool overwrite;
  10133. bool encrypted;
  10134. bool grouped;
  10135. IHThorDiskWriteArg &helper;
  10136. CachedOutputMetaData diskmeta;
  10137. Owned<IRoxieWriteHandler> writer;
  10138. bool tallycrc;
  10139. unsigned __int64 uncompressedBytesWritten;
  10140. CRC32 crc;
  10141. void updateWorkUnitResult(unsigned __int64 reccount)
  10142. {
  10143. assertex(writer);
  10144. // MORE - a lot of this is common with hthor
  10145. WorkunitUpdate wu = ctx->updateWorkUnit();
  10146. if (wu)
  10147. {
  10148. OwnedRoxieString rawLogicalName = helper.getFileName();
  10149. StringBuffer lfn; // logical filename
  10150. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10151. if (lfn.length())
  10152. {
  10153. unsigned flags = helper.getFlags();
  10154. WUFileKind fileKind;
  10155. if (TDXtemporary & flags)
  10156. fileKind = WUFileTemporary;
  10157. else if(TDXjobtemp & flags)
  10158. fileKind = WUFileJobOwned;
  10159. else if(TDWowned & flags)
  10160. fileKind = WUFileOwned;
  10161. else
  10162. fileKind = WUFileStandard;
  10163. StringArray clusters;
  10164. writer->getClusters(clusters);
  10165. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10166. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10167. {
  10168. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10169. if (result)
  10170. {
  10171. result->setResultTotalRowCount(reccount);
  10172. result->setResultStatus(ResultStatusCalculated);
  10173. if (helper.getFlags() & TDWresult)
  10174. result->setResultFilename(lfn.str());
  10175. else
  10176. result->setResultLogicalName(lfn.str());
  10177. }
  10178. }
  10179. }
  10180. }
  10181. }
  10182. void resolve()
  10183. {
  10184. OwnedRoxieString rawLogicalName = helper.getFileName();
  10185. assertex(rawLogicalName);
  10186. assertex((helper.getFlags() & TDXtemporary) == 0);
  10187. StringArray clusters;
  10188. unsigned clusterIdx = 0;
  10189. while(true)
  10190. {
  10191. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10192. if(!cluster)
  10193. break;
  10194. clusters.append(cluster);
  10195. clusterIdx++;
  10196. }
  10197. if (clusters.length())
  10198. {
  10199. if (extend)
  10200. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10201. }
  10202. else
  10203. {
  10204. if (roxieName.length())
  10205. clusters.append(roxieName.str());
  10206. else
  10207. clusters.append(".");
  10208. }
  10209. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10210. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10211. }
  10212. public:
  10213. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10214. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  10215. {
  10216. extend = ((helper.getFlags() & TDWextend) != 0);
  10217. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10218. grouped = false; // don't think we need to support it...
  10219. diskmeta.set(helper.queryDiskRecordSize());
  10220. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10221. encrypted = false; // set later
  10222. tallycrc = true;
  10223. uncompressedBytesWritten = 0;
  10224. }
  10225. ~CRoxieServerDiskWriteActivity()
  10226. {
  10227. }
  10228. virtual bool needsAllocator() const
  10229. {
  10230. return true;
  10231. }
  10232. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10233. {
  10234. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10235. resolve();
  10236. Owned<IFileIO> io;
  10237. void *ekey;
  10238. size32_t ekeylen;
  10239. helper.getEncryptKey(ekeylen, ekey);
  10240. Owned<ICompressor> ecomp;
  10241. if (ekeylen!=0)
  10242. {
  10243. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10244. memset(ekey,0,ekeylen);
  10245. rtlFree(ekey);
  10246. encrypted = true;
  10247. blockcompressed = true;
  10248. }
  10249. if (blockcompressed)
  10250. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  10251. else
  10252. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10253. if (!io)
  10254. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10255. diskout.setown(createBufferedIOStream(io));
  10256. if (extend)
  10257. diskout->seek(0, IFSend);
  10258. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  10259. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10260. rowSerializer.set(rowIf->queryRowSerializer());
  10261. unsigned rwFlags = rw_autoflush;
  10262. if(grouped)
  10263. rwFlags |= rw_grouped;
  10264. if(tallycrc)
  10265. rwFlags |= rw_crc;
  10266. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10267. }
  10268. virtual void stop()
  10269. {
  10270. if (aborted)
  10271. {
  10272. if (writer)
  10273. writer->finish(false, this);
  10274. }
  10275. else
  10276. {
  10277. if (outSeq)
  10278. outSeq->flush(&crc);
  10279. if (outSeq)
  10280. uncompressedBytesWritten = outSeq->getPosition();
  10281. outSeq.clear();
  10282. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10283. if (writer)
  10284. {
  10285. updateWorkUnitResult(processed);
  10286. writer->finish(true, this);
  10287. }
  10288. }
  10289. writer.clear();
  10290. CRoxieServerActivity::stop();
  10291. }
  10292. virtual void reset()
  10293. {
  10294. CRoxieServerActivity::reset();
  10295. diskout.clear();
  10296. outSeq.clear();
  10297. writer.clear();
  10298. uncompressedBytesWritten = 0;
  10299. crc.reset();
  10300. }
  10301. virtual void onExecute()
  10302. {
  10303. loop
  10304. {
  10305. const void *nextrec = inputStream->ungroupedNextRow();
  10306. if (!nextrec)
  10307. break;
  10308. processed++;
  10309. outSeq->putRow(nextrec);
  10310. }
  10311. }
  10312. virtual void setFileProperties(IFileDescriptor *desc) const
  10313. {
  10314. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10315. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10316. if (blockcompressed)
  10317. {
  10318. // caller has already set @size from file size...
  10319. fileProps.setPropBool("@blockCompressed", true);
  10320. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10321. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10322. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10323. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10324. }
  10325. else if (tallycrc && crc.get())
  10326. partProps.setPropInt64("@fileCrc", crc.get());
  10327. if (encrypted)
  10328. fileProps.setPropBool("@encrypted", true);
  10329. fileProps.setPropInt64("@recordCount", processed);
  10330. unsigned flags = helper.getFlags();
  10331. if (flags & TDWpersist)
  10332. fileProps.setPropBool("@persistent", true);
  10333. if (grouped)
  10334. fileProps.setPropBool("@grouped", true);
  10335. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10336. fileProps.setPropBool("@owned", true);
  10337. if (flags & TDWresult)
  10338. fileProps.setPropBool("@result", true);
  10339. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10340. if (workUnit)
  10341. {
  10342. fileProps.setProp("@owner", workUnit->queryUser());
  10343. fileProps.setProp("@workunit", workUnit->queryWuid());
  10344. fileProps.setProp("@job", workUnit->queryJobName());
  10345. }
  10346. if (flags & TDWexpires)
  10347. setExpiryTime(fileProps, helper.getExpiryDays());
  10348. if (flags & TDWupdate)
  10349. {
  10350. unsigned eclCRC;
  10351. unsigned __int64 totalCRC;
  10352. helper.getUpdateCRCs(eclCRC, totalCRC);
  10353. fileProps.setPropInt("@eclCRC", eclCRC);
  10354. fileProps.setPropInt64("@totalCRC", totalCRC);
  10355. }
  10356. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10357. IRecordSize * inputMeta = input->queryOutputMeta();
  10358. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10359. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10360. const char *recordECL = helper.queryRecordECL();
  10361. if (recordECL && *recordECL)
  10362. fileProps.setProp("ECL", recordECL);
  10363. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10364. }
  10365. virtual IUserDescriptor *queryUserDescriptor() const
  10366. {
  10367. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10368. if (workUnit)
  10369. return workUnit->queryUserDescriptor();
  10370. else
  10371. return NULL;
  10372. }
  10373. virtual bool isOutputTransformed() const { return false; }
  10374. };
  10375. //=================================================================================
  10376. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10377. {
  10378. IHThorCsvWriteArg &csvHelper;
  10379. CSVOutputStream csvOutput;
  10380. public:
  10381. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10382. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10383. {
  10384. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10385. }
  10386. virtual void onExecute()
  10387. {
  10388. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10389. if (header)
  10390. {
  10391. csvOutput.beginLine();
  10392. csvOutput.writeHeaderLn(strlen(header), header);
  10393. diskout->write(csvOutput.length(), csvOutput.str());
  10394. }
  10395. loop
  10396. {
  10397. const void *nextrec = inputStream->ungroupedNextRow();
  10398. if (!nextrec)
  10399. break;
  10400. processed++;
  10401. csvOutput.beginLine();
  10402. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10403. csvOutput.endLine();
  10404. diskout->write(csvOutput.length(), csvOutput.str());
  10405. ReleaseRoxieRow(nextrec);
  10406. }
  10407. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10408. if (footer)
  10409. {
  10410. csvOutput.beginLine();
  10411. csvOutput.writeHeaderLn(strlen(footer), footer);
  10412. diskout->write(csvOutput.length(), csvOutput.str());
  10413. }
  10414. }
  10415. virtual void setFileProperties(IFileDescriptor *desc) const
  10416. {
  10417. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10418. IPropertyTree &props = desc->queryProperties();
  10419. props.setProp("@format","utf8n");
  10420. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10421. StringBuffer separator;
  10422. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10423. const char *s = rs;
  10424. while (s && *s)
  10425. {
  10426. if (',' == *s)
  10427. separator.append("\\,");
  10428. else
  10429. separator.append(*s);
  10430. ++s;
  10431. }
  10432. props.setProp("@csvSeparate", separator.str());
  10433. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10434. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10435. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10436. props.setProp("@kind", "csv");
  10437. }
  10438. virtual bool isOutputTransformed() const { return true; }
  10439. };
  10440. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10441. {
  10442. IHThorXmlWriteArg &xmlHelper;
  10443. StringAttr rowTag;
  10444. ThorActivityKind kind;
  10445. unsigned headerLength;
  10446. unsigned footerLength;
  10447. public:
  10448. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10449. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10450. {
  10451. }
  10452. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10453. {
  10454. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10455. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10456. if (!xmlpath)
  10457. rowTag.set(DEFAULTXMLROWTAG);
  10458. else
  10459. {
  10460. const char *path = xmlpath;
  10461. if (*path == '/') path++;
  10462. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10463. rowTag.set(path);
  10464. }
  10465. }
  10466. virtual void onExecute()
  10467. {
  10468. StringBuffer header;
  10469. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10470. if (kind==TAKjsonwrite)
  10471. buildJsonHeader(header, suppliedHeader, rowTag);
  10472. else if (suppliedHeader)
  10473. header.set(suppliedHeader);
  10474. else
  10475. header.append(DEFAULTXMLHEADER).newline();
  10476. headerLength = header.length();
  10477. diskout->write(header.length(), header.str());
  10478. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10479. writer->outputBeginArray(rowTag); //need to set this
  10480. writer->clear(); //but not output it
  10481. loop
  10482. {
  10483. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10484. if (!nextrec)
  10485. break;
  10486. processed++;
  10487. writer->clear().outputBeginNested(rowTag, false);
  10488. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10489. writer->outputEndNested(rowTag);
  10490. diskout->write(writer->length(), writer->str());
  10491. }
  10492. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10493. StringBuffer footer;
  10494. if (kind==TAKjsonwrite)
  10495. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10496. else if (suppliedFooter)
  10497. footer.append(suppliedFooter);
  10498. else
  10499. footer.append(DEFAULTXMLFOOTER);
  10500. footerLength=footer.length();
  10501. diskout->write(footer.length(), footer);
  10502. }
  10503. virtual void reset()
  10504. {
  10505. CRoxieServerDiskWriteActivity::reset();
  10506. rowTag.clear();
  10507. }
  10508. virtual void setFileProperties(IFileDescriptor *desc) const
  10509. {
  10510. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10511. desc->queryProperties().setProp("@format","utf8n");
  10512. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10513. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10514. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10515. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10516. }
  10517. virtual bool isOutputTransformed() const { return true; }
  10518. };
  10519. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10520. {
  10521. bool isRoot;
  10522. bool isTemp;
  10523. public:
  10524. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10525. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10526. {
  10527. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10528. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10529. setNumOutputs(helper->getTempUsageCount());
  10530. if (_kind!=TAKdiskwrite)
  10531. assertex(numOutputs == 0);
  10532. }
  10533. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10534. {
  10535. switch (numOutputs)
  10536. {
  10537. case 0:
  10538. switch (kind)
  10539. {
  10540. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10541. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10542. case TAKxmlwrite:
  10543. case TAKjsonwrite:
  10544. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10545. };
  10546. throwUnexpected();
  10547. case 1:
  10548. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10549. default:
  10550. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10551. }
  10552. }
  10553. virtual bool isSink() const
  10554. {
  10555. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10556. }
  10557. };
  10558. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10559. {
  10560. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10561. }
  10562. //=================================================================================
  10563. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10564. {
  10565. IHThorIndexWriteArg &helper;
  10566. bool overwrite;
  10567. Owned<ClusterWriteHandler> clusterHandler;
  10568. Owned<IRoxieWriteHandler> writer;
  10569. unsigned __int64 reccount;
  10570. unsigned int fileCrc;
  10571. StringBuffer filename;
  10572. void updateWorkUnitResult()
  10573. {
  10574. // MORE - a lot of this is common with hthor
  10575. WorkunitUpdate wu = ctx->updateWorkUnit();
  10576. if (wu)
  10577. {
  10578. OwnedRoxieString rawLogicalName = helper.getFileName();
  10579. StringBuffer lfn; // logical filename
  10580. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10581. if (lfn.length())
  10582. {
  10583. if (helper.getSequence() >= 0)
  10584. {
  10585. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10586. if (result)
  10587. {
  10588. result->setResultTotalRowCount(reccount);
  10589. result->setResultStatus(ResultStatusCalculated);
  10590. result->setResultLogicalName(lfn.str());
  10591. }
  10592. }
  10593. if(clusterHandler)
  10594. clusterHandler->finish(writer->queryFile());
  10595. CTXLOG("Created roxie index file %s", lfn.str());
  10596. }
  10597. }
  10598. }
  10599. virtual void resolve()
  10600. {
  10601. StringArray clusters;
  10602. unsigned clusterIdx = 0;
  10603. while(true)
  10604. {
  10605. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10606. if(!cluster)
  10607. break;
  10608. clusters.append(cluster);
  10609. clusterIdx++;
  10610. }
  10611. if (roxieName.length())
  10612. clusters.append(roxieName.str());
  10613. else
  10614. clusters.append(".");
  10615. OwnedRoxieString fname(helper.getFileName());
  10616. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10617. filename.set(writer->queryFile()->queryFilename());
  10618. if (writer->queryFile()->exists())
  10619. {
  10620. if (overwrite)
  10621. {
  10622. CTXLOG("Removing existing %s from DFS",filename.str());
  10623. writer->queryFile()->remove();
  10624. }
  10625. else
  10626. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10627. }
  10628. }
  10629. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10630. {
  10631. size32_t nameLen;
  10632. char * nameBuff;
  10633. size32_t valueLen;
  10634. char * valueBuff;
  10635. unsigned idx = 0;
  10636. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10637. {
  10638. StringBuffer name(nameLen, nameBuff);
  10639. StringBuffer value(valueLen, valueBuff);
  10640. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10641. {
  10642. OwnedRoxieString fname(helper.getFileName());
  10643. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10644. }
  10645. if(!validateXMLTag(name.str()))
  10646. {
  10647. OwnedRoxieString fname(helper.getFileName());
  10648. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10649. }
  10650. if(!metadata)
  10651. metadata.setown(createPTree("metadata"));
  10652. metadata->setProp(name.str(), value.str());
  10653. }
  10654. }
  10655. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10656. {
  10657. if(!metadata)
  10658. metadata.setown(createPTree("metadata"));
  10659. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10660. void * layoutMetaBuff;
  10661. size32_t layoutMetaSize;
  10662. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10663. {
  10664. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10665. rtlFree(layoutMetaBuff);
  10666. }
  10667. }
  10668. public:
  10669. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10670. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10671. {
  10672. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10673. reccount = 0;
  10674. fileCrc = 0;
  10675. }
  10676. ~CRoxieServerIndexWriteActivity()
  10677. {
  10678. }
  10679. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10680. {
  10681. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10682. resolve();
  10683. }
  10684. virtual void onExecute()
  10685. {
  10686. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10687. size32_t maxDiskRecordSize;
  10688. if (isVariable)
  10689. {
  10690. if (helper.getFlags() & TIWmaxlength)
  10691. maxDiskRecordSize = helper.getMaxKeySize();
  10692. else
  10693. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10694. }
  10695. else
  10696. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10697. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10698. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10699. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10700. fileCrc = -1;
  10701. {
  10702. Owned<IFileIO> io;
  10703. try
  10704. {
  10705. io.setown(writer->queryFile()->open(IFOcreate));
  10706. }
  10707. catch(IException * e)
  10708. {
  10709. e->Release();
  10710. clearKeyStoreCache(false);
  10711. io.setown(writer->queryFile()->open(IFOcreate));
  10712. }
  10713. if(!io)
  10714. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10715. Owned<IFileIOStream> out = createIOStream(io);
  10716. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10717. if (helper.getFlags() & TIWrowcompress)
  10718. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10719. else if (!(helper.getFlags() & TIWnolzwcompress))
  10720. flags |= HTREE_COMPRESSED_KEY;
  10721. if (isVariable)
  10722. flags |= HTREE_VARSIZE;
  10723. Owned<IPropertyTree> metadata;
  10724. buildUserMetadata(metadata);
  10725. buildLayoutMetadata(metadata);
  10726. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10727. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10728. class BcWrapper : implements IBlobCreator
  10729. {
  10730. IKeyBuilder *builder;
  10731. public:
  10732. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10733. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10734. {
  10735. return builder->createBlob(size, (const char *) ptr);
  10736. }
  10737. } bc(builder);
  10738. // Loop thru the results
  10739. loop
  10740. {
  10741. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10742. if (!nextrec)
  10743. break;
  10744. try
  10745. {
  10746. unsigned __int64 fpos=0;
  10747. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10748. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10749. builder->processKeyData(rowBuffer, fpos, thisSize);
  10750. }
  10751. catch(IException * e)
  10752. {
  10753. throw makeWrappedException(e);
  10754. }
  10755. reccount++;
  10756. }
  10757. if(metadata)
  10758. builder->finish(metadata,&fileCrc);
  10759. else
  10760. builder->finish(&fileCrc);
  10761. }
  10762. }
  10763. virtual void stop()
  10764. {
  10765. if (writer)
  10766. {
  10767. if (!aborted)
  10768. updateWorkUnitResult();
  10769. writer->finish(!aborted, this);
  10770. writer.clear();
  10771. }
  10772. CRoxieServerActivity::stop();
  10773. }
  10774. virtual void reset()
  10775. {
  10776. CRoxieServerActivity::reset();
  10777. writer.clear();
  10778. }
  10779. //interface IRoxiePublishCallback
  10780. virtual void setFileProperties(IFileDescriptor *desc) const
  10781. {
  10782. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10783. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10784. // Now publish to name services
  10785. StringBuffer dir,base;
  10786. offset_t indexFileSize = writer->queryFile()->size();
  10787. if(clusterHandler)
  10788. clusterHandler->splitPhysicalFilename(dir, base);
  10789. else
  10790. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10791. desc->setDefaultDir(dir.str());
  10792. //properties of the first file part.
  10793. Owned<IPropertyTree> attrs;
  10794. if(clusterHandler)
  10795. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10796. else
  10797. {
  10798. // add cluster
  10799. StringBuffer mygroupname;
  10800. desc->setNumParts(1);
  10801. desc->setPartMask(base.str());
  10802. attrs.set(&desc->queryPart(0)->queryProperties());
  10803. }
  10804. attrs->setPropInt64("@size", indexFileSize);
  10805. CDateTime createTime, modifiedTime, accessedTime;
  10806. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10807. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10808. unsigned hour, min, sec, nanosec;
  10809. modifiedTime.getTime(hour, min, sec, nanosec);
  10810. modifiedTime.setTime(hour, min, sec, 0);
  10811. StringBuffer timestr;
  10812. modifiedTime.getString(timestr);
  10813. if(timestr.length())
  10814. attrs->setProp("@modified", timestr.str());
  10815. if(clusterHandler)
  10816. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10817. // properties of the logical file
  10818. IPropertyTree & properties = desc->queryProperties();
  10819. properties.setProp("@kind", "key");
  10820. properties.setPropInt64("@size", indexFileSize);
  10821. properties.setPropInt64("@recordCount", reccount);
  10822. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10823. if (workUnit)
  10824. {
  10825. properties.setProp("@owner", workUnit->queryUser());
  10826. properties.setProp("@workunit", workUnit->queryWuid());
  10827. properties.setProp("@job", workUnit->queryJobName());
  10828. }
  10829. char const * rececl = helper.queryRecordECL();
  10830. if(rececl && *rececl)
  10831. properties.setProp("ECL", rececl);
  10832. if (helper.getFlags() & TIWexpires)
  10833. setExpiryTime(properties, helper.getExpiryDays());
  10834. if (helper.getFlags() & TIWupdate)
  10835. {
  10836. unsigned eclCRC;
  10837. unsigned __int64 totalCRC;
  10838. helper.getUpdateCRCs(eclCRC, totalCRC);
  10839. properties.setPropInt("@eclCRC", eclCRC);
  10840. properties.setPropInt64("@totalCRC", totalCRC);
  10841. }
  10842. properties.setPropInt("@fileCrc", fileCrc);
  10843. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10844. void * layoutMetaBuff;
  10845. size32_t layoutMetaSize;
  10846. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10847. {
  10848. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10849. rtlFree(layoutMetaBuff);
  10850. }
  10851. }
  10852. IUserDescriptor *queryUserDescriptor() const
  10853. {
  10854. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10855. if (workUnit)
  10856. return workUnit->queryUserDescriptor();
  10857. else
  10858. return NULL;
  10859. }
  10860. };
  10861. //=================================================================================
  10862. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10863. {
  10864. public:
  10865. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10866. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10867. {
  10868. setNumOutputs(0);
  10869. }
  10870. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10871. {
  10872. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  10873. }
  10874. virtual bool isSink() const
  10875. {
  10876. return true;
  10877. }
  10878. };
  10879. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10880. {
  10881. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10882. }
  10883. //=================================================================================
  10884. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10885. {
  10886. if((flags & JFmatchAbortLimitSkips) != 0)
  10887. {
  10888. limitFail = false;
  10889. limitOnFail = false;
  10890. }
  10891. else
  10892. {
  10893. limitOnFail = ((flags & JFonfail) != 0);
  10894. limitFail = !limitOnFail;
  10895. }
  10896. }
  10897. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10898. {
  10899. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10900. IHThorJoinArg &helper;
  10901. ICompare * collate;
  10902. ICompare * collateupper;
  10903. ThorActivityKind activityKind;
  10904. bool leftOuterJoin;
  10905. bool rightOuterJoin;
  10906. bool exclude;
  10907. bool limitFail;
  10908. bool limitOnFail;
  10909. bool forceSpill;
  10910. unsigned keepLimit;
  10911. unsigned joinLimit;
  10912. unsigned atmostLimit;
  10913. unsigned abortLimit;
  10914. unsigned atmostsTriggered;
  10915. bool betweenjoin;
  10916. OwnedRowArray right;
  10917. const void * left;
  10918. const void * pendingRight;
  10919. unsigned rightIndex;
  10920. unsigned joinCounter;
  10921. BoolArray matchedRight;
  10922. bool matchedLeft;
  10923. Owned<IException> failingLimit;
  10924. ConstPointerArray filteredRight;
  10925. Owned<IRHLimitedCompareHelper> limitedhelper;
  10926. OwnedConstRoxieRow defaultLeft;
  10927. OwnedConstRoxieRow defaultRight;
  10928. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10929. Owned<IEngineRowAllocator> defaultRightAllocator;
  10930. Owned<IGroupedInput> sortedLeft;
  10931. Owned<IGroupedInput> groupedSortedRight;
  10932. bool cloneLeft;
  10933. void createDefaultLeft()
  10934. {
  10935. if (!defaultLeft)
  10936. {
  10937. if (!defaultLeftAllocator)
  10938. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  10939. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10940. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10941. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10942. }
  10943. }
  10944. void createDefaultRight()
  10945. {
  10946. if (!defaultRight)
  10947. {
  10948. if (!defaultRightAllocator)
  10949. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  10950. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10951. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10952. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10953. }
  10954. }
  10955. public:
  10956. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  10957. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  10958. {
  10959. // MORE - some of this should be done in factory
  10960. unsigned joinFlags = helper.getJoinFlags();
  10961. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10962. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10963. exclude = (joinFlags & JFexclude) != 0;
  10964. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10965. getLimitType(joinFlags, limitFail, limitOnFail);
  10966. if (joinFlags & JFslidingmatch)
  10967. {
  10968. betweenjoin = true;
  10969. collate = helper.queryCompareLeftRightLower();
  10970. collateupper = helper.queryCompareLeftRightUpper();
  10971. }
  10972. else
  10973. {
  10974. betweenjoin = false;
  10975. collate = collateupper = helper.queryCompareLeftRight();
  10976. }
  10977. rightIndex = 0;
  10978. joinCounter = 0;
  10979. state = JSfill;
  10980. matchedLeft = false;
  10981. joinLimit = 0;
  10982. keepLimit = 0; // wait until ctx available
  10983. atmostLimit = 0; // wait until ctx available
  10984. abortLimit = 0; // wait until ctx available
  10985. atmostsTriggered = 0;
  10986. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10987. left = NULL;
  10988. pendingRight = NULL;
  10989. activityKind = _factory->getKind();
  10990. }
  10991. virtual bool needsAllocator() const { return true; }
  10992. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10993. {
  10994. left = NULL;
  10995. rightIndex = 0;
  10996. joinCounter = 0;
  10997. state = JSfill;
  10998. matchedLeft = false;
  10999. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11000. keepLimit = helper.getKeepLimit();
  11001. if (keepLimit == 0)
  11002. keepLimit = (unsigned)-1;
  11003. atmostsTriggered = 0;
  11004. atmostLimit = helper.getJoinLimit();
  11005. if(atmostLimit == 0)
  11006. atmostLimit = (unsigned)-1;
  11007. else
  11008. assertex(!rightOuterJoin && !betweenjoin);
  11009. abortLimit = helper.getMatchAbortLimit();
  11010. if (abortLimit == 0)
  11011. abortLimit = (unsigned)-1;
  11012. if (rightOuterJoin)
  11013. createDefaultLeft();
  11014. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11015. createDefaultRight();
  11016. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11017. RoxieSortAlgorithm sortAlgorithm;
  11018. if (forceSpill)
  11019. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11020. else
  11021. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11022. if (helper.isLeftAlreadySorted())
  11023. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11024. else
  11025. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11026. ICompare *compareRight = helper.queryCompareRight();
  11027. if (helper.isRightAlreadySorted())
  11028. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11029. else
  11030. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11031. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11032. { //limited match join (s[1..n])
  11033. limitedhelper.setown(createRHLimitedCompareHelper());
  11034. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11035. }
  11036. }
  11037. virtual void reset()
  11038. {
  11039. if (atmostsTriggered)
  11040. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11041. right.clear();
  11042. ReleaseClearRoxieRow(left);
  11043. ReleaseClearRoxieRow(pendingRight);
  11044. defaultRight.clear();
  11045. defaultLeft.clear();
  11046. sortedLeft.clear();
  11047. groupedSortedRight.clear();
  11048. CRoxieServerTwoInputActivity::reset();
  11049. }
  11050. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11051. {
  11052. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11053. {
  11054. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11055. puller->setInput(0, _sourceIdx, _in);
  11056. _in = puller;
  11057. _sourceIdx = 0;
  11058. }
  11059. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11060. }
  11061. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11062. {
  11063. if (idx==(unsigned)-1)
  11064. idx = 0;
  11065. return idx ? NULL : this;
  11066. }
  11067. void fillLeft()
  11068. {
  11069. matchedLeft = false;
  11070. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11071. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11072. fillRight();
  11073. if (limitedhelper && 0==rightIndex)
  11074. {
  11075. rightIndex = 0;
  11076. joinCounter = 0;
  11077. right.clear();
  11078. matchedRight.kill();
  11079. if (left)
  11080. {
  11081. limitedhelper->getGroup(right,left);
  11082. ForEachItemIn(idx, right)
  11083. matchedRight.append(false);
  11084. }
  11085. }
  11086. }
  11087. void fillRight()
  11088. {
  11089. if (limitedhelper)
  11090. return;
  11091. failingLimit.clear();
  11092. if(betweenjoin && left)
  11093. {
  11094. aindex_t start = 0;
  11095. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11096. start++;
  11097. if(start>0)
  11098. right.clearPart(0, start);
  11099. }
  11100. else
  11101. right.clear();
  11102. rightIndex = 0;
  11103. joinCounter = 0;
  11104. unsigned groupCount = 0;
  11105. const void * next;
  11106. while(true)
  11107. {
  11108. if(pendingRight)
  11109. {
  11110. next = pendingRight;
  11111. pendingRight = NULL;
  11112. }
  11113. else
  11114. {
  11115. next = groupedSortedRight->nextRow();
  11116. }
  11117. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11118. {
  11119. while(next)
  11120. {
  11121. ReleaseClearRoxieRow(next);
  11122. next = groupedSortedRight->nextRow();
  11123. }
  11124. continue;
  11125. }
  11126. while(next)
  11127. {
  11128. if(groupCount==abortLimit)
  11129. {
  11130. if(limitFail)
  11131. failLimit();
  11132. if (ctx->queryDebugContext())
  11133. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11134. if(limitOnFail)
  11135. {
  11136. assertex(!failingLimit);
  11137. try
  11138. {
  11139. failLimit();
  11140. }
  11141. catch(IException * except)
  11142. {
  11143. failingLimit.setown(except);
  11144. }
  11145. assertex(failingLimit != NULL);
  11146. }
  11147. right.append(next);
  11148. do
  11149. {
  11150. next = groupedSortedRight->nextRow();
  11151. ReleaseRoxieRow(next);
  11152. } while(next);
  11153. break;
  11154. }
  11155. else if(groupCount==atmostLimit)
  11156. {
  11157. atmostsTriggered++;
  11158. right.clear();
  11159. groupCount = 0;
  11160. while(next)
  11161. {
  11162. ReleaseRoxieRow(next);
  11163. next = groupedSortedRight->nextRow();
  11164. }
  11165. }
  11166. else
  11167. {
  11168. right.append(next);
  11169. groupCount++;
  11170. }
  11171. next = groupedSortedRight->nextRow();
  11172. }
  11173. // 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
  11174. if(betweenjoin && left)
  11175. {
  11176. pendingRight = groupedSortedRight->nextRow();
  11177. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11178. break;
  11179. }
  11180. else
  11181. break;
  11182. }
  11183. matchedRight.kill();
  11184. ForEachItemIn(idx, right)
  11185. matchedRight.append(false);
  11186. }
  11187. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  11188. {
  11189. if (cloneLeft)
  11190. {
  11191. LinkRoxieRow(curLeft);
  11192. return curLeft;
  11193. }
  11194. try
  11195. {
  11196. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11197. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  11198. if (thisSize)
  11199. return rowBuilder.finalizeRowClear(thisSize);
  11200. else
  11201. return NULL;
  11202. }
  11203. catch (IException *E)
  11204. {
  11205. throw makeWrappedException(E);
  11206. }
  11207. }
  11208. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  11209. {
  11210. try
  11211. {
  11212. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11213. unsigned numRows = rows.ordinality();
  11214. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11215. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  11216. if (thisSize)
  11217. return rowBuilder.finalizeRowClear(thisSize);
  11218. else
  11219. return NULL;
  11220. }
  11221. catch (IException *E)
  11222. {
  11223. throw makeWrappedException(E);
  11224. }
  11225. }
  11226. const void * joinException(const void * curLeft, IException * except)
  11227. {
  11228. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11229. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  11230. return rowBuilder.finalizeRowClear(thisSize);
  11231. }
  11232. void failLimit()
  11233. {
  11234. helper.onMatchAbortLimitExceeded();
  11235. CommonXmlWriter xmlwrite(0);
  11236. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11237. {
  11238. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11239. }
  11240. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11241. }
  11242. virtual const void * nextRow()
  11243. {
  11244. ActivityTimer t(totalCycles, timeActivities);
  11245. loop
  11246. {
  11247. switch (state)
  11248. {
  11249. case JSfill:
  11250. fillLeft();
  11251. state = JSfillright;
  11252. break;
  11253. case JSfillright:
  11254. fillRight();
  11255. state = JScollate;
  11256. break;
  11257. case JSfillleft:
  11258. fillLeft();
  11259. state = JScollate;
  11260. break;
  11261. case JScollate:
  11262. if (right.ordinality() == 0)
  11263. {
  11264. if (left == NULL)
  11265. return NULL;
  11266. state = JSleftonly;
  11267. }
  11268. else
  11269. {
  11270. if (!left)
  11271. state = JSrightonly;
  11272. else
  11273. {
  11274. int diff;
  11275. if(betweenjoin)
  11276. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11277. else
  11278. diff = collate->docompare(left, right.item(0));
  11279. bool limitExceeded = right.ordinality()>abortLimit;
  11280. if (diff == 0)
  11281. {
  11282. if (limitExceeded)
  11283. {
  11284. const void * ret = NULL;
  11285. if(failingLimit)
  11286. ret = joinException(left, failingLimit);
  11287. ReleaseRoxieRow(left);
  11288. left = NULL;
  11289. state = JSfillleft;
  11290. ForEachItemIn(idx, right)
  11291. matchedRight.replace(true, idx);
  11292. if(ret)
  11293. {
  11294. processed++;
  11295. return ret;
  11296. }
  11297. }
  11298. else
  11299. {
  11300. state = JScompare;
  11301. joinLimit = keepLimit;
  11302. }
  11303. }
  11304. else if (diff < 0)
  11305. state = JSleftonly;
  11306. else if (limitExceeded)
  11307. {
  11308. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11309. state = JSfillright;
  11310. }
  11311. else
  11312. state = JSrightonly;
  11313. }
  11314. }
  11315. break;
  11316. case JSrightonly:
  11317. if (rightOuterJoin)
  11318. {
  11319. switch (activityKind)
  11320. {
  11321. case TAKjoin:
  11322. {
  11323. while (right.isItem(rightIndex))
  11324. {
  11325. if (!matchedRight.item(rightIndex))
  11326. {
  11327. const void * rhs = right.item(rightIndex++);
  11328. const void *ret = joinRecords(defaultLeft, rhs, 0);
  11329. if (ret)
  11330. {
  11331. processed++;
  11332. return ret;
  11333. }
  11334. }
  11335. else
  11336. rightIndex++;
  11337. }
  11338. break;
  11339. }
  11340. //Probably excessive to implement the following, but possibly useful
  11341. case TAKdenormalize:
  11342. {
  11343. OwnedConstRoxieRow newLeft;
  11344. newLeft.set(defaultLeft);
  11345. unsigned rowSize = 0;
  11346. unsigned leftCount = 0;
  11347. while (right.isItem(rightIndex))
  11348. {
  11349. if (!matchedRight.item(rightIndex))
  11350. {
  11351. const void * rhs = right.item(rightIndex);
  11352. try
  11353. {
  11354. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11355. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11356. if (thisSize)
  11357. {
  11358. rowSize = thisSize;
  11359. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11360. }
  11361. }
  11362. catch (IException *E)
  11363. {
  11364. throw makeWrappedException(E);
  11365. }
  11366. }
  11367. rightIndex++;
  11368. }
  11369. state = JSfillright;
  11370. if (rowSize)
  11371. {
  11372. processed++;
  11373. return newLeft.getClear();
  11374. }
  11375. break;
  11376. }
  11377. case TAKdenormalizegroup:
  11378. {
  11379. filteredRight.kill();
  11380. while (right.isItem(rightIndex))
  11381. {
  11382. if (!matchedRight.item(rightIndex))
  11383. filteredRight.append(right.item(rightIndex));
  11384. rightIndex++;
  11385. }
  11386. state = JSfillright;
  11387. if (filteredRight.ordinality())
  11388. {
  11389. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  11390. filteredRight.kill();
  11391. if (ret)
  11392. {
  11393. processed++;
  11394. return ret;
  11395. }
  11396. }
  11397. break;
  11398. }
  11399. }
  11400. }
  11401. state = JSfillright;
  11402. break;
  11403. case JSleftonly:
  11404. {
  11405. const void * ret = NULL;
  11406. if (!matchedLeft && leftOuterJoin)
  11407. {
  11408. switch (activityKind)
  11409. {
  11410. case TAKjoin:
  11411. ret = joinRecords(left, defaultRight, 0);
  11412. break;
  11413. case TAKdenormalize:
  11414. ret = left;
  11415. left = NULL;
  11416. break;
  11417. case TAKdenormalizegroup:
  11418. filteredRight.kill();
  11419. ret = denormalizeRecords(left, filteredRight);
  11420. break;
  11421. }
  11422. }
  11423. ReleaseRoxieRow(left);
  11424. left = NULL;
  11425. state = JSfillleft;
  11426. if (ret)
  11427. {
  11428. processed++;
  11429. return ret;
  11430. }
  11431. break;
  11432. }
  11433. case JScompare:
  11434. if (joinLimit != 0)
  11435. {
  11436. switch (activityKind)
  11437. {
  11438. case TAKjoin:
  11439. {
  11440. while (right.isItem(rightIndex))
  11441. {
  11442. const void * rhs = right.item(rightIndex++);
  11443. if (helper.match(left, rhs))
  11444. {
  11445. matchedRight.replace(true, rightIndex-1);
  11446. matchedLeft = true;
  11447. if (!exclude)
  11448. {
  11449. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11450. if (ret)
  11451. {
  11452. processed++;
  11453. joinLimit--;
  11454. return ret;
  11455. }
  11456. }
  11457. }
  11458. }
  11459. break;
  11460. }
  11461. case TAKdenormalize:
  11462. {
  11463. OwnedConstRoxieRow newLeft;
  11464. newLeft.set(left);
  11465. unsigned rowSize = 0;
  11466. unsigned leftCount = 0;
  11467. while (right.isItem(rightIndex) && joinLimit)
  11468. {
  11469. try
  11470. {
  11471. const void * rhs = right.item(rightIndex++);
  11472. if (helper.match(left, rhs))
  11473. {
  11474. matchedRight.replace(true, rightIndex-1);
  11475. matchedLeft = true;
  11476. if (!exclude)
  11477. {
  11478. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11479. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11480. if (thisSize)
  11481. {
  11482. rowSize = thisSize;
  11483. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11484. joinLimit--;
  11485. }
  11486. }
  11487. }
  11488. }
  11489. catch (IException *E)
  11490. {
  11491. throw makeWrappedException(E);
  11492. }
  11493. }
  11494. state = JSleftonly;
  11495. rightIndex = 0;
  11496. if (rowSize)
  11497. {
  11498. processed++;
  11499. return newLeft.getClear();
  11500. }
  11501. break;
  11502. }
  11503. case TAKdenormalizegroup:
  11504. {
  11505. filteredRight.kill();
  11506. while (right.isItem(rightIndex))
  11507. {
  11508. const void * rhs = right.item(rightIndex++);
  11509. if (helper.match(left, rhs))
  11510. {
  11511. matchedRight.replace(true, rightIndex-1);
  11512. filteredRight.append(rhs);
  11513. matchedLeft = true;
  11514. if (filteredRight.ordinality()==joinLimit)
  11515. break;
  11516. }
  11517. }
  11518. state = JSleftonly;
  11519. rightIndex = 0;
  11520. if (!exclude && filteredRight.ordinality())
  11521. {
  11522. const void * ret = denormalizeRecords(left, filteredRight);
  11523. filteredRight.kill();
  11524. if (ret)
  11525. {
  11526. processed++;
  11527. return ret;
  11528. }
  11529. }
  11530. break;
  11531. }
  11532. }
  11533. }
  11534. state = JSleftonly;
  11535. rightIndex = 0;
  11536. joinCounter = 0;
  11537. break;
  11538. }
  11539. }
  11540. }
  11541. };
  11542. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11543. {
  11544. unsigned input2;
  11545. unsigned input2idx;
  11546. bool forceSpill;
  11547. public:
  11548. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11549. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11550. {
  11551. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11552. input2 = 0;
  11553. input2idx = 0;
  11554. }
  11555. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11556. {
  11557. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11558. }
  11559. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11560. {
  11561. if (idx==1)
  11562. {
  11563. input2 = source;
  11564. input2idx = sourceidx;
  11565. }
  11566. else
  11567. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11568. }
  11569. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11570. {
  11571. switch (idx)
  11572. {
  11573. case 1:
  11574. sourceidx = input2idx;
  11575. return input2;
  11576. case 0:
  11577. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11578. default:
  11579. return (unsigned) -1;
  11580. }
  11581. }
  11582. virtual unsigned numInputs() const { return 2; }
  11583. virtual const StatisticsMapping &queryStatsMapping() const
  11584. {
  11585. return joinStatistics;
  11586. }
  11587. };
  11588. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11589. {
  11590. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11591. }
  11592. //=================================================================================
  11593. #define CONCAT_READAHEAD 1000
  11594. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11595. {
  11596. public:
  11597. IMPLEMENT_IINTERFACE;
  11598. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11599. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11600. {
  11601. }
  11602. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11603. {
  11604. space.reinit(CONCAT_READAHEAD);
  11605. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11606. }
  11607. void stop()
  11608. {
  11609. space.interrupt();
  11610. puller.stop();
  11611. }
  11612. IFinalRoxieInput *queryInput() const
  11613. {
  11614. return puller.queryInput();
  11615. }
  11616. void reset()
  11617. {
  11618. puller.reset();
  11619. ForEachItemIn(idx, buffer)
  11620. ReleaseRoxieRow(buffer.item(idx));
  11621. buffer.clear();
  11622. eof = false;
  11623. atEog = true;
  11624. }
  11625. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11626. {
  11627. puller.setInput(this, _sourceIdx, _in);
  11628. }
  11629. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11630. {
  11631. puller.connectInputStreams(ctx, consumerOrdered);
  11632. }
  11633. virtual void processRow(const void *row)
  11634. {
  11635. buffer.enqueue(row);
  11636. ready.signal();
  11637. space.wait();
  11638. }
  11639. virtual void processGroup(const ConstPointerArray &rows)
  11640. {
  11641. // We use record-by-record input mode of the puller thread even in grouped mode.
  11642. throwUnexpected();
  11643. }
  11644. virtual void processEOG()
  11645. {
  11646. if (grouped)
  11647. processRow(NULL);
  11648. }
  11649. virtual void processDone()
  11650. {
  11651. processRow(NULL);
  11652. }
  11653. virtual bool fireException(IException *e)
  11654. {
  11655. // called from puller thread on failure
  11656. ready.interrupt(LINK(e));
  11657. space.interrupt(e);
  11658. return true;
  11659. }
  11660. bool peek(const void * &row, bool &anyActive)
  11661. {
  11662. if (!eof)
  11663. {
  11664. if (buffer.ordinality())
  11665. {
  11666. space.signal();
  11667. row = buffer.dequeue();
  11668. if (row==NULL)
  11669. {
  11670. if (atEog)
  11671. {
  11672. eof = true;
  11673. return false;
  11674. }
  11675. else
  11676. atEog = true;
  11677. }
  11678. else if (grouped)
  11679. atEog = false;
  11680. return true;
  11681. }
  11682. anyActive = true;
  11683. }
  11684. return false;
  11685. }
  11686. protected:
  11687. RecordPullerThread puller;
  11688. InterruptableSemaphore space;
  11689. InterruptableSemaphore &ready;
  11690. SafeQueueOf<const void, true> buffer;
  11691. bool atEog;
  11692. bool eof;
  11693. bool grouped;
  11694. };
  11695. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11696. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11697. {
  11698. InterruptableSemaphore ready;
  11699. ReaderArray pullers;
  11700. unsigned numInputs;
  11701. unsigned nextPuller; // for round robin
  11702. unsigned readyPending;
  11703. bool eof;
  11704. bool inGroup;
  11705. bool grouped;
  11706. public:
  11707. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11708. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11709. {
  11710. numInputs = _numInputs;
  11711. eof = (numInputs==0);
  11712. inGroup = false;
  11713. nextPuller = 0;
  11714. readyPending = 0;
  11715. for (unsigned i = 0; i < numInputs; i++)
  11716. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11717. }
  11718. ~CRoxieServerThreadedConcatActivity()
  11719. {
  11720. ForEachItemIn(idx, pullers)
  11721. delete &pullers.item(idx);
  11722. }
  11723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11724. {
  11725. eof = (numInputs==0);
  11726. inGroup = false;
  11727. nextPuller = 0;
  11728. readyPending = 0;
  11729. ready.reinit();
  11730. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11731. ForEachItemIn(idx, pullers)
  11732. {
  11733. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11734. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11735. // in the part of the subgraph that the thread uses has been started.
  11736. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11737. }
  11738. }
  11739. virtual void stop()
  11740. {
  11741. ready.interrupt();
  11742. ForEachItemIn(idx, pullers)
  11743. pullers.item(idx).stop();
  11744. CRoxieServerActivity::stop();
  11745. }
  11746. virtual unsigned __int64 queryLocalCycles() const
  11747. {
  11748. return 0;
  11749. }
  11750. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11751. {
  11752. if (pullers.isItem(idx))
  11753. return pullers.item(idx).queryInput();
  11754. else
  11755. return NULL;
  11756. }
  11757. virtual void reset()
  11758. {
  11759. CRoxieServerActivity::reset();
  11760. ForEachItemIn(idx, pullers)
  11761. pullers.item(idx).reset();
  11762. eof = false;
  11763. inGroup = false;
  11764. nextPuller = 0;
  11765. readyPending = 0;
  11766. }
  11767. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11768. {
  11769. if (pullers.isItem(idx))
  11770. pullers.item(idx).setInput(_sourceIdx, _in);
  11771. else
  11772. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  11773. }
  11774. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  11775. {
  11776. ForEachItemIn(i, pullers)
  11777. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  11778. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  11779. }
  11780. virtual const void * nextRow()
  11781. {
  11782. ActivityTimer t(totalCycles, timeActivities);
  11783. if (eof)
  11784. return NULL;
  11785. loop
  11786. {
  11787. if (readyPending && !inGroup)
  11788. {
  11789. if (readyPending > 1)
  11790. ready.signal(readyPending-1);
  11791. readyPending = 0;
  11792. }
  11793. else
  11794. ready.wait();
  11795. bool anyActive = false;
  11796. ForEachItemIn(unused_index, pullers)
  11797. {
  11798. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11799. const void *ret;
  11800. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11801. if (fetched)
  11802. {
  11803. inGroup = (ret != NULL);
  11804. return ret;
  11805. }
  11806. if (inGroup && grouped)
  11807. {
  11808. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11809. readyPending++;
  11810. anyActive = true;
  11811. break;
  11812. }
  11813. nextPuller++;
  11814. if (nextPuller==pullers.ordinality())
  11815. nextPuller = 0;
  11816. }
  11817. if (!anyActive)
  11818. break;
  11819. // A ready signal without anything being ready means someone reached end-of-file.
  11820. }
  11821. eof = true;
  11822. return NULL;
  11823. }
  11824. };
  11825. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  11826. {
  11827. IEngineRowStream *curStream;
  11828. bool eogSeen;
  11829. bool anyThisGroup;
  11830. bool grouped;
  11831. unsigned streamIdx;
  11832. public:
  11833. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11834. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  11835. {
  11836. eogSeen = false;
  11837. anyThisGroup = false;
  11838. grouped = _grouped;
  11839. streamIdx = 0;
  11840. curStream = NULL;
  11841. }
  11842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11843. {
  11844. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11845. streamIdx = 0;
  11846. curStream = streamArray[streamIdx];
  11847. eogSeen = false;
  11848. anyThisGroup = false;
  11849. }
  11850. virtual const void * nextRow()
  11851. {
  11852. ActivityTimer t(totalCycles, timeActivities);
  11853. if (!curStream)
  11854. return NULL; // eof
  11855. const void * next = curStream->nextRow();
  11856. if (next)
  11857. {
  11858. anyThisGroup = true;
  11859. eogSeen = false;
  11860. processed++;
  11861. return next;
  11862. }
  11863. else if (!eogSeen)
  11864. {
  11865. eogSeen = true;
  11866. if (grouped)
  11867. {
  11868. if (anyThisGroup)
  11869. {
  11870. anyThisGroup = false;
  11871. return NULL;
  11872. }
  11873. else
  11874. return nextRow();
  11875. }
  11876. else
  11877. return nextRow();
  11878. }
  11879. else if (streamIdx < numStreams-1)
  11880. {
  11881. streamIdx++;
  11882. curStream = streamArray[streamIdx];
  11883. eogSeen = false;
  11884. return nextRow();
  11885. }
  11886. else
  11887. {
  11888. curStream = NULL;
  11889. return NULL;
  11890. }
  11891. }
  11892. };
  11893. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11894. {
  11895. bool ordered;
  11896. bool grouped;
  11897. public:
  11898. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11899. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11900. {
  11901. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11902. ordered = helper->isOrdered();
  11903. grouped = helper->queryOutputMeta()->isGrouped();
  11904. }
  11905. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11906. {
  11907. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11908. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11909. else
  11910. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  11911. }
  11912. };
  11913. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11914. {
  11915. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11916. }
  11917. //=================================================================================
  11918. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11919. {
  11920. IEngineRowStream* selectedStream;
  11921. unsigned savedParentExtractSize;
  11922. const byte * savedParentExtract;
  11923. bool foundInput;
  11924. public:
  11925. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11926. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  11927. {
  11928. foundInput = false;
  11929. selectedStream = NULL;
  11930. savedParentExtractSize = 0;;
  11931. savedParentExtract = NULL;
  11932. }
  11933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11934. {
  11935. //Don't start the inputs yet so we can short-circuit...
  11936. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11937. savedParentExtractSize = parentExtractSize;
  11938. savedParentExtract = parentExtract;
  11939. }
  11940. virtual void stop()
  11941. {
  11942. if (foundInput)
  11943. {
  11944. if (selectedStream)
  11945. selectedStream->stop();
  11946. }
  11947. else
  11948. {
  11949. for (unsigned i = 0; i < numStreams; i++)
  11950. streamArray[i]->stop();
  11951. }
  11952. CRoxieServerMultiInputBaseActivity::stop();
  11953. }
  11954. virtual void reset()
  11955. {
  11956. CRoxieServerMultiInputBaseActivity::reset();
  11957. foundInput = false;
  11958. selectedStream = NULL;
  11959. }
  11960. virtual unsigned __int64 queryLocalCycles() const
  11961. {
  11962. return 0; // Can't easily calculate anything reliable but local processing is negligible
  11963. }
  11964. virtual const void * nextRow()
  11965. {
  11966. ActivityTimer t(totalCycles, timeActivities);
  11967. if (!foundInput)
  11968. {
  11969. foundInput = true;
  11970. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  11971. //If we get an exception in this loop then stop() will stop any started inputs
  11972. for (unsigned i=0; i < numStreams; i++)
  11973. {
  11974. selectedStream = streamArray[i];
  11975. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  11976. startJunction(junctionArray[i]);
  11977. const void * next = selectedStream->nextRow();
  11978. if (next)
  11979. {
  11980. //Found a row so stop remaining
  11981. for (unsigned j=i+1; j < numInputs; j++)
  11982. streamArray[j]->stop();
  11983. processed++;
  11984. return next;
  11985. }
  11986. selectedStream->stop();
  11987. }
  11988. selectedStream = NULL;
  11989. return NULL;
  11990. }
  11991. if (!selectedStream)
  11992. return NULL;
  11993. const void * next = selectedStream->nextRow();
  11994. if (next)
  11995. processed++;
  11996. return next;
  11997. }
  11998. };
  11999. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12000. {
  12001. public:
  12002. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12003. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12004. {
  12005. }
  12006. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12007. {
  12008. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12009. }
  12010. };
  12011. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12012. {
  12013. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12014. }
  12015. //=================================================================================
  12016. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12017. {
  12018. IHThorMergeArg &helper;
  12019. unsigned *mergeheap;
  12020. unsigned activeInputs;
  12021. const void **pending;
  12022. bool first;
  12023. ICompare *compare;
  12024. bool dedup;
  12025. void permute()
  12026. {
  12027. assertex(activeInputs == 0);
  12028. for(unsigned i = 0; i < numStreams; i++)
  12029. if(pullInput(i))
  12030. mergeheap[activeInputs++] = i;
  12031. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12032. // the heap property: no element should be smaller than its parent
  12033. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12034. // 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
  12035. if (activeInputs >= 2)
  12036. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12037. siftDown(p);
  12038. if(dedup)
  12039. siftDownDedupTop();
  12040. else
  12041. siftDown(0);
  12042. }
  12043. void readNext()
  12044. {
  12045. if(!pullInput(mergeheap[0]))
  12046. if(!promote(0))
  12047. return;
  12048. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12049. if(dedup)
  12050. siftDownDedupTop();
  12051. else
  12052. siftDown(0);
  12053. }
  12054. bool pullInput(unsigned i)
  12055. {
  12056. const void *next = streamArray[i]->ungroupedNextRow();
  12057. pending[i] = next;
  12058. return (next != NULL);
  12059. }
  12060. bool promote(unsigned p)
  12061. {
  12062. activeInputs--;
  12063. if(activeInputs == p)
  12064. return false;
  12065. mergeheap[p] = mergeheap[activeInputs];
  12066. return true;
  12067. }
  12068. bool siftDown(unsigned p)
  12069. {
  12070. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12071. bool nochange = true;
  12072. while(1)
  12073. {
  12074. unsigned c = p*2 + 1;
  12075. if(c >= activeInputs)
  12076. return nochange;
  12077. if(c+1 < activeInputs)
  12078. {
  12079. int childcmp = BuffCompare(c+1, c);
  12080. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12081. ++c;
  12082. }
  12083. int cmp = BuffCompare(c, p);
  12084. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12085. return nochange;
  12086. nochange = false;
  12087. unsigned r = mergeheap[c];
  12088. mergeheap[c] = mergeheap[p];
  12089. mergeheap[p] = r;
  12090. p = c;
  12091. }
  12092. }
  12093. void siftDownDedupTop()
  12094. {
  12095. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12096. if(activeInputs < 2)
  12097. return;
  12098. unsigned c = 1;
  12099. int childcmp = 1;
  12100. if(activeInputs >= 3)
  12101. {
  12102. childcmp = BuffCompare(2, 1);
  12103. if(childcmp < 0)
  12104. c = 2;
  12105. }
  12106. int cmp = BuffCompare(c, 0);
  12107. if(cmp > 0)
  12108. return;
  12109. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12110. while(cmp <= 0)
  12111. {
  12112. if(cmp == 0)
  12113. {
  12114. if(mergeheap[c] < mergeheap[0])
  12115. {
  12116. unsigned r = mergeheap[c];
  12117. mergeheap[c] = mergeheap[0];
  12118. mergeheap[0] = r;
  12119. }
  12120. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12121. if(!pullInput(mergeheap[c]))
  12122. if(!promote(c))
  12123. break;
  12124. siftDown(c);
  12125. }
  12126. else
  12127. {
  12128. unsigned r = mergeheap[c];
  12129. mergeheap[c] = mergeheap[0];
  12130. mergeheap[0] = r;
  12131. if(siftDown(c))
  12132. break;
  12133. }
  12134. cmp = BuffCompare(c, 0);
  12135. }
  12136. // the following loop ensures the uniqueness property holds on the other branch too
  12137. c = 3-c;
  12138. if(activeInputs <= c)
  12139. return;
  12140. while(childcmp == 0)
  12141. {
  12142. if(mergeheap[c] < mergeheap[0])
  12143. {
  12144. unsigned r = mergeheap[c];
  12145. mergeheap[c] = mergeheap[0];
  12146. mergeheap[0] = r;
  12147. }
  12148. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12149. if(!pullInput(mergeheap[c]))
  12150. if(!promote(c))
  12151. break;
  12152. siftDown(c);
  12153. childcmp = BuffCompare(c, 0);
  12154. }
  12155. }
  12156. inline int BuffCompare(unsigned a, unsigned b)
  12157. {
  12158. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12159. }
  12160. public:
  12161. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12162. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12163. {
  12164. activeInputs = 0;
  12165. first = true;
  12166. mergeheap = new unsigned[numInputs];
  12167. pending = new const void *[numStreams];
  12168. compare = helper.queryCompare();
  12169. dedup = helper.dedup();
  12170. for (unsigned i = 0; i < numStreams; i++)
  12171. pending[i] = NULL;
  12172. }
  12173. ~CRoxieServerMergeActivity()
  12174. {
  12175. delete [] mergeheap;
  12176. delete [] pending;
  12177. }
  12178. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12179. {
  12180. activeInputs = 0;
  12181. first = true;
  12182. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12183. }
  12184. virtual void reset()
  12185. {
  12186. for (unsigned i = 0; i < numStreams; i++)
  12187. ReleaseClearRoxieRow(pending[i]);
  12188. CRoxieServerMultiInputActivity::reset();
  12189. }
  12190. virtual const void * nextRow()
  12191. {
  12192. ActivityTimer t(totalCycles, timeActivities);
  12193. if (first)
  12194. {
  12195. permute();
  12196. first = false;
  12197. }
  12198. if (activeInputs)
  12199. {
  12200. const void *next = pending[mergeheap[0]];
  12201. readNext();
  12202. if (next)
  12203. processed++;
  12204. return next;
  12205. }
  12206. else
  12207. return NULL;
  12208. }
  12209. };
  12210. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12211. {
  12212. public:
  12213. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12214. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12215. {
  12216. }
  12217. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12218. {
  12219. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12220. }
  12221. };
  12222. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12223. {
  12224. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12225. }
  12226. //=================================================================================
  12227. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12228. {
  12229. IHThorRegroupArg &helper;
  12230. unsigned streamIndex;
  12231. bool eof;
  12232. unsigned __int64 numProcessedLastGroup;
  12233. public:
  12234. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12235. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12236. {
  12237. streamIndex = 0;
  12238. eof = false;
  12239. numProcessedLastGroup = 0;
  12240. }
  12241. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12242. {
  12243. streamIndex = 0;
  12244. eof = false;
  12245. numProcessedLastGroup = processed;
  12246. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12247. }
  12248. const void * nextFromInputs()
  12249. {
  12250. unsigned initialStream = streamIndex;
  12251. while (streamIndex < numStreams)
  12252. {
  12253. const void * next = streamArray[streamIndex]->nextRow();
  12254. if (next)
  12255. {
  12256. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12257. {
  12258. ReleaseRoxieRow(next);
  12259. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12260. }
  12261. return next;
  12262. }
  12263. streamIndex++;
  12264. }
  12265. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12266. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12267. streamIndex = 0;
  12268. return NULL;
  12269. }
  12270. virtual const void * nextRow()
  12271. {
  12272. ActivityTimer t(totalCycles, timeActivities);
  12273. if (eof)
  12274. return NULL;
  12275. const void * ret = nextFromInputs();
  12276. if (ret)
  12277. {
  12278. processed++;
  12279. return ret;
  12280. }
  12281. if (numProcessedLastGroup != processed)
  12282. {
  12283. numProcessedLastGroup = processed;
  12284. return NULL;
  12285. }
  12286. eof = true;
  12287. return NULL;
  12288. }
  12289. };
  12290. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12291. {
  12292. public:
  12293. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12294. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12295. {
  12296. }
  12297. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12298. {
  12299. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12300. }
  12301. };
  12302. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12303. {
  12304. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12305. }
  12306. //=================================================================================
  12307. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12308. {
  12309. IHThorCombineArg &helper;
  12310. unsigned __int64 numProcessedLastGroup;
  12311. public:
  12312. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12313. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12314. {
  12315. numProcessedLastGroup = 0;
  12316. }
  12317. ~CRoxieServerCombineActivity()
  12318. {
  12319. }
  12320. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12321. {
  12322. numProcessedLastGroup = processed;
  12323. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12324. }
  12325. void nextInputs(ConstPointerArray & out)
  12326. {
  12327. for (unsigned i=0; i < numStreams; i++)
  12328. {
  12329. const void * next = streamArray[i]->nextRow();
  12330. if (next)
  12331. out.append(next);
  12332. }
  12333. }
  12334. virtual bool needsAllocator() const { return true; }
  12335. virtual const void * nextRow()
  12336. {
  12337. ActivityTimer t(totalCycles, timeActivities);
  12338. loop
  12339. {
  12340. ConstPointerArray group;
  12341. nextInputs(group);
  12342. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12343. nextInputs(group);
  12344. if (group.ordinality() == 0)
  12345. {
  12346. numProcessedLastGroup = processed;
  12347. return NULL;
  12348. }
  12349. else if (group.ordinality() != numInputs)
  12350. {
  12351. ReleaseRoxieRows(group);
  12352. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12353. }
  12354. try
  12355. {
  12356. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12357. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12358. ReleaseRoxieRows(group);
  12359. if (outSize)
  12360. {
  12361. processed++;
  12362. return rowBuilder.finalizeRowClear(outSize);
  12363. }
  12364. }
  12365. catch (IException *E)
  12366. {
  12367. ReleaseRoxieRows(group);
  12368. throw makeWrappedException(E);
  12369. }
  12370. }
  12371. }
  12372. };
  12373. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12374. {
  12375. public:
  12376. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12377. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12378. {
  12379. }
  12380. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12381. {
  12382. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12383. }
  12384. };
  12385. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12386. {
  12387. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12388. }
  12389. //=================================================================================
  12390. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12391. {
  12392. IHThorCombineGroupArg &helper;
  12393. unsigned __int64 numProcessedLastGroup;
  12394. public:
  12395. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12396. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12397. {
  12398. numProcessedLastGroup = 0;
  12399. }
  12400. ~CRoxieServerCombineGroupActivity()
  12401. {
  12402. }
  12403. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12404. {
  12405. numProcessedLastGroup = processed;
  12406. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12407. }
  12408. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12409. {
  12410. if (idx==(unsigned)-1)
  12411. idx = 0;
  12412. return idx ? NULL : this;
  12413. }
  12414. virtual bool needsAllocator() const { return true; }
  12415. virtual const void * nextRow()
  12416. {
  12417. ActivityTimer t(totalCycles, timeActivities);
  12418. loop
  12419. {
  12420. const void * left = inputStream->nextRow();
  12421. if (!left && (numProcessedLastGroup == processed))
  12422. left = inputStream->nextRow();
  12423. if (!left)
  12424. {
  12425. if (numProcessedLastGroup == processed)
  12426. {
  12427. const void * nextRight = inputStream1->nextRow();
  12428. if (nextRight)
  12429. {
  12430. ReleaseRoxieRow(nextRight);
  12431. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12432. }
  12433. }
  12434. else
  12435. numProcessedLastGroup = processed;
  12436. return NULL;
  12437. }
  12438. ConstPointerArray group;
  12439. loop
  12440. {
  12441. const void * in = inputStream1->nextRow();
  12442. if (!in)
  12443. break;
  12444. group.append(in);
  12445. }
  12446. if (group.ordinality() == 0)
  12447. {
  12448. ReleaseRoxieRow(left);
  12449. ReleaseRoxieRows(group);
  12450. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12451. }
  12452. try
  12453. {
  12454. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12455. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12456. ReleaseRoxieRow(left);
  12457. ReleaseRoxieRows(group);
  12458. if (outSize)
  12459. {
  12460. processed++;
  12461. return rowBuilder.finalizeRowClear(outSize);
  12462. }
  12463. }
  12464. catch (IException *E)
  12465. {
  12466. ReleaseRoxieRow(left);
  12467. ReleaseRoxieRows(group);
  12468. throw makeWrappedException(E);
  12469. }
  12470. }
  12471. }
  12472. };
  12473. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12474. {
  12475. unsigned input2;
  12476. unsigned input2idx;
  12477. public:
  12478. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12479. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12480. {
  12481. input2 = 0;
  12482. input2idx = 0;
  12483. }
  12484. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12485. {
  12486. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12487. }
  12488. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12489. {
  12490. if (idx==1)
  12491. {
  12492. input2 = source;
  12493. input2idx = sourceidx;
  12494. }
  12495. else
  12496. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12497. }
  12498. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12499. {
  12500. switch (idx)
  12501. {
  12502. case 1:
  12503. sourceidx = input2idx;
  12504. return input2;
  12505. case 0:
  12506. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12507. default:
  12508. return (unsigned) -1;
  12509. }
  12510. }
  12511. virtual unsigned numInputs() const { return 2; }
  12512. };
  12513. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12514. {
  12515. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12516. }
  12517. //=================================================================================
  12518. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12519. {
  12520. IHThorRollupGroupArg &helper;
  12521. bool eof;
  12522. public:
  12523. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12524. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12525. helper((IHThorRollupGroupArg &)basehelper)
  12526. {
  12527. eof = false;
  12528. }
  12529. ~CRoxieServerRollupGroupActivity()
  12530. {
  12531. }
  12532. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12533. {
  12534. eof = false;
  12535. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12536. }
  12537. virtual bool needsAllocator() const { return true; }
  12538. virtual const void * nextRow()
  12539. {
  12540. ActivityTimer t(totalCycles, timeActivities);
  12541. if (eof)
  12542. return NULL;
  12543. loop
  12544. {
  12545. ConstPointerArray group;
  12546. loop
  12547. {
  12548. const void * in = inputStream->nextRow();
  12549. if (!in)
  12550. break;
  12551. group.append(in);
  12552. }
  12553. if (group.ordinality() == 0)
  12554. {
  12555. eof = true;
  12556. return NULL;
  12557. }
  12558. try
  12559. {
  12560. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12561. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12562. ReleaseRoxieRows(group);
  12563. if (outSize)
  12564. {
  12565. processed++;
  12566. return rowBuilder.finalizeRowClear(outSize);
  12567. }
  12568. }
  12569. catch (IException * E)
  12570. {
  12571. ReleaseRoxieRows(group);
  12572. throw makeWrappedException(E);
  12573. }
  12574. }
  12575. }
  12576. };
  12577. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12578. {
  12579. public:
  12580. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12581. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12582. {
  12583. }
  12584. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12585. {
  12586. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12587. }
  12588. };
  12589. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12590. {
  12591. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12592. }
  12593. //=================================================================================
  12594. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12595. {
  12596. IHThorFilterProjectArg &helper;
  12597. unsigned numProcessedLastGroup;
  12598. unsigned __int64 recordCount;
  12599. public:
  12600. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12601. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12602. {
  12603. numProcessedLastGroup = 0;
  12604. recordCount = 0;
  12605. }
  12606. ~CRoxieServerFilterProjectActivity()
  12607. {
  12608. }
  12609. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12610. {
  12611. numProcessedLastGroup = 0;
  12612. recordCount = 0;
  12613. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12614. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12615. }
  12616. virtual bool needsAllocator() const { return true; }
  12617. virtual const void * nextRow()
  12618. {
  12619. ActivityTimer t(totalCycles, timeActivities);
  12620. if (eof)
  12621. return NULL;
  12622. loop
  12623. {
  12624. const void * in = inputStream->nextRow();
  12625. if (!in)
  12626. {
  12627. recordCount = 0;
  12628. if (numProcessedLastGroup == processed)
  12629. in = inputStream->nextRow();
  12630. if (!in)
  12631. {
  12632. numProcessedLastGroup = processed;
  12633. return NULL;
  12634. }
  12635. }
  12636. try
  12637. {
  12638. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12639. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12640. ReleaseRoxieRow(in);
  12641. if (outSize)
  12642. {
  12643. processed++;
  12644. return rowBuilder.finalizeRowClear(outSize);
  12645. }
  12646. }
  12647. catch (IException *E)
  12648. {
  12649. throw makeWrappedException(E);
  12650. }
  12651. }
  12652. }
  12653. };
  12654. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12655. {
  12656. public:
  12657. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12658. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12659. {
  12660. //MORE: Code generator needs to indicate if the count is used.
  12661. //optStableInput = false;
  12662. }
  12663. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12664. {
  12665. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  12666. }
  12667. };
  12668. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12669. {
  12670. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12671. }
  12672. //=====================================================
  12673. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  12674. {
  12675. class ProjectProcessor : public StrandProcessor
  12676. {
  12677. protected:
  12678. IHThorProjectArg &helper;
  12679. public:
  12680. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  12681. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  12682. {
  12683. }
  12684. virtual const void * nextRow()
  12685. {
  12686. ActivityTimer t(totalCycles, timeActivities);
  12687. loop
  12688. {
  12689. OwnedConstRoxieRow in = inputStream->nextRow();
  12690. if (!in)
  12691. {
  12692. if (numProcessedLastGroup == processed)
  12693. in.setown(inputStream->nextRow());
  12694. if (!in)
  12695. {
  12696. numProcessedLastGroup = processed;
  12697. return NULL;
  12698. }
  12699. }
  12700. try
  12701. {
  12702. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12703. size32_t outSize;
  12704. outSize = helper.transform(rowBuilder, in);
  12705. if (outSize)
  12706. {
  12707. processed++;
  12708. return rowBuilder.finalizeRowClear(outSize);
  12709. }
  12710. }
  12711. catch (IException *E)
  12712. {
  12713. throw parent.makeWrappedException(E);
  12714. }
  12715. }
  12716. }
  12717. };
  12718. public:
  12719. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  12720. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  12721. {
  12722. }
  12723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12724. {
  12725. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  12726. onStartStrands();
  12727. }
  12728. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  12729. {
  12730. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  12731. }
  12732. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  12733. };
  12734. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12735. {
  12736. unsigned numProcessedLastGroup;
  12737. unsigned __int64 recordCount;
  12738. bool count;
  12739. public:
  12740. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12741. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12742. count(_count)
  12743. {
  12744. numProcessedLastGroup = 0;
  12745. recordCount = 0;
  12746. }
  12747. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12748. {
  12749. numProcessedLastGroup = 0;
  12750. recordCount = 0;
  12751. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12752. }
  12753. virtual bool needsAllocator() const { return true; }
  12754. virtual const void * nextRow()
  12755. {
  12756. ActivityTimer t(totalCycles, timeActivities);
  12757. loop
  12758. {
  12759. OwnedConstRoxieRow in = inputStream->nextRow();
  12760. if (!in)
  12761. {
  12762. recordCount = 0;
  12763. if (numProcessedLastGroup == processed)
  12764. in.setown(inputStream->nextRow());
  12765. if (!in)
  12766. {
  12767. numProcessedLastGroup = processed;
  12768. return NULL;
  12769. }
  12770. }
  12771. try
  12772. {
  12773. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12774. size32_t outSize;
  12775. if (count)
  12776. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12777. else
  12778. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12779. if (outSize)
  12780. {
  12781. processed++;
  12782. return rowBuilder.finalizeRowClear(outSize);
  12783. }
  12784. }
  12785. catch (IException *E)
  12786. {
  12787. throw makeWrappedException(E);
  12788. }
  12789. }
  12790. }
  12791. };
  12792. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12793. {
  12794. protected:
  12795. StrandOptions strandOptions;
  12796. bool count;
  12797. public:
  12798. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12799. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  12800. {
  12801. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  12802. optStableInput = count;
  12803. }
  12804. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12805. {
  12806. // 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.
  12807. if (kind == TAKproject) // Not supported on prefetch or count projects
  12808. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  12809. else
  12810. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  12811. }
  12812. };
  12813. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12814. {
  12815. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12816. }
  12817. //=================================================================================
  12818. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12819. {
  12820. unsigned numProcessedLastGroup;
  12821. bool count;
  12822. bool eof;
  12823. bool allPulled;
  12824. bool isThreaded;
  12825. unsigned preload;
  12826. unsigned __int64 recordCount;
  12827. IHThorPrefetchProjectArg &helper;
  12828. RecordPullerThread puller;
  12829. InterruptableSemaphore ready;
  12830. InterruptableSemaphore space;
  12831. class PrefetchInfo : public CInterface
  12832. {
  12833. public:
  12834. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12835. {
  12836. if (helper.preTransform(extract, _in, _recordCount))
  12837. {
  12838. in.setown(_in);
  12839. recordCount = _recordCount;
  12840. }
  12841. else
  12842. {
  12843. ReleaseRoxieRow(_in);
  12844. recordCount = 0;
  12845. }
  12846. }
  12847. OwnedConstRoxieRow in;
  12848. unsigned __int64 recordCount;
  12849. rtlRowBuilder extract;
  12850. };
  12851. QueueOf<PrefetchInfo, true> pulled;
  12852. CriticalSection pulledCrit;
  12853. public:
  12854. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12855. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12856. helper((IHThorPrefetchProjectArg &) basehelper),
  12857. puller(false),
  12858. count(_count)
  12859. {
  12860. numProcessedLastGroup = 0;
  12861. recordCount = 0;
  12862. eof = false;
  12863. allPulled = false;
  12864. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12865. preload = 0;
  12866. }
  12867. ~CRoxieServerPrefetchProjectActivity()
  12868. {
  12869. while (pulled.ordinality())
  12870. ::Release(pulled.dequeue());
  12871. }
  12872. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12873. {
  12874. if (idx)
  12875. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12876. puller.setInput(this, _sourceIdx, _in);
  12877. }
  12878. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12879. {
  12880. puller.connectInputStreams(ctx, consumerOrdered);
  12881. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12882. }
  12883. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12884. {
  12885. if (idx==0)
  12886. return puller.queryInput();
  12887. else
  12888. return NULL;
  12889. }
  12890. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12891. {
  12892. numProcessedLastGroup = 0;
  12893. recordCount = 0;
  12894. eof = false;
  12895. allPulled = false;
  12896. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12897. preload = helper.getLookahead();
  12898. if (!preload)
  12899. preload = ctx->queryOptions().prefetchProjectPreload;
  12900. space.reinit(preload);
  12901. ready.reinit();
  12902. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12903. }
  12904. virtual void stop()
  12905. {
  12906. space.interrupt();
  12907. ready.interrupt();
  12908. CRoxieServerActivity::stop();
  12909. puller.stop();
  12910. }
  12911. virtual void reset()
  12912. {
  12913. CRoxieServerActivity::reset();
  12914. puller.reset();
  12915. allPulled = false;
  12916. while (pulled.ordinality())
  12917. ::Release(pulled.dequeue());
  12918. }
  12919. virtual PrefetchInfo *readNextRecord()
  12920. {
  12921. if (!isThreaded)
  12922. {
  12923. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12924. puller.pullRecords(1);
  12925. }
  12926. else
  12927. ready.wait();
  12928. CriticalBlock b(pulledCrit);
  12929. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12930. space.signal();
  12931. return ret;
  12932. }
  12933. virtual bool needsAllocator() const { return true; }
  12934. virtual const void * nextRow()
  12935. {
  12936. ActivityTimer t(totalCycles, timeActivities);
  12937. if (eof)
  12938. return NULL;
  12939. loop
  12940. {
  12941. Owned<PrefetchInfo> in = readNextRecord();
  12942. if (!in)
  12943. {
  12944. recordCount = 0;
  12945. if (numProcessedLastGroup == processed)
  12946. in.setown(readNextRecord());
  12947. if (!in)
  12948. {
  12949. numProcessedLastGroup = processed;
  12950. eof = true;
  12951. return NULL;
  12952. }
  12953. }
  12954. try
  12955. {
  12956. if (in->in)
  12957. {
  12958. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12959. size32_t outSize;
  12960. IThorChildGraph *child = helper.queryChild();
  12961. Owned<IEclGraphResults> results;
  12962. if (child)
  12963. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12964. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12965. if (outSize)
  12966. {
  12967. processed++;
  12968. return rowBuilder.finalizeRowClear(outSize);
  12969. }
  12970. }
  12971. }
  12972. catch (IException *E)
  12973. {
  12974. throw makeWrappedException(E);
  12975. }
  12976. }
  12977. }
  12978. // interface IExceptionHandler
  12979. virtual bool fireException(IException *e)
  12980. {
  12981. // called from puller thread on failure
  12982. ready.interrupt(LINK(e));
  12983. space.interrupt(e);
  12984. return true;
  12985. }
  12986. // interface IRecordPullerCallback
  12987. virtual void processRow(const void *row)
  12988. {
  12989. {
  12990. CriticalBlock b(pulledCrit);
  12991. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12992. }
  12993. if (isThreaded)
  12994. {
  12995. ready.signal();
  12996. space.wait();
  12997. }
  12998. }
  12999. virtual void processEOG()
  13000. {
  13001. {
  13002. CriticalBlock b(pulledCrit);
  13003. pulled.enqueue(NULL);
  13004. }
  13005. if (isThreaded)
  13006. {
  13007. ready.signal();
  13008. space.wait();
  13009. }
  13010. }
  13011. virtual void processGroup(const ConstPointerArray &rows)
  13012. {
  13013. throwUnexpected();
  13014. }
  13015. virtual void processDone()
  13016. {
  13017. CriticalBlock b(pulledCrit);
  13018. allPulled = true;
  13019. if (isThreaded)
  13020. ready.signal();
  13021. }
  13022. };
  13023. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13024. {
  13025. public:
  13026. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13027. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13028. {
  13029. }
  13030. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13031. {
  13032. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13033. }
  13034. };
  13035. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13036. {
  13037. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13038. }
  13039. //=================================================================================
  13040. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13041. {
  13042. public:
  13043. CPointerArrayRoxieInput()
  13044. {
  13045. rowset = NULL;
  13046. rowcount = 0;
  13047. curRow = 0;
  13048. }
  13049. void init(size32_t _rowcount, byte **_rowset)
  13050. {
  13051. rowset = _rowset;
  13052. rowcount = _rowcount;
  13053. curRow = 0;
  13054. }
  13055. virtual const void * nextRow()
  13056. {
  13057. if (curRow < rowcount)
  13058. {
  13059. const void * ret = rowset[curRow];
  13060. if (ret)
  13061. LinkRoxieRow(ret);
  13062. curRow++;
  13063. return ret;
  13064. }
  13065. return NULL;
  13066. }
  13067. protected:
  13068. byte **rowset;
  13069. size32_t rowcount;
  13070. size32_t curRow;
  13071. };
  13072. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13073. {
  13074. protected:
  13075. IHThorLoopArg &helper;
  13076. ThorActivityKind activityKind;
  13077. unsigned maxIterations;
  13078. bool finishedLooping;
  13079. unsigned flags;
  13080. bool eof;
  13081. rtlRowBuilder loopExtractBuilder;
  13082. unsigned loopGraphId;
  13083. Linked<IOutputMetaData> counterMeta;
  13084. public:
  13085. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13086. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13087. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13088. {
  13089. eof = false;
  13090. finishedLooping = false;
  13091. activityKind = factory->getKind();
  13092. flags = helper.getFlags();
  13093. maxIterations = 0;
  13094. }
  13095. virtual bool needsAllocator() const { return true; }
  13096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13097. {
  13098. eof = false;
  13099. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13100. int iterations = (int) helper.numIterations();
  13101. maxIterations = (iterations >= 0) ? iterations : 0;
  13102. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13103. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13104. finishedLooping = true;
  13105. loopExtractBuilder.clear();
  13106. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13107. }
  13108. virtual void stop()
  13109. {
  13110. CRoxieServerActivity::stop();
  13111. loopExtractBuilder.clear();
  13112. }
  13113. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13114. {
  13115. if (flags & IHThorLoopArg::LFcounter)
  13116. {
  13117. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13118. *((thor_loop_counter_t *)counterRow) = counter;
  13119. RtlLinkedDatasetBuilder builder(rowAllocator);
  13120. builder.appendOwn(counterRow);
  13121. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13122. graph->setInputResult(2, counterResult);
  13123. }
  13124. }
  13125. };
  13126. //=================================================================================
  13127. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13128. {
  13129. Owned<IActivityGraph> loopQuery;
  13130. Owned<IRoxieServerChildGraph> loopGraph;
  13131. IEngineRowStream * curStream;
  13132. RtlLinkedDatasetBuilder *loopInputBuilder;
  13133. CPointerArrayRoxieInput arrayInput;
  13134. Linked<IEngineRowStream> resultStream;
  13135. unsigned loopCounter;
  13136. public:
  13137. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13138. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13139. {
  13140. curStream = NULL;
  13141. loopCounter = 0;
  13142. loopInputBuilder = NULL;
  13143. }
  13144. virtual bool needsAllocator() const { return true; }
  13145. virtual void onCreate(IHThorArg *_colocalParent)
  13146. {
  13147. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13148. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13149. }
  13150. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13151. {
  13152. curStream = inputStream;
  13153. loopCounter = 1;
  13154. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13155. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13156. loopGraph.set(loopQuery->queryLoopGraph());
  13157. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13158. }
  13159. virtual void stop()
  13160. {
  13161. delete loopInputBuilder;
  13162. loopInputBuilder = NULL;
  13163. CRoxieServerLoopActivity::stop();
  13164. }
  13165. virtual const void * nextRow()
  13166. {
  13167. ActivityTimer t(totalCycles, timeActivities);
  13168. if (eof)
  13169. return NULL;
  13170. unsigned emptyIterations = 0;
  13171. loop
  13172. {
  13173. loop
  13174. {
  13175. const void * ret = curStream->nextRow();
  13176. if (!ret)
  13177. {
  13178. ret = curStream->nextRow(); // more cope with groups somehow....
  13179. if (!ret)
  13180. {
  13181. if (finishedLooping)
  13182. {
  13183. eof = true;
  13184. return NULL;
  13185. }
  13186. break;
  13187. }
  13188. }
  13189. if (finishedLooping ||
  13190. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13191. {
  13192. processed++;
  13193. return ret;
  13194. }
  13195. loopInputBuilder->appendOwn(ret);
  13196. }
  13197. switch (activityKind)
  13198. {
  13199. case TAKloopdataset:
  13200. {
  13201. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13202. {
  13203. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13204. {
  13205. if (loopInputBuilder->getcount() == 0)
  13206. {
  13207. eof = true;
  13208. return NULL;
  13209. }
  13210. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13211. // MORE - should builder be cleared here?
  13212. curStream = &arrayInput;
  13213. finishedLooping = true;
  13214. continue; // back to the input loop again
  13215. }
  13216. }
  13217. break;
  13218. }
  13219. case TAKlooprow:
  13220. if (!loopInputBuilder->getcount())
  13221. {
  13222. finishedLooping = true;
  13223. eof = true;
  13224. return NULL;
  13225. }
  13226. break;
  13227. }
  13228. if (loopInputBuilder->getcount())
  13229. emptyIterations = 0;
  13230. else
  13231. {
  13232. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13233. emptyIterations++;
  13234. if (emptyIterations > maxEmptyLoopIterations)
  13235. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13236. if (emptyIterations % 32 == 0)
  13237. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13238. }
  13239. checkAbort();
  13240. try
  13241. {
  13242. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13243. resultStream.setown(results->createIterator(0));
  13244. if (flags & IHThorLoopArg::LFnewloopagain)
  13245. {
  13246. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13247. OwnedConstRoxieRow row = againResult->nextRow();
  13248. assertex(row);
  13249. //Result is a row which contains a single boolean field.
  13250. if (!((const bool *)row.get())[0])
  13251. finishedLooping = true;
  13252. }
  13253. }
  13254. catch (IException *E)
  13255. {
  13256. throw makeWrappedException(E);
  13257. }
  13258. curStream = resultStream.get();
  13259. loopCounter++;
  13260. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13261. finishedLooping = true;
  13262. }
  13263. }
  13264. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13265. {
  13266. try
  13267. {
  13268. loopGraph->beforeExecute();
  13269. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13270. loopInputBuilder->clear();
  13271. loopGraph->setInputResult(1, inputRowsResult);
  13272. createCounterResult(loopGraph, counter);
  13273. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13274. loopGraph->afterExecute();
  13275. return ret.getClear();
  13276. }
  13277. catch (...)
  13278. {
  13279. CTXLOG("Exception thrown in loop body - cleaning up");
  13280. loopGraph->afterExecute();
  13281. throw;
  13282. }
  13283. }
  13284. };
  13285. //=================================================================================
  13286. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13287. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13288. {
  13289. public:
  13290. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13291. : meta(_meta), input(_input)
  13292. {
  13293. eof = false;
  13294. }
  13295. virtual const void * nextRow()
  13296. {
  13297. if (eof)
  13298. return NULL;
  13299. const void * ret = input.dequeue();
  13300. if (!ret)
  13301. eof = true;
  13302. return ret;
  13303. }
  13304. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13305. protected:
  13306. SafeRowQueue & input;
  13307. IOutputMetaData * meta;
  13308. bool eof;
  13309. };
  13310. class CRoxieServerParallelLoopActivity;
  13311. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13312. {
  13313. public:
  13314. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13315. activity(_activity), counter(_counter)
  13316. {
  13317. }
  13318. virtual const void * nextRow();
  13319. protected:
  13320. CRoxieServerParallelLoopActivity * activity;
  13321. unsigned counter;
  13322. };
  13323. class LoopExecutorThread : public RestartableThread
  13324. {
  13325. protected:
  13326. Owned<CSafeRoxieInput> safeInput;
  13327. CRoxieServerParallelLoopActivity * activity;
  13328. bool eof;
  13329. CriticalSection crit;
  13330. unsigned flags;
  13331. SafeRowQueue tempResults[2];
  13332. unsigned savedParentExtractSize;
  13333. const byte * savedParentExtract;
  13334. IArrayOf<IActivityGraph> cachedGraphs;
  13335. IRoxieSlaveContext *ctx;
  13336. public:
  13337. LoopExecutorThread()
  13338. : RestartableThread("LoopExecutorThread")
  13339. {
  13340. activity = NULL;
  13341. eof = false;
  13342. flags = 0;
  13343. ctx = NULL;
  13344. savedParentExtract = NULL;
  13345. savedParentExtractSize = 0;
  13346. }
  13347. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13348. {
  13349. activity = _activity;
  13350. flags = _flags;
  13351. // 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.
  13352. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13353. }
  13354. void connectInputStreams(bool consumerOrdered)
  13355. {
  13356. safeInput->connectInputStreams(ctx, consumerOrdered);
  13357. }
  13358. IFinalRoxieInput *queryInput() const
  13359. {
  13360. return safeInput;
  13361. }
  13362. void onCreate(IRoxieSlaveContext * _ctx);
  13363. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13364. void stop();
  13365. void reset();
  13366. virtual int run();
  13367. protected:
  13368. void executeLoop();
  13369. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13370. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13371. };
  13372. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13373. {
  13374. friend class LoopFilterPseudoInput;
  13375. friend class LoopExecutorThread;
  13376. QueueOf<const void, true> ready;
  13377. CriticalSection helperCS;
  13378. CriticalSection cs;
  13379. unsigned defaultNumParallel;
  13380. LoopExecutorThread executor;
  13381. IProbeManager* probeManager;
  13382. CriticalSection canAccess;
  13383. CriticalSection scrit;
  13384. InterruptableSemaphore readySpace;
  13385. InterruptableSemaphore recordsReady;
  13386. protected:
  13387. bool includeInLoop(unsigned counter, const void * row)
  13388. {
  13389. CriticalBlock b(helperCS);
  13390. return helper.sendToLoop(counter, row);
  13391. }
  13392. public:
  13393. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13394. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13395. readySpace(parallelLoopFlowLimit)
  13396. {
  13397. probeManager = _probeManager;
  13398. defaultNumParallel = 0;
  13399. }
  13400. virtual void onCreate(IHThorArg *_colocalParent)
  13401. {
  13402. CRoxieServerActivity::onCreate(_colocalParent);
  13403. executor.onCreate(ctx);
  13404. }
  13405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13406. {
  13407. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13408. readySpace.reinit(parallelLoopFlowLimit);
  13409. recordsReady.reinit();
  13410. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13411. defaultNumParallel = helper.defaultParallelIterations();
  13412. if (!defaultNumParallel)
  13413. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13414. //MORE: If numIterations <= number of parallel iterations[1],
  13415. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13416. //being transferred via a queue
  13417. executor.start(parentExtractSize, parentExtract, paused);
  13418. }
  13419. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13420. {
  13421. if (idx)
  13422. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13423. executor.setInput(this, _sourceIdx, _in, flags);
  13424. }
  13425. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13426. {
  13427. executor.connectInputStreams(consumerOrdered);
  13428. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13429. }
  13430. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13431. {
  13432. if (idx==0)
  13433. return executor.queryInput();
  13434. else
  13435. return NULL;
  13436. }
  13437. virtual void stop()
  13438. {
  13439. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13440. readySpace.interrupt();
  13441. recordsReady.interrupt();
  13442. executor.join(); // MORE - may not be needed given stop/reset split
  13443. CRoxieServerLoopActivity::stop();
  13444. }
  13445. virtual void reset()
  13446. {
  13447. while (ready.ordinality())
  13448. ReleaseRoxieRow(ready.dequeue());
  13449. executor.reset();
  13450. CRoxieServerActivity::reset();
  13451. }
  13452. virtual const void * nextRow()
  13453. {
  13454. ActivityTimer t(totalCycles, timeActivities);
  13455. loop
  13456. {
  13457. if (eof)
  13458. return NULL;
  13459. recordsReady.wait();
  13460. CriticalBlock procedure(canAccess);
  13461. if (ready.ordinality())
  13462. {
  13463. const void *result = ready.dequeue();
  13464. readySpace.signal();
  13465. if (result)
  13466. processed++;
  13467. return result;
  13468. }
  13469. else
  13470. eof = true;
  13471. }
  13472. }
  13473. unsigned getNumParallel(unsigned iter)
  13474. {
  13475. return defaultNumParallel;
  13476. }
  13477. inline void enqueueResult(const void * row)
  13478. {
  13479. try
  13480. {
  13481. while(!readySpace.wait(1000))
  13482. {
  13483. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13484. }
  13485. }
  13486. catch (...)
  13487. {
  13488. ReleaseRoxieRow(row);
  13489. throw;
  13490. }
  13491. CriticalBlock b2(canAccess);
  13492. ready.enqueue(row);
  13493. recordsReady.signal();
  13494. }
  13495. inline void finishResults()
  13496. {
  13497. recordsReady.signal();
  13498. }
  13499. virtual bool fireException(IException *e)
  13500. {
  13501. readySpace.interrupt(LINK(e));
  13502. recordsReady.interrupt(e);
  13503. return true;
  13504. }
  13505. IActivityGraph * createChildGraphInstance()
  13506. {
  13507. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13508. }
  13509. IActivityGraph * queryChildGraph()
  13510. {
  13511. return ctx->queryChildGraph(loopGraphId);
  13512. }
  13513. };
  13514. //=================================================================================
  13515. const void * LoopFilterPseudoInput::nextRow()
  13516. {
  13517. loop
  13518. {
  13519. const void * next = stream->nextRow();
  13520. if (!next || activity->includeInLoop(counter, next))
  13521. return next;
  13522. activity->enqueueResult(next);
  13523. }
  13524. }
  13525. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13526. {
  13527. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13528. ctx = _ctx;
  13529. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13530. }
  13531. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13532. {
  13533. savedParentExtractSize = parentExtractSize;
  13534. savedParentExtract = parentExtract;
  13535. eof = false;
  13536. StringBuffer logPrefix("[");
  13537. ctx->getLogPrefix(logPrefix).append("] ");
  13538. RestartableThread::start(logPrefix);
  13539. }
  13540. int LoopExecutorThread::run()
  13541. {
  13542. try
  13543. {
  13544. executeLoop();
  13545. }
  13546. catch (IException *e)
  13547. {
  13548. activity->fireException(e);
  13549. }
  13550. catch (...)
  13551. {
  13552. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13553. }
  13554. return 0;
  13555. }
  13556. void LoopExecutorThread::stop()
  13557. {
  13558. safeInput->stop();
  13559. RestartableThread::join();
  13560. }
  13561. void LoopExecutorThread::reset()
  13562. {
  13563. safeInput->reset();
  13564. }
  13565. void LoopExecutorThread::executeLoop()
  13566. {
  13567. unsigned iterations = 0;
  13568. unsigned counter = 0;
  13569. unsigned outputIndex = 0;
  13570. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13571. loop
  13572. {
  13573. if (activity->activityKind == TAKloopcount)
  13574. {
  13575. if (counter == activity->maxIterations)
  13576. break;
  13577. }
  13578. else
  13579. {
  13580. //This condition isn't quite right because it needs to be whether the filtered
  13581. //input is empty. May be ok if we include that in the semantics,
  13582. if (tempResults[1-outputIndex].ordinality() == 0)
  13583. break;
  13584. }
  13585. unsigned numParallel = activity->getNumParallel(iterations);
  13586. Linked<IFinalRoxieInput> curInput;
  13587. if (iterations == 0)
  13588. curInput.set(safeInput);
  13589. else
  13590. {
  13591. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13592. inputQueue.enqueue(NULL);
  13593. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13594. }
  13595. SafeRowQueue * curOutput = NULL;
  13596. if (counter+numParallel > activity->maxIterations)
  13597. numParallel = activity->maxIterations - counter;
  13598. else if (counter+numParallel < activity->maxIterations)
  13599. curOutput = &tempResults[outputIndex];
  13600. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13601. outputIndex = 1-outputIndex;
  13602. counter += numParallel;
  13603. iterations++;
  13604. }
  13605. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13606. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13607. while (inputQueue.ordinality())
  13608. {
  13609. const void * next = inputQueue.dequeue();
  13610. activity->enqueueResult(next);
  13611. }
  13612. activity->finishResults();
  13613. }
  13614. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13615. {
  13616. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13617. Linked<IFinalRoxieInput> curInput = input;
  13618. unsigned i;
  13619. for (i= 0; i != numIterations; i++)
  13620. {
  13621. unsigned thisCounter = counter+i+1;
  13622. IFinalRoxieInput * filtered = curInput;
  13623. if (flags & IHThorLoopArg::LFfiltered)
  13624. {
  13625. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13626. newFiltered->setInput(inputIdx, curInput);
  13627. filtered = newFiltered;
  13628. savedInputs.append(*filtered);
  13629. inputIdx = 0;
  13630. }
  13631. //graph is kept, so new curInput will be guaranteed to exist
  13632. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13633. inputIdx = 0;
  13634. }
  13635. Owned<IStrandJunction> curJunction;
  13636. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13637. try
  13638. {
  13639. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13640. if (spillOutput)
  13641. {
  13642. loop
  13643. {
  13644. const void * next = curStream->nextRow();
  13645. if (!next)
  13646. break;
  13647. spillOutput->enqueue(next);
  13648. }
  13649. }
  13650. else
  13651. {
  13652. loop
  13653. {
  13654. const void * next = curStream->nextRow();
  13655. if (!next)
  13656. break;
  13657. activity->enqueueResult(next);
  13658. }
  13659. }
  13660. }
  13661. catch (IException *E)
  13662. {
  13663. ctx->notifyAbort(E);
  13664. for (i= 0; i != numIterations; i++)
  13665. {
  13666. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13667. }
  13668. curStream->stop();
  13669. curInput->reset();
  13670. throw;
  13671. }
  13672. for (i= 0; i != numIterations; i++)
  13673. {
  13674. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13675. }
  13676. curStream->stop();
  13677. curInput->reset();
  13678. }
  13679. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  13680. {
  13681. if (!cachedGraphs.isItem(i))
  13682. cachedGraphs.append(*activity->createChildGraphInstance());
  13683. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13684. loopGraph->beforeExecute();
  13685. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  13686. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13687. activity->createCounterResult(loopGraph, counter);
  13688. return loopGraph->selectOutput(0);
  13689. }
  13690. //=================================================================================
  13691. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  13692. {
  13693. public:
  13694. IMPLEMENT_IINTERFACE
  13695. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13696. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13697. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13698. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13699. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13700. virtual unsigned getMetaFlags() { return 0; }
  13701. virtual void destruct(byte * self) {}
  13702. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13703. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13704. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13705. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13706. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13707. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13708. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13709. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13710. };
  13711. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13712. {
  13713. unsigned loopGraphId;
  13714. unsigned flags;
  13715. Linked<IOutputMetaData> counterMeta;
  13716. public:
  13717. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13718. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  13719. {
  13720. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13721. flags = helper->getFlags();
  13722. counterMeta.setown(new CCounterRowMetaData);
  13723. }
  13724. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13725. {
  13726. if (flags & IHThorLoopArg::LFparallel)
  13727. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13728. else
  13729. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  13730. }
  13731. };
  13732. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  13733. {
  13734. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  13735. }
  13736. //=================================================================================
  13737. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13738. {
  13739. protected:
  13740. IHThorGraphLoopArg &helper;
  13741. unsigned maxIterations;
  13742. unsigned flags;
  13743. rtlRowBuilder GraphExtractBuilder;
  13744. unsigned loopGraphId;
  13745. Linked<IOutputMetaData> counterMeta;
  13746. public:
  13747. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13748. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13749. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13750. {
  13751. flags = helper.getFlags();
  13752. maxIterations = 0;
  13753. }
  13754. virtual bool needsAllocator() const { return true; }
  13755. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13756. {
  13757. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13758. int iterations = (int) helper.numIterations();
  13759. maxIterations = (iterations >= 0) ? iterations : 0;
  13760. if (maxIterations > maxGraphLoopIterations)
  13761. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13762. if (maxIterations != 0)
  13763. {
  13764. GraphExtractBuilder.clear();
  13765. helper.createParentExtract(GraphExtractBuilder);
  13766. }
  13767. }
  13768. virtual void stop()
  13769. {
  13770. CRoxieServerActivity::stop();
  13771. GraphExtractBuilder.clear();
  13772. }
  13773. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13774. {
  13775. if (flags & IHThorGraphLoopArg::GLFcounter)
  13776. {
  13777. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13778. *((thor_loop_counter_t *)counterRow) = counter;
  13779. RtlLinkedDatasetBuilder builder(rowAllocator);
  13780. builder.appendOwn(counterRow);
  13781. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13782. graph->setInputResult(0, counterResult);
  13783. }
  13784. }
  13785. };
  13786. //=================================================================================
  13787. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13788. {
  13789. Owned<IActivityGraph> GraphQuery;
  13790. Owned<IRoxieServerChildGraph> loopGraph;
  13791. Linked<IEngineRowStream> resultStream;
  13792. bool evaluated;
  13793. public:
  13794. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13795. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  13796. {
  13797. evaluated = false;
  13798. }
  13799. virtual void onCreate(IHThorArg *_colocalParent)
  13800. {
  13801. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13802. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  13803. }
  13804. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13805. {
  13806. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13807. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13808. loopGraph.set(GraphQuery->queryLoopGraph());
  13809. evaluated = false;
  13810. }
  13811. virtual void stop()
  13812. {
  13813. if (loopGraph)
  13814. loopGraph->clearGraphLoopResults();
  13815. CRoxieServerGraphLoopActivity::stop();
  13816. }
  13817. virtual const void * nextRow()
  13818. {
  13819. ActivityTimer t(totalCycles, timeActivities);
  13820. if (!evaluated)
  13821. {
  13822. executeEntireGraph();
  13823. evaluated = true;
  13824. }
  13825. const void * ret = resultStream->nextRow();
  13826. if (ret)
  13827. processed++;
  13828. return ret;
  13829. }
  13830. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13831. {
  13832. try
  13833. {
  13834. loopGraph->beforeExecute();
  13835. createCounterResult(loopGraph, counter);
  13836. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13837. loopGraph->afterExecute();
  13838. }
  13839. catch (...)
  13840. {
  13841. CTXLOG("Exception thrown in graph body - cleaning up");
  13842. loopGraph->afterExecute();
  13843. throw;
  13844. }
  13845. }
  13846. void createInitialGraphInput()
  13847. {
  13848. loopGraph->clearGraphLoopResults();
  13849. RtlLinkedDatasetBuilder builder(rowAllocator);
  13850. inputStream->readAll(builder);
  13851. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13852. loopGraph->setGraphLoopResult(0, result);
  13853. }
  13854. void executeEntireGraph()
  13855. {
  13856. createInitialGraphInput();
  13857. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13858. {
  13859. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13860. }
  13861. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  13862. }
  13863. };
  13864. //=================================================================================
  13865. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13866. {
  13867. public:
  13868. virtual unsigned numBranches()
  13869. {
  13870. return 0;
  13871. }
  13872. virtual IOutputMetaData * queryOutputMeta()
  13873. {
  13874. return NULL;// get it from the parent..
  13875. }
  13876. };
  13877. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13878. class CGraphIterationInfo : public CInterface
  13879. {
  13880. private:
  13881. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13882. unsigned sourceIdx;
  13883. Linked<IRoxieServerActivity> sourceAct;
  13884. Linked<IFinalRoxieInput> sourceInput;
  13885. unsigned numUses;
  13886. unsigned iteration;
  13887. public:
  13888. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13889. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13890. {
  13891. numUses = 0;
  13892. }
  13893. inline void noteUsed()
  13894. {
  13895. numUses++;
  13896. }
  13897. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  13898. {
  13899. if (numUses > 1)
  13900. {
  13901. Owned<IPropertyTree> splitterNode = createPTree();
  13902. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  13903. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  13904. splitter->onCreate(NULL);
  13905. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13906. if (probeManager)
  13907. {
  13908. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13909. probes.append(*LINK(inputProbe));
  13910. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13911. sourceIdx = 0;
  13912. }
  13913. sourceAct.setown(splitter);
  13914. sourceAct->setInput(0, sourceIdx, input);
  13915. sourceIdx = 0;
  13916. sourceInput.clear();
  13917. }
  13918. }
  13919. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13920. {
  13921. // MORE - not really necessary to create splitters in separate pass, is it?
  13922. if (factory) // we created a splitter....
  13923. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13924. IFinalRoxieInput *ret = sourceInput;
  13925. if (probeManager)
  13926. {
  13927. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13928. probes.append(*LINK(inputProbe));
  13929. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  13930. // MORE - do we need to connect the stream in the probe?
  13931. }
  13932. if (factory) // we created a splitter....
  13933. sourceIdx++;
  13934. return ret;
  13935. }
  13936. };
  13937. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13938. {
  13939. Owned<IActivityGraph> childGraph;
  13940. IFinalRoxieInput * resultInput;
  13941. IEngineRowStream * resultStream;
  13942. Owned<IStrandJunction> resultJunction;
  13943. CIArrayOf<CGraphIterationInfo> outputs;
  13944. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13945. Owned<CExtractMapperInput> inputExtractMapper;
  13946. IProbeManager *probeManager;
  13947. unsigned createLoopCounter;
  13948. IArrayOf<IRoxieProbe> probes;
  13949. public:
  13950. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13951. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13952. {
  13953. inputExtractMapper.setown(new CExtractMapperInput);
  13954. resultInput = NULL;
  13955. resultStream = NULL;
  13956. createLoopCounter = 0;
  13957. }
  13958. virtual void onCreate(IHThorArg *_colocalParent)
  13959. {
  13960. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  13961. childGraph.set(ctx->queryChildGraph(loopGraphId));
  13962. }
  13963. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13964. {
  13965. //Input needs to be handled very carefully.....
  13966. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13967. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13968. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13969. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13970. assertex(idx == 0);
  13971. inputExtractMapper->setInput(_sourceIdx, _in);
  13972. }
  13973. virtual void connectInputStreams(bool consumerOrdered)
  13974. {
  13975. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  13976. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  13977. }
  13978. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13979. {
  13980. if (idx==0)
  13981. return inputExtractMapper->queryInput();
  13982. else
  13983. return NULL;
  13984. }
  13985. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13986. {
  13987. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13988. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13989. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13990. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13991. startJunction(resultJunction);
  13992. }
  13993. virtual void stop()
  13994. {
  13995. if (resultStream)
  13996. resultStream->stop();
  13997. CRoxieServerGraphLoopActivity::stop();
  13998. }
  13999. virtual void reset()
  14000. {
  14001. if (resultInput)
  14002. resultInput->reset();
  14003. resetJunction(resultJunction);
  14004. resultInput = NULL;
  14005. resultStream = NULL;
  14006. resultJunction.clear();
  14007. outputs.kill();
  14008. iterationGraphs.kill(); // must be done after all activities killed
  14009. if (probeManager)
  14010. {
  14011. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14012. probes.kill();
  14013. }
  14014. CRoxieServerGraphLoopActivity::reset();
  14015. }
  14016. virtual const void * nextRow()
  14017. {
  14018. ActivityTimer t(totalCycles, timeActivities);
  14019. const void * ret = resultStream->nextRow();
  14020. if (ret)
  14021. processed++;
  14022. return ret;
  14023. }
  14024. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14025. {
  14026. //result(0) is the input to the graph.
  14027. resultInput = inputExtractMapper;
  14028. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14029. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14030. {
  14031. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14032. graph->beforeExecute();
  14033. iterationGraphs.append(*graph);
  14034. graph->gatherIterationUsage(*this);
  14035. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14036. outputs.append(*iteration);
  14037. }
  14038. createLoopCounter = 0;
  14039. createSplitters(probeManager, probes);
  14040. ForEachItemIn(i2, iterationGraphs)
  14041. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14042. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14043. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14044. }
  14045. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14046. {
  14047. ForEachItemIn(i, outputs)
  14048. {
  14049. CGraphIterationInfo & next = outputs.item(i);
  14050. next.createSplitter(ctx, probeManager, probes);
  14051. }
  14052. }
  14053. //IRoxieServerLoopResultProcessor
  14054. virtual void noteUseIteration(unsigned _whichIteration)
  14055. {
  14056. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14057. if (whichIteration >= 0)
  14058. {
  14059. if (!outputs.isItem(whichIteration))
  14060. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14061. outputs.item(whichIteration).noteUsed();
  14062. }
  14063. }
  14064. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14065. {
  14066. if (outputs.isItem(whichIteration))
  14067. {
  14068. CGraphIterationInfo & next = outputs.item(whichIteration);
  14069. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14070. }
  14071. return NULL;
  14072. }
  14073. };
  14074. //=================================================================================
  14075. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14076. {
  14077. unsigned loopGraphId;
  14078. unsigned flags;
  14079. Linked<IOutputMetaData> counterMeta;
  14080. public:
  14081. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14082. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14083. {
  14084. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14085. flags = helper->getFlags();
  14086. counterMeta.setown(new CCounterRowMetaData);
  14087. }
  14088. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14089. {
  14090. if (kind == TAKparallelgraphloop)
  14091. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14092. else
  14093. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14094. }
  14095. };
  14096. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14097. {
  14098. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14099. }
  14100. //=====================================================================================================
  14101. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14102. {
  14103. class OutputAdaptor : public CExtractMapperInput
  14104. {
  14105. bool stopped;
  14106. public:
  14107. CRoxieServerLibraryCallActivity *parent;
  14108. IOutputMetaData * meta = nullptr;
  14109. unsigned oid;
  14110. unsigned processed;
  14111. public:
  14112. OutputAdaptor()
  14113. {
  14114. parent = NULL;
  14115. oid = 0;
  14116. init();
  14117. }
  14118. ~OutputAdaptor()
  14119. {
  14120. if (traceStartStop)
  14121. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14122. if (processed && parent && parent->factory)
  14123. {
  14124. parent->factory->noteProcessed(oid, processed);
  14125. if (parent->ctx)
  14126. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
  14127. }
  14128. }
  14129. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14130. {
  14131. parent = _parent;
  14132. meta = _meta;
  14133. oid = _oid;
  14134. }
  14135. void init()
  14136. {
  14137. processed = 0;
  14138. stopped = false;
  14139. }
  14140. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14141. {
  14142. parent->start(oid, parentExtractSize, parentExtract, paused);
  14143. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14144. }
  14145. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14146. {
  14147. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14148. if (!oid) // Only need to set up once
  14149. {
  14150. parent->connectInputStreams(true); // To handle dependencies etc
  14151. }
  14152. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14153. }
  14154. //This override should not really be needed, but input is set up too late for the call to connect strands
  14155. virtual IOutputMetaData * queryOutputMeta() const
  14156. {
  14157. return meta;
  14158. }
  14159. virtual void stop()
  14160. {
  14161. if (!stopped)
  14162. {
  14163. stopped = true;
  14164. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14165. CExtractMapperInput::stop();
  14166. }
  14167. };
  14168. virtual void reset()
  14169. {
  14170. parent->reset(oid);
  14171. CExtractMapperInput::reset();
  14172. init();
  14173. };
  14174. virtual void checkAbort()
  14175. {
  14176. parent->checkAbort();
  14177. }
  14178. };
  14179. IHThorLibraryCallArg &helper;
  14180. unsigned numInputs;
  14181. unsigned numOutputs;
  14182. unsigned numActiveOutputs;
  14183. bool started;
  14184. OutputAdaptor* outputAdaptors;
  14185. CExtractMapperInput * * inputAdaptors;
  14186. bool * inputUsed;
  14187. bool * outputUsed;
  14188. Owned<IException> error;
  14189. CriticalSection crit;
  14190. rtlRowBuilder libraryExtractBuilder;
  14191. Owned<IActivityGraph> libraryGraph;
  14192. const LibraryCallFactoryExtra & extra;
  14193. public:
  14194. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14195. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14196. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14197. {
  14198. numInputs = _numInputs;
  14199. numOutputs = _numOutputs;
  14200. numActiveOutputs = numOutputs;
  14201. inputAdaptors = new CExtractMapperInput*[numInputs];
  14202. inputUsed = new bool[numInputs];
  14203. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14204. {
  14205. inputAdaptors[i1] = new CExtractMapperInput;
  14206. inputUsed[i1] = false;
  14207. }
  14208. outputAdaptors = new OutputAdaptor[numOutputs];
  14209. outputUsed = new bool[numOutputs];
  14210. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14211. {
  14212. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14213. outputUsed[i2] = false;
  14214. }
  14215. started = false;
  14216. }
  14217. ~CRoxieServerLibraryCallActivity()
  14218. {
  14219. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14220. ::Release(inputAdaptors[i1]);
  14221. delete [] inputAdaptors;
  14222. delete [] inputUsed;
  14223. delete [] outputAdaptors;
  14224. delete [] outputUsed;
  14225. }
  14226. virtual void onCreate(IHThorArg *_colocalParent)
  14227. {
  14228. CRoxieServerActivity::onCreate(_colocalParent);
  14229. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14230. libraryGraph->onCreate(_colocalParent);
  14231. //Now map the inputs and outputs to the adapters
  14232. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14233. for (unsigned i1=0; i1<numInputs; i1++)
  14234. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14235. for (unsigned i2=0; i2<numOutputs; i2++)
  14236. {
  14237. unsigned outputIndex = extra.outputs.item(i2);
  14238. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14239. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14240. outputAdaptors[i2].connectInputStreams(ctx, true);
  14241. }
  14242. }
  14243. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14244. {
  14245. CriticalBlock b(crit);
  14246. if (error)
  14247. throw error.getLink();
  14248. if (factory)
  14249. factory->noteStarted(oid);
  14250. if (!started)
  14251. {
  14252. // even though it is not complete, we don't want to run this again if it fails.
  14253. started = true;
  14254. //see notes on splitter above
  14255. try
  14256. {
  14257. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14258. }
  14259. catch (IException *E)
  14260. {
  14261. #ifdef TRACE_SPLIT
  14262. CTXLOG("spill %d caught exception in start", activityId);
  14263. #endif
  14264. error.set(E);
  14265. throw;
  14266. }
  14267. catch (...)
  14268. {
  14269. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14270. error.set(E);
  14271. throw E;
  14272. }
  14273. //recreate the parent extract, and use it to reinitialize the graphs...
  14274. libraryExtractBuilder.clear();
  14275. helper.createParentExtract(libraryExtractBuilder);
  14276. // 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
  14277. // some inputs before we see start on others.
  14278. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14279. {
  14280. if (inputUsed[i1])
  14281. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14282. else
  14283. inputAdaptors[i1]->queryInput()->stopall();
  14284. }
  14285. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14286. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14287. //call stop on all the unused inputs.
  14288. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14289. graph->beforeExecute();
  14290. ForEachItemIn(i3, extra.unusedOutputs)
  14291. {
  14292. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14293. output->stopall();
  14294. }
  14295. }
  14296. }
  14297. virtual void stop(unsigned oid)
  14298. {
  14299. CriticalBlock b(crit);
  14300. if (--numActiveOutputs == 0)
  14301. {
  14302. //call stop on all the unused inputs.
  14303. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14304. graph->beforeExecute();
  14305. ForEachItemIn(i3, extra.unusedOutputs)
  14306. {
  14307. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14308. output->stopall();
  14309. }
  14310. CRoxieServerActivity::stop();
  14311. }
  14312. }
  14313. void reset(unsigned oid)
  14314. {
  14315. started = false;
  14316. error.clear();
  14317. numActiveOutputs = numOutputs;
  14318. if (state != STATEreset) // make sure input is only reset once
  14319. {
  14320. CRoxieServerActivity::reset();
  14321. libraryGraph->reset();
  14322. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14323. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14324. {
  14325. if (!inputUsed[i1])
  14326. inputAdaptors[i1]->reset();
  14327. }
  14328. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14329. ForEachItemIn(i3, extra.unusedOutputs)
  14330. {
  14331. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14332. output->reset();
  14333. }
  14334. }
  14335. };
  14336. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14337. {
  14338. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14339. }
  14340. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14341. {
  14342. if (idx < numInputs && inputAdaptors[idx])
  14343. return inputAdaptors[idx]->queryInput();
  14344. else
  14345. return NULL;
  14346. }
  14347. public:
  14348. virtual const void *nextRow()
  14349. {
  14350. throwUnexpected(); // Internal logic error - we are not anybody's input
  14351. }
  14352. virtual IOutputMetaData * queryOutputMeta() const
  14353. {
  14354. throwUnexpected(); // should be called on outputs instead
  14355. }
  14356. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14357. {
  14358. assertex(idx!=(unsigned)-1);
  14359. assertex(!outputUsed[idx]);
  14360. outputUsed[idx] = true;
  14361. return &outputAdaptors[idx];
  14362. }
  14363. };
  14364. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14365. {
  14366. ForEachItemIn(i1, _other.outputs)
  14367. outputs.append(_other.outputs.item(i1));
  14368. ForEachItemIn(i2, _other.unusedOutputs)
  14369. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14370. maxOutputs = _other.maxOutputs;
  14371. graphid = _other.graphid;
  14372. libraryName.set(_other.libraryName);
  14373. embeddedGraphName.set(_other.embeddedGraphName);
  14374. interfaceHash = _other.interfaceHash;
  14375. embedded = _other.embedded;
  14376. }
  14377. void LibraryCallFactoryExtra::calcUnused()
  14378. {
  14379. for (unsigned i=0; i < maxOutputs; i++)
  14380. if (!outputs.contains(i))
  14381. unusedOutputs.append(i);
  14382. }
  14383. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14384. {
  14385. private:
  14386. CRoxieServerMultiInputInfo inputs;
  14387. LibraryCallFactoryExtra extra;
  14388. public:
  14389. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14390. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14391. {
  14392. extra.set(_extra);
  14393. extra.calcUnused();
  14394. setNumOutputs(extra.outputs.ordinality());
  14395. }
  14396. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14397. {
  14398. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14399. }
  14400. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14401. {
  14402. inputs.set(idx, source, sourceidx);
  14403. }
  14404. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14405. {
  14406. return inputs.get(idx, sourceidx);
  14407. }
  14408. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14409. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14410. {
  14411. addXrefLibraryInfo(reply, extra.libraryName);
  14412. }
  14413. };
  14414. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14415. {
  14416. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14417. }
  14418. //=====================================================================================================
  14419. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14420. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14421. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14422. {
  14423. protected:
  14424. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14425. PointerArrayOf<IEngineRowStream> selectedStreams;
  14426. PointerArrayOf<IStrandJunction> selectedJunctions;
  14427. public:
  14428. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14429. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14430. {
  14431. }
  14432. virtual void stop()
  14433. {
  14434. ForEachItemIn(i2, selectedStreams)
  14435. selectedStreams.item(i2)->stop();
  14436. CRoxieServerMultiInputBaseActivity::stop();
  14437. }
  14438. virtual unsigned __int64 queryLocalCycles() const
  14439. {
  14440. __int64 localCycles = totalCycles.totalCycles;
  14441. ForEachItemIn(i, selectedInputs)
  14442. {
  14443. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14444. }
  14445. if (localCycles < 0)
  14446. localCycles = 0;
  14447. return localCycles;
  14448. }
  14449. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14450. {
  14451. if (selectedInputs.isItem(idx))
  14452. return selectedInputs.item(idx);
  14453. else
  14454. return NULL;
  14455. }
  14456. virtual void reset()
  14457. {
  14458. ForEachItemIn(i, selectedInputs)
  14459. selectedInputs.item(i)->reset();
  14460. selectedInputs.kill();
  14461. selectedStreams.kill();
  14462. selectedJunctions.kill();
  14463. CRoxieServerMultiInputBaseActivity::reset();
  14464. }
  14465. virtual const void * nextRow()
  14466. {
  14467. throwUnexpected();
  14468. }
  14469. virtual unsigned numConcreteOutputs() const
  14470. {
  14471. return selectedInputs.ordinality();
  14472. }
  14473. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14474. {
  14475. return queryInput(idx);
  14476. }
  14477. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14478. {
  14479. if (selectedStreams.isItem(whichInput))
  14480. return selectedStreams.item(whichInput);
  14481. return NULL;
  14482. }
  14483. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14484. {
  14485. if (selectedJunctions.isItem(idx))
  14486. return selectedJunctions.item(idx);
  14487. return NULL;
  14488. }
  14489. };
  14490. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14491. {
  14492. IHThorNWayInputArg & helper;
  14493. public:
  14494. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14495. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14496. {
  14497. }
  14498. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14499. {
  14500. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14501. bool selectionIsAll;
  14502. size32_t selectionLen;
  14503. rtlDataAttr selection;
  14504. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14505. selectedInputs.kill();
  14506. selectedStreams.kill();
  14507. selectedJunctions.kill();
  14508. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14509. if (selectionIsAll)
  14510. {
  14511. for (unsigned i=0; i < numInputs; i++)
  14512. {
  14513. selectedInputs.append(inputArray[i]);
  14514. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14515. selectedJunctions.append(junctionArray[i]);
  14516. }
  14517. }
  14518. else
  14519. {
  14520. const size32_t * selections = (const size32_t *)selection.getdata();
  14521. unsigned max = selectionLen/sizeof(size32_t);
  14522. for (unsigned i = 0; i < max; i++)
  14523. {
  14524. unsigned nextIndex = selections[i];
  14525. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14526. for (unsigned j=i+1; j < max; j++)
  14527. {
  14528. if (nextIndex == selections[j])
  14529. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14530. }
  14531. if (nextIndex > numInputs || nextIndex > numStreams)
  14532. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14533. selectedInputs.append(inputArray[nextIndex-1]);
  14534. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14535. selectedJunctions.append(junctionArray[nextIndex-1]);
  14536. }
  14537. }
  14538. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14539. }
  14540. virtual void stop()
  14541. {
  14542. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs
  14543. }
  14544. };
  14545. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14546. {
  14547. public:
  14548. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14549. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14550. {
  14551. }
  14552. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14553. {
  14554. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14555. }
  14556. };
  14557. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14558. {
  14559. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14560. }
  14561. //=====================================================================================================
  14562. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14563. {
  14564. IHThorNWayGraphLoopResultReadArg & helper;
  14565. IArrayOf<IRoxieServerActivity> resultReaders;
  14566. Owned<IStrandJunction> *resultJunctions;
  14567. unsigned graphId;
  14568. bool grouped;
  14569. bool selectionIsAll;
  14570. size32_t selectionLen;
  14571. rtlDataAttr selection;
  14572. public:
  14573. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14574. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14575. {
  14576. grouped = helper.isGrouped();
  14577. graphId = _graphId;
  14578. selectionIsAll = false;
  14579. selectionLen = 0;
  14580. resultJunctions = NULL;
  14581. }
  14582. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14583. {
  14584. delete [] resultJunctions;
  14585. }
  14586. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14587. {
  14588. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14589. if (selectedInputs.ordinality() == 0)
  14590. {
  14591. initInputSelection();
  14592. unsigned max = selectionLen / sizeof(size32_t);
  14593. const size32_t * selections = (const size32_t *)selection.getdata();
  14594. IProbeManager * probeManager = NULL; // MORE!!
  14595. for (unsigned i = 0; i < max; i++)
  14596. {
  14597. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14598. resultReaders.append(*resultInput);
  14599. selectedInputs.append(resultInput);
  14600. resultInput->onCreate(colocalParent);
  14601. resultInput->start(parentExtractSize, parentExtract, paused);
  14602. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14603. selectedJunctions.append(resultJunctions[i]);
  14604. }
  14605. }
  14606. }
  14607. virtual void reset()
  14608. {
  14609. resultReaders.kill();
  14610. CRoxieServerNWayInputBaseActivity::reset();
  14611. ForEachItemIn(i, selectedStreams)
  14612. resetJunction(resultJunctions[i]);
  14613. }
  14614. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14615. {
  14616. ensureCreated();
  14617. basehelper.onStart(parentExtract, NULL);
  14618. initInputSelection();
  14619. unsigned max = selectionLen / sizeof(size32_t);
  14620. const size32_t * selections = (const size32_t *)selection.getdata();
  14621. for (unsigned i = 0; i < max; i++)
  14622. processor.noteUseIteration(selections[i]);
  14623. }
  14624. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14625. {
  14626. //selection etc. already initialised from the gatherIterationUsage() call.
  14627. unsigned max = selectionLen / sizeof(size32_t);
  14628. const size32_t * selections = (const size32_t *)selection.getdata();
  14629. resultJunctions = new Owned<IStrandJunction> [max];
  14630. for (unsigned i = 0; i < max; i++)
  14631. {
  14632. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  14633. selectedInputs.append(in);
  14634. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  14635. selectedJunctions.append(resultJunctions[i]);
  14636. }
  14637. }
  14638. protected:
  14639. void initInputSelection()
  14640. {
  14641. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14642. if (selectionIsAll)
  14643. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14644. }
  14645. };
  14646. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14647. {
  14648. unsigned graphId;
  14649. public:
  14650. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  14651. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  14652. {
  14653. }
  14654. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14655. {
  14656. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  14657. }
  14658. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14659. {
  14660. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14661. }
  14662. };
  14663. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  14664. {
  14665. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  14666. }
  14667. //=================================================================================
  14668. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  14669. {
  14670. public:
  14671. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  14672. IMPLEMENT_IINTERFACE
  14673. protected:
  14674. virtual const void * nextInputRow()
  14675. {
  14676. #ifdef TRACE_SEEK_REQUESTS
  14677. IRoxieContextLogger * logger = input->queryActivity();
  14678. const void * ret = doNextInputRow();
  14679. {
  14680. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14681. if (!ret)
  14682. xmlwrite.outputBool(true,"eof");
  14683. else if (input->queryOutputMeta()->hasXML())
  14684. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14685. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14686. }
  14687. return ret;
  14688. #else
  14689. return inputStream->ungroupedNextRow();
  14690. #endif
  14691. }
  14692. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14693. {
  14694. #ifdef TRACE_SEEK_REQUESTS
  14695. IRoxieContextLogger * logger = input->queryActivity();
  14696. {
  14697. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14698. if (input->queryOutputMeta()->hasXML())
  14699. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14700. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14701. numFields,
  14702. stepExtra.readAheadManyResults() ? "readahead " : "",
  14703. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14704. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14705. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14706. xmlwrite.str());
  14707. }
  14708. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14709. {
  14710. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14711. if (!ret)
  14712. xmlwrite.outputBool(true,"eof");
  14713. else if (input->queryOutputMeta()->hasXML())
  14714. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14715. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14716. numFields,
  14717. stepExtra.readAheadManyResults() ? "readahead " : "",
  14718. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14719. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14720. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14721. xmlwrite.str());
  14722. }
  14723. return ret;
  14724. #else
  14725. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14726. #endif
  14727. }
  14728. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14729. {
  14730. return input->gatherConjunctions(collector);
  14731. }
  14732. virtual void resetEOF()
  14733. {
  14734. inputStream->resetEOF();
  14735. }
  14736. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14737. {
  14738. return input->querySteppingMeta();
  14739. }
  14740. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14741. {
  14742. assertex(wasCompleteMatch);
  14743. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14744. }
  14745. protected:
  14746. IFinalRoxieInput * input;
  14747. IEngineRowStream * inputStream;
  14748. };
  14749. //=================================================================================
  14750. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  14751. {
  14752. public:
  14753. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14754. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14755. {
  14756. }
  14757. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14758. {
  14759. ForEachItemIn(ei, expandedInputs)
  14760. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  14761. ForEachItemIn(idx, expandedInputs)
  14762. startJunction(expandedJunctions.item(idx));
  14763. }
  14764. virtual void stop()
  14765. {
  14766. ForEachItemIn(i, expandedStreams)
  14767. expandedStreams.item(i)->stop();
  14768. CRoxieServerMultiInputBaseActivity::stop();
  14769. }
  14770. virtual void reset()
  14771. {
  14772. ForEachItemIn(idx, expandedInputs)
  14773. resetJunction(expandedJunctions.item(idx));
  14774. expandedInputs.kill();
  14775. expandedStreams.kill();
  14776. expandedJunctions.kill();
  14777. CRoxieServerMultiInputBaseActivity::reset();
  14778. }
  14779. protected:
  14780. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  14781. PointerArrayOf<IEngineRowStream> expandedStreams;
  14782. PointerArrayOf<IStrandJunction> expandedJunctions;
  14783. };
  14784. //=================================================================================
  14785. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  14786. {
  14787. public:
  14788. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14789. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14790. {
  14791. }
  14792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14793. {
  14794. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  14795. for (unsigned i=0; i < numInputs; i++)
  14796. {
  14797. IFinalRoxieInput * cur = inputArray[i];
  14798. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  14799. if (nWayInput)
  14800. {
  14801. nWayInput->start(parentExtractSize, parentExtract, paused);
  14802. unsigned numRealInputs = cur->numConcreteOutputs();
  14803. for (unsigned j = 0; j < numRealInputs; j++)
  14804. {
  14805. expandedInputs.append(cur->queryConcreteInput(j));
  14806. expandedStreams.append(cur->queryConcreteOutputStream(j));
  14807. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  14808. }
  14809. }
  14810. else
  14811. {
  14812. expandedInputs.append(cur);
  14813. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  14814. expandedStreams.append(queryConcreteOutputStream(i));
  14815. expandedJunctions.append(queryConcreteOutputJunction(i));
  14816. }
  14817. }
  14818. startExpandedInputs(parentExtractSize, parentExtract, paused);
  14819. }
  14820. };
  14821. //=================================================================================
  14822. class CRoxieStreamMerger : public CStreamMerger
  14823. {
  14824. public:
  14825. CRoxieStreamMerger() : CStreamMerger(true)
  14826. {
  14827. streamArray = NULL;
  14828. }
  14829. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  14830. {
  14831. CStreamMerger::initInputs(_numInputs);
  14832. streamArray = _streamArray;
  14833. }
  14834. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14835. {
  14836. const void * next;
  14837. bool matches = true;
  14838. if (seek)
  14839. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  14840. else
  14841. next = streamArray[i]->ungroupedNextRow();
  14842. pending[i] = next;
  14843. pendingMatches[i] = matches;
  14844. return (next != NULL);
  14845. }
  14846. virtual void releaseRow(const void * row)
  14847. {
  14848. ReleaseRoxieRow(row);
  14849. }
  14850. protected:
  14851. IEngineRowStream **streamArray;
  14852. };
  14853. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14854. {
  14855. public:
  14856. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14857. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  14858. helper((IHThorNWayMergeArg &)basehelper)
  14859. {
  14860. initializedMeta = false;
  14861. }
  14862. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14863. {
  14864. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14865. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14866. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  14867. }
  14868. virtual void stop()
  14869. {
  14870. merger.done();
  14871. CRoxieServerNaryActivity::stop();
  14872. }
  14873. virtual void reset()
  14874. {
  14875. merger.cleanup();
  14876. CRoxieServerNaryActivity::reset();
  14877. initializedMeta = false;
  14878. }
  14879. virtual const void * nextRow()
  14880. {
  14881. ActivityTimer t(totalCycles, timeActivities);
  14882. const void * next = merger.nextRow();
  14883. if (next)
  14884. processed++;
  14885. return next;
  14886. }
  14887. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14888. {
  14889. ActivityTimer t(totalCycles, timeActivities);
  14890. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14891. if (next)
  14892. processed++;
  14893. return next;
  14894. }
  14895. virtual IInputSteppingMeta * querySteppingMeta()
  14896. {
  14897. if (expandedStreams.ordinality() == 0)
  14898. return NULL;
  14899. if (!initializedMeta)
  14900. {
  14901. meta.init(helper.querySteppingMeta(), false);
  14902. ForEachItemIn(i, expandedStreams)
  14903. {
  14904. if (meta.getNumFields() == 0)
  14905. break;
  14906. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14907. meta.intersect(inputMeta);
  14908. }
  14909. initializedMeta = true;
  14910. }
  14911. if (meta.getNumFields() == 0)
  14912. return NULL;
  14913. return &meta;
  14914. }
  14915. protected:
  14916. IHThorNWayMergeArg &helper;
  14917. CRoxieStreamMerger merger;
  14918. CSteppingMeta meta;
  14919. bool initializedMeta;
  14920. };
  14921. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14922. {
  14923. public:
  14924. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14925. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14926. {
  14927. }
  14928. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14929. {
  14930. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  14931. }
  14932. };
  14933. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14934. {
  14935. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14936. }
  14937. //=================================================================================
  14938. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14939. {
  14940. public:
  14941. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14942. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  14943. helper((IHThorNWayMergeJoinArg &)basehelper)
  14944. {
  14945. }
  14946. virtual void onCreate(IHThorArg *_colocalParent)
  14947. {
  14948. CRoxieServerNaryActivity::onCreate(_colocalParent);
  14949. ICodeContext * codectx = ctx->queryCodeContext();
  14950. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  14951. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  14952. }
  14953. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14954. {
  14955. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14956. ForEachItemIn(i1, expandedInputs)
  14957. {
  14958. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  14959. processor.addInput(stepInput);
  14960. }
  14961. processor.beforeProcessing(inputAllocator, outputAllocator);
  14962. }
  14963. virtual void stop()
  14964. {
  14965. processor.afterProcessing();
  14966. CRoxieServerNaryActivity::stop();
  14967. }
  14968. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14969. {
  14970. return processor.gatherConjunctions(collector);
  14971. }
  14972. virtual void resetEOF()
  14973. {
  14974. processor.queryResetEOF();
  14975. }
  14976. virtual const void * nextRow()
  14977. {
  14978. ActivityTimer t(totalCycles, timeActivities);
  14979. const void * next = processor.nextRow();
  14980. if (next)
  14981. processed++;
  14982. return next;
  14983. }
  14984. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14985. {
  14986. ActivityTimer t(totalCycles, timeActivities);
  14987. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14988. if (next)
  14989. processed++;
  14990. return next;
  14991. }
  14992. virtual IInputSteppingMeta * querySteppingMeta()
  14993. {
  14994. return processor.queryInputSteppingMeta();
  14995. }
  14996. protected:
  14997. IHThorNWayMergeJoinArg & helper;
  14998. CMergeJoinProcessor & processor;
  14999. Owned<IEngineRowAllocator> inputAllocator;
  15000. Owned<IEngineRowAllocator> outputAllocator;
  15001. };
  15002. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15003. {
  15004. public:
  15005. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15006. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15007. {
  15008. }
  15009. protected:
  15010. CAndMergeJoinProcessor andProcessor;
  15011. };
  15012. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15013. {
  15014. public:
  15015. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15016. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15017. {
  15018. }
  15019. protected:
  15020. CAndLeftMergeJoinProcessor andLeftProcessor;
  15021. };
  15022. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15023. {
  15024. public:
  15025. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15026. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15027. {
  15028. }
  15029. protected:
  15030. CMofNMergeJoinProcessor mofnProcessor;
  15031. };
  15032. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15033. {
  15034. public:
  15035. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15036. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15037. {
  15038. }
  15039. protected:
  15040. CProximityJoinProcessor proximityProcessor;
  15041. };
  15042. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15043. {
  15044. unsigned flags;
  15045. public:
  15046. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15047. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15048. {
  15049. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15050. flags = helper->getJoinFlags();
  15051. }
  15052. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15053. {
  15054. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15055. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15056. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15057. {
  15058. case IHThorNWayMergeJoinArg::MJFinner:
  15059. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15060. case IHThorNWayMergeJoinArg::MJFleftonly:
  15061. case IHThorNWayMergeJoinArg::MJFleftouter:
  15062. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15063. case IHThorNWayMergeJoinArg::MJFmofn:
  15064. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15065. default:
  15066. throwUnexpected();
  15067. }
  15068. }
  15069. };
  15070. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15071. {
  15072. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15073. }
  15074. //=================================================================================
  15075. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15076. {
  15077. IHThorNWaySelectArg &helper;
  15078. public:
  15079. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15080. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15081. helper((IHThorNWaySelectArg &)basehelper)
  15082. {
  15083. }
  15084. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15085. {
  15086. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15087. unsigned whichInput = helper.getInputIndex();
  15088. selectedInput = nullptr;
  15089. selectedStream = nullptr;
  15090. if (whichInput--)
  15091. {
  15092. for (unsigned i=0; i < numInputs; i++)
  15093. {
  15094. IFinalRoxieInput * cur = inputArray[i];
  15095. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15096. if (nWayInput)
  15097. {
  15098. nWayInput->start(parentExtractSize, parentExtract, paused);
  15099. unsigned numRealInputs = cur->numConcreteOutputs();
  15100. if (whichInput < numRealInputs)
  15101. {
  15102. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15103. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15104. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15105. break;
  15106. }
  15107. whichInput -= numRealInputs;
  15108. }
  15109. else
  15110. {
  15111. if (whichInput == 0)
  15112. {
  15113. expandedInputs.append(cur);
  15114. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15115. expandedStreams.append(queryConcreteOutputStream(i));
  15116. expandedJunctions.append(queryConcreteOutputJunction(i));
  15117. break;
  15118. }
  15119. whichInput -= 1;
  15120. }
  15121. }
  15122. }
  15123. if (expandedInputs.ordinality())
  15124. {
  15125. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15126. selectedInput = expandedInputs.item(0);
  15127. selectedStream = expandedStreams.item(0);
  15128. }
  15129. }
  15130. const void * nextRow()
  15131. {
  15132. ActivityTimer t(totalCycles, timeActivities);
  15133. if (!selectedStream)
  15134. return NULL;
  15135. return selectedStream->nextRow();
  15136. }
  15137. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15138. {
  15139. if (!selectedInput)
  15140. return false;
  15141. return selectedInput->gatherConjunctions(collector);
  15142. }
  15143. virtual void resetEOF()
  15144. {
  15145. if (selectedStream)
  15146. selectedStream->resetEOF();
  15147. }
  15148. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15149. {
  15150. ActivityTimer t(totalCycles, timeActivities);
  15151. if (!selectedStream)
  15152. return NULL;
  15153. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15154. }
  15155. IInputSteppingMeta * querySteppingMeta()
  15156. {
  15157. if (selectedInput)
  15158. return selectedInput->querySteppingMeta();
  15159. return NULL;
  15160. }
  15161. protected:
  15162. IFinalRoxieInput * selectedInput = nullptr;
  15163. IEngineRowStream * selectedStream = nullptr;
  15164. Owned<IStrandJunction> selectedJunction;
  15165. };
  15166. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15167. {
  15168. public:
  15169. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15170. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15171. {
  15172. }
  15173. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15174. {
  15175. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15176. }
  15177. };
  15178. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15179. {
  15180. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15181. }
  15182. //=================================================================================
  15183. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15184. {
  15185. protected:
  15186. IHThorRemoteArg &helper;
  15187. CRemoteResultAdaptor remote;
  15188. public:
  15189. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15190. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15191. helper((IHThorRemoteArg &)basehelper),
  15192. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15193. {
  15194. }
  15195. virtual const IResolvedFile *queryVarFileInfo() const
  15196. {
  15197. return NULL;
  15198. }
  15199. virtual void onCreate(IHThorArg *_colocalParent)
  15200. {
  15201. CRoxieServerActivity::onCreate(_colocalParent);
  15202. remote.onCreate(_colocalParent);
  15203. }
  15204. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15205. {
  15206. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15207. remote.onStart(parentExtractSize, parentExtract);
  15208. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15209. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15210. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15211. remote.flush();
  15212. remote.senddone();
  15213. }
  15214. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15215. {
  15216. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15217. }
  15218. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15219. {
  15220. if (idx==(unsigned)-1)
  15221. idx = 0;
  15222. return idx ? NULL: &remote;
  15223. }
  15224. virtual void reset()
  15225. {
  15226. processed = remote.processed;
  15227. remote.processed = 0;
  15228. CRoxieServerActivity::reset();
  15229. }
  15230. virtual void onLimitExceeded(bool isKeyed)
  15231. {
  15232. if (traceLevel > 4)
  15233. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15234. helper.onLimitExceeded();
  15235. }
  15236. virtual const void *createLimitFailRow(bool isKeyed)
  15237. {
  15238. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15239. }
  15240. virtual const void *nextRow()
  15241. {
  15242. throwUnexpected(); // I am nobody's input
  15243. }
  15244. };
  15245. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15246. {
  15247. public:
  15248. RemoteActivityId remoteId;
  15249. bool isRoot;
  15250. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15251. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15252. {
  15253. }
  15254. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15255. {
  15256. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15257. }
  15258. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15259. {
  15260. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15261. }
  15262. virtual bool isSink() const
  15263. {
  15264. //I don't think the action version of this is implemented - but this would be the code
  15265. return isRoot && !meta.queryOriginal();
  15266. }
  15267. virtual const StatisticsMapping &queryStatsMapping() const
  15268. {
  15269. return allStatistics; // Child queries...
  15270. }
  15271. };
  15272. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15273. {
  15274. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15275. }
  15276. //=================================================================================
  15277. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15278. {
  15279. IHThorIterateArg &helper;
  15280. OwnedConstRoxieRow defaultRecord;
  15281. OwnedConstRoxieRow left;
  15282. OwnedConstRoxieRow right;
  15283. unsigned counter;
  15284. public:
  15285. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15286. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15287. helper((IHThorIterateArg &)basehelper)
  15288. {
  15289. counter = 0;
  15290. }
  15291. virtual bool needsAllocator() const { return true; }
  15292. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15293. {
  15294. counter = 0;
  15295. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15296. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15297. size32_t thisSize = helper.createDefault(rowBuilder);
  15298. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15299. }
  15300. virtual void reset()
  15301. {
  15302. defaultRecord.clear();
  15303. right.clear();
  15304. left.clear();
  15305. CRoxieServerActivity::reset();
  15306. }
  15307. virtual const void * nextRow()
  15308. {
  15309. ActivityTimer t(totalCycles, timeActivities);
  15310. loop
  15311. {
  15312. right.setown(inputStream->nextRow());
  15313. if (!right)
  15314. {
  15315. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15316. left.clear();
  15317. counter = 0;
  15318. if (skippedGroup) continue;
  15319. return NULL;
  15320. }
  15321. try
  15322. {
  15323. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15324. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15325. if (outSize)
  15326. {
  15327. left.setown(rowBuilder.finalizeRowClear(outSize));
  15328. processed++;
  15329. return left.getLink();
  15330. }
  15331. }
  15332. catch (IException *E)
  15333. {
  15334. throw makeWrappedException(E);
  15335. }
  15336. }
  15337. }
  15338. };
  15339. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15340. {
  15341. public:
  15342. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15343. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15344. {
  15345. }
  15346. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15347. {
  15348. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15349. }
  15350. };
  15351. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15352. {
  15353. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15354. }
  15355. //=================================================================================
  15356. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15357. {
  15358. IHThorProcessArg &helper;
  15359. OwnedConstRoxieRow curRight;
  15360. OwnedConstRoxieRow initialRight;
  15361. unsigned counter;
  15362. Owned<IEngineRowAllocator> rightRowAllocator;
  15363. public:
  15364. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15365. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15366. {
  15367. counter = 0;
  15368. }
  15369. virtual bool needsAllocator() const { return true; }
  15370. virtual void onCreate(IHThorArg *_colocalParent)
  15371. {
  15372. CRoxieServerActivity::onCreate(_colocalParent);
  15373. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15374. }
  15375. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15376. {
  15377. counter = 0;
  15378. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15379. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15380. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15381. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15382. curRight.set(initialRight);
  15383. }
  15384. virtual const void * nextRow()
  15385. {
  15386. ActivityTimer t(totalCycles, timeActivities);
  15387. try
  15388. {
  15389. loop
  15390. {
  15391. const void * in = inputStream->nextRow();
  15392. if (!in)
  15393. {
  15394. bool eog = (curRight != initialRight); // processed any records?
  15395. counter = 0;
  15396. curRight.set(initialRight);
  15397. if (eog)
  15398. return NULL;
  15399. in = inputStream->nextRow();
  15400. if (!in)
  15401. return NULL;
  15402. }
  15403. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15404. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15405. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15406. ReleaseRoxieRow(in);
  15407. if (outSize)
  15408. {
  15409. //MORE: This should be returned...
  15410. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15411. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15412. processed++;
  15413. return rowBuilder.finalizeRowClear(outSize);
  15414. }
  15415. }
  15416. }
  15417. catch (IException *E)
  15418. {
  15419. throw makeWrappedException(E);
  15420. }
  15421. }
  15422. };
  15423. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15424. {
  15425. public:
  15426. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15427. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15428. {
  15429. }
  15430. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15431. {
  15432. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15433. }
  15434. };
  15435. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15436. {
  15437. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15438. }
  15439. //=================================================================================
  15440. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15441. {
  15442. IHThorGroupArg &helper;
  15443. bool endPending;
  15444. bool eof;
  15445. bool first;
  15446. unsigned numGroups;
  15447. unsigned numGroupMax;
  15448. unsigned numProcessedLastGroup;
  15449. const void *next;
  15450. public:
  15451. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15452. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15453. {
  15454. next = NULL;
  15455. endPending = false;
  15456. eof = false;
  15457. first = true;
  15458. numGroups = 0;
  15459. numGroupMax = 0;
  15460. numProcessedLastGroup = 0;
  15461. }
  15462. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15463. {
  15464. endPending = false;
  15465. eof = false;
  15466. first = true;
  15467. numGroups = 0;
  15468. numGroupMax = 0;
  15469. numProcessedLastGroup = processed;
  15470. assertex(next == NULL);
  15471. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15472. }
  15473. virtual void reset()
  15474. {
  15475. noteStatistic(StNumGroups, numGroups);
  15476. noteStatistic(StNumGroupMax, numGroupMax);
  15477. ReleaseClearRoxieRow(next);
  15478. CRoxieServerActivity::reset();
  15479. }
  15480. virtual const void * nextRow()
  15481. {
  15482. ActivityTimer t(totalCycles, timeActivities);
  15483. if (first)
  15484. {
  15485. next = inputStream->nextRow();
  15486. first = false;
  15487. }
  15488. if (eof || endPending)
  15489. {
  15490. endPending = false;
  15491. return NULL;
  15492. }
  15493. const void * prev = next;
  15494. next = inputStream->ungroupedNextRow();
  15495. if (next)
  15496. {
  15497. assertex(prev);
  15498. if (!helper.isSameGroup(prev, next))
  15499. {
  15500. noteEndOfGroup();
  15501. endPending = true;
  15502. }
  15503. }
  15504. else
  15505. {
  15506. noteEndOfGroup();
  15507. eof = true;
  15508. }
  15509. if (prev)
  15510. processed++;
  15511. return prev;
  15512. }
  15513. inline void noteEndOfGroup()
  15514. {
  15515. unsigned numThisGroup = processed - numProcessedLastGroup;
  15516. if (numThisGroup == 0)
  15517. return;
  15518. numProcessedLastGroup = processed;
  15519. if (numThisGroup > numGroupMax)
  15520. numGroupMax = numThisGroup;
  15521. numGroups++;
  15522. }
  15523. };
  15524. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15525. {
  15526. public:
  15527. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15528. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15529. {
  15530. }
  15531. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15532. {
  15533. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15534. }
  15535. virtual const StatisticsMapping &queryStatsMapping() const
  15536. {
  15537. return groupStatistics;
  15538. }
  15539. };
  15540. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15541. {
  15542. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15543. }
  15544. //=================================================================================
  15545. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15546. {
  15547. unsigned __int64 limit;
  15548. unsigned __int64 skip;
  15549. unsigned doneThisGroup;
  15550. IHThorFirstNArg &helper;
  15551. public:
  15552. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15553. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15554. {
  15555. doneThisGroup = 0;
  15556. limit = 0;
  15557. skip = 0;
  15558. }
  15559. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15560. {
  15561. doneThisGroup = 0;
  15562. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15563. limit = helper.getLimit();
  15564. skip = helper.numToSkip();
  15565. lateStart(parentExtractSize, parentExtract, limit > 0);
  15566. if (limit + skip >= limit)
  15567. limit += skip;
  15568. }
  15569. const void * nextRow()
  15570. {
  15571. ActivityTimer t(totalCycles, timeActivities);
  15572. if (eof)
  15573. return NULL;
  15574. const void *ret;
  15575. loop
  15576. {
  15577. ret = inputStream->nextRow();
  15578. if (!ret)
  15579. {
  15580. if (meta.isGrouped())
  15581. {
  15582. if (doneThisGroup > skip)
  15583. {
  15584. doneThisGroup = 0;
  15585. return NULL;
  15586. }
  15587. doneThisGroup = 0;
  15588. }
  15589. ret = inputStream->nextRow();
  15590. if (!ret)
  15591. {
  15592. eof = true;
  15593. return NULL;
  15594. }
  15595. }
  15596. doneThisGroup++;
  15597. if (doneThisGroup > skip)
  15598. break;
  15599. ReleaseRoxieRow(ret);
  15600. }
  15601. if (doneThisGroup <= limit)
  15602. {
  15603. processed++;
  15604. return ret;
  15605. }
  15606. ReleaseRoxieRow(ret);
  15607. if (meta.isGrouped())
  15608. {
  15609. while ((ret = inputStream->nextRow()) != NULL)
  15610. ReleaseRoxieRow(ret);
  15611. doneThisGroup = 0;
  15612. }
  15613. else
  15614. eof = true;
  15615. return NULL;
  15616. }
  15617. };
  15618. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15619. {
  15620. public:
  15621. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15622. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15623. {
  15624. }
  15625. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15626. {
  15627. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  15628. }
  15629. };
  15630. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15631. {
  15632. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15633. }
  15634. //=================================================================================
  15635. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15636. {
  15637. bool done;
  15638. IHThorSelectNArg &helper;
  15639. public:
  15640. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15641. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15642. {
  15643. done = false;
  15644. }
  15645. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15646. {
  15647. done = false;
  15648. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15649. }
  15650. const void *defaultRow()
  15651. {
  15652. if (!rowAllocator)
  15653. ensureRowAllocator(); // We delay as often not needed...
  15654. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15655. size32_t thisSize = helper.createDefault(rowBuilder);
  15656. return rowBuilder.finalizeRowClear(thisSize);
  15657. }
  15658. virtual const void * nextRow()
  15659. {
  15660. ActivityTimer t(totalCycles, timeActivities);
  15661. if (done)
  15662. return NULL;
  15663. done = true;
  15664. processed++; // always going to return a row!
  15665. unsigned __int64 index = helper.getRowToSelect();
  15666. while (--index)
  15667. {
  15668. const void * next = inputStream->ungroupedNextRow();
  15669. if (!next)
  15670. return defaultRow();
  15671. ReleaseRoxieRow(next);
  15672. }
  15673. const void * next = inputStream->ungroupedNextRow();
  15674. if (!next)
  15675. next = defaultRow();
  15676. return next;
  15677. }
  15678. };
  15679. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15680. {
  15681. public:
  15682. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15683. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15684. {
  15685. }
  15686. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15687. {
  15688. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  15689. }
  15690. };
  15691. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15692. {
  15693. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15694. }
  15695. //=================================================================================
  15696. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15697. {
  15698. IHThorJoinArg &helper;
  15699. ICompare *collate;
  15700. OwnedRowArray group;
  15701. bool matchedLeft;
  15702. BoolArray matchedRight;
  15703. bool eof;
  15704. bool first;
  15705. unsigned leftIndex;
  15706. unsigned rightIndex;
  15707. unsigned rightOuterIndex;
  15708. unsigned joinLimit;
  15709. unsigned atmostLimit;
  15710. unsigned atmostsTriggered;
  15711. unsigned abortLimit;
  15712. unsigned keepLimit;
  15713. unsigned joinCounter;
  15714. bool leftOuterJoin;
  15715. bool rightOuterJoin;
  15716. bool exclude;
  15717. bool limitFail;
  15718. bool limitOnFail;
  15719. bool cloneLeft;
  15720. bool forceSpill;
  15721. OwnedConstRoxieRow defaultLeft;
  15722. OwnedConstRoxieRow defaultRight;
  15723. OwnedConstRoxieRow lhs;
  15724. Owned<IException> failingLimit;
  15725. bool failingOuterAtmost;
  15726. Owned<IEngineRowAllocator> defaultAllocator;
  15727. Owned<IRHLimitedCompareHelper> limitedhelper;
  15728. Owned<CRHDualCache> dualcache;
  15729. Owned<IGroupedInput> groupedInput;
  15730. IRowStream *dualCacheInput;
  15731. bool fillGroup()
  15732. {
  15733. group.clear();
  15734. matchedLeft = false;
  15735. matchedRight.kill();
  15736. failingOuterAtmost = false;
  15737. const void * next;
  15738. unsigned groupCount = 0;
  15739. while((next = groupedInput->nextRow()) != NULL)
  15740. {
  15741. if(groupCount==abortLimit)
  15742. {
  15743. if(limitFail)
  15744. failLimit(next);
  15745. if (ctx->queryDebugContext())
  15746. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15747. if(limitOnFail)
  15748. {
  15749. assertex(!failingLimit);
  15750. try
  15751. {
  15752. failLimit(next);
  15753. }
  15754. catch(IException * except)
  15755. {
  15756. failingLimit.setown(except);
  15757. }
  15758. assertex(failingLimit != NULL);
  15759. group.append(next);
  15760. groupCount++;
  15761. break;
  15762. }
  15763. group.clear();
  15764. groupCount = 0;
  15765. while(next)
  15766. {
  15767. ReleaseRoxieRow(next);
  15768. next = groupedInput->nextRow();
  15769. }
  15770. }
  15771. else if(groupCount==atmostLimit)
  15772. {
  15773. atmostsTriggered++;
  15774. if(leftOuterJoin)
  15775. {
  15776. group.append(next);
  15777. groupCount++;
  15778. failingOuterAtmost = true;
  15779. break;
  15780. }
  15781. else
  15782. {
  15783. group.clear();
  15784. groupCount = 0;
  15785. while (next)
  15786. {
  15787. ReleaseRoxieRow(next);
  15788. next = groupedInput->nextRow();
  15789. }
  15790. }
  15791. }
  15792. else
  15793. {
  15794. group.append(next);
  15795. groupCount++;
  15796. }
  15797. }
  15798. if(group.ordinality()==0)
  15799. {
  15800. eof = true;
  15801. return false;
  15802. }
  15803. leftIndex = 0;
  15804. rightIndex = 0;
  15805. rightOuterIndex = 0;
  15806. joinCounter = 0;
  15807. joinLimit = keepLimit;
  15808. ForEachItemIn(idx, group)
  15809. matchedRight.append(false);
  15810. return true;
  15811. }
  15812. void failLimit(const void * next)
  15813. {
  15814. helper.onMatchAbortLimitExceeded();
  15815. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15816. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15817. {
  15818. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15819. }
  15820. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15821. }
  15822. virtual bool needsAllocator() const { return true; }
  15823. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15824. {
  15825. try
  15826. {
  15827. if (cloneLeft && !except)
  15828. {
  15829. LinkRoxieRow(curLeft);
  15830. return curLeft;
  15831. }
  15832. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15833. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15834. if (outsize)
  15835. return rowBuilder.finalizeRowClear(outsize);
  15836. else
  15837. return NULL;
  15838. }
  15839. catch (IException *E)
  15840. {
  15841. throw makeWrappedException(E);
  15842. }
  15843. }
  15844. void createDefaultLeft()
  15845. {
  15846. if (!defaultLeft)
  15847. {
  15848. if (!defaultAllocator)
  15849. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15850. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15851. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15852. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15853. }
  15854. }
  15855. void createDefaultRight()
  15856. {
  15857. if (!defaultRight)
  15858. {
  15859. if (!defaultAllocator)
  15860. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  15861. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15862. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15863. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15864. }
  15865. }
  15866. public:
  15867. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  15868. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  15869. {
  15870. collate = helper.queryCompareLeftRight();
  15871. eof = false;
  15872. first = true;
  15873. keepLimit = 0;
  15874. atmostLimit = 0;
  15875. atmostsTriggered = 0;
  15876. unsigned joinFlags = helper.getJoinFlags();
  15877. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15878. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15879. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15880. exclude = (joinFlags & JFexclude) != 0;
  15881. abortLimit = 0;
  15882. joinLimit = 0;
  15883. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15884. getLimitType(joinFlags, limitFail, limitOnFail);
  15885. if((joinFlags & JFslidingmatch) != 0)
  15886. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15887. failingOuterAtmost = false;
  15888. matchedLeft = false;
  15889. leftIndex = 0;
  15890. rightIndex = 0;
  15891. rightOuterIndex = 0;
  15892. joinCounter = 0;
  15893. dualCacheInput = NULL;
  15894. }
  15895. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15896. {
  15897. eof = false;
  15898. first = true;
  15899. failingLimit.clear();
  15900. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15901. keepLimit = helper.getKeepLimit();
  15902. if(keepLimit == 0)
  15903. keepLimit = (unsigned)-1;
  15904. atmostsTriggered = 0;
  15905. atmostLimit = helper.getJoinLimit();
  15906. if(atmostLimit == 0)
  15907. atmostLimit = (unsigned)-1;
  15908. else
  15909. assertex(!rightOuterJoin);
  15910. abortLimit = helper.getMatchAbortLimit();
  15911. if (abortLimit == 0)
  15912. abortLimit = (unsigned)-1;
  15913. if (rightOuterJoin)
  15914. createDefaultLeft();
  15915. if (leftOuterJoin || limitOnFail)
  15916. createDefaultRight();
  15917. ICompare *compareLeft = helper.queryCompareLeft();
  15918. if (helper.isLeftAlreadySorted())
  15919. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  15920. else
  15921. {
  15922. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  15923. RoxieSortAlgorithm sortAlgorithm;
  15924. if (forceSpill)
  15925. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  15926. else
  15927. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  15928. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  15929. }
  15930. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15931. { //limited match join (s[1..n])
  15932. dualcache.setown(new CRHDualCache());
  15933. dualcache->init(groupedInput);
  15934. dualCacheInput = dualcache->queryOut1();
  15935. failingOuterAtmost = false;
  15936. matchedLeft = false;
  15937. leftIndex = 0;
  15938. rightOuterIndex = 0;
  15939. joinCounter = 0;
  15940. limitedhelper.setown(createRHLimitedCompareHelper());
  15941. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15942. }
  15943. }
  15944. virtual void reset()
  15945. {
  15946. if (atmostsTriggered)
  15947. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15948. group.clear();
  15949. groupedInput.clear();
  15950. CRoxieServerActivity::reset();
  15951. defaultLeft.clear();
  15952. defaultRight.clear();
  15953. }
  15954. virtual const void * nextRow()
  15955. {
  15956. ActivityTimer t(totalCycles, timeActivities);
  15957. if (limitedhelper)
  15958. {
  15959. while(!eof) //limited match join
  15960. {
  15961. if (!group.isItem(rightIndex))
  15962. {
  15963. lhs.setown(dualCacheInput->nextRow());
  15964. if (lhs)
  15965. {
  15966. rightIndex = 0;
  15967. joinCounter = 0;
  15968. group.clear();
  15969. limitedhelper->getGroup(group,lhs);
  15970. }
  15971. else
  15972. {
  15973. eof = true;
  15974. }
  15975. }
  15976. if (group.isItem(rightIndex))
  15977. {
  15978. const void * rhs = group.item(rightIndex++);
  15979. if(helper.match(lhs, rhs))
  15980. {
  15981. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15982. if(ret)
  15983. {
  15984. processed++;
  15985. return ret;
  15986. }
  15987. }
  15988. }
  15989. }
  15990. return NULL;
  15991. }
  15992. else
  15993. {
  15994. if (first)
  15995. {
  15996. first = false;
  15997. fillGroup();
  15998. }
  15999. while(!eof)
  16000. {
  16001. if(failingOuterAtmost)
  16002. while(group.isItem(leftIndex))
  16003. {
  16004. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  16005. if(ret)
  16006. {
  16007. processed++;
  16008. return ret;
  16009. }
  16010. }
  16011. if((joinLimit == 0) || !group.isItem(rightIndex))
  16012. {
  16013. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16014. {
  16015. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  16016. if(ret)
  16017. {
  16018. matchedLeft = true;
  16019. processed++;
  16020. return ret;
  16021. }
  16022. }
  16023. leftIndex++;
  16024. matchedLeft = false;
  16025. rightIndex = 0;
  16026. joinCounter = 0;
  16027. joinLimit = keepLimit;
  16028. }
  16029. if(!group.isItem(leftIndex))
  16030. {
  16031. if(failingLimit || failingOuterAtmost)
  16032. {
  16033. const void * lhs;
  16034. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16035. {
  16036. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16037. ReleaseRoxieRow(lhs);
  16038. if(ret)
  16039. {
  16040. processed++;
  16041. return ret;
  16042. }
  16043. }
  16044. failingLimit.clear();
  16045. }
  16046. if(rightOuterJoin && !failingLimit)
  16047. while(group.isItem(rightOuterIndex))
  16048. if(!matchedRight.item(rightOuterIndex++))
  16049. {
  16050. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  16051. if(ret)
  16052. {
  16053. processed++;
  16054. return ret;
  16055. }
  16056. }
  16057. if(!fillGroup())
  16058. return NULL;
  16059. continue;
  16060. }
  16061. const void * lhs = group.item(leftIndex);
  16062. if(failingLimit)
  16063. {
  16064. leftIndex++;
  16065. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  16066. if(ret)
  16067. {
  16068. processed++;
  16069. return ret;
  16070. }
  16071. }
  16072. else
  16073. {
  16074. const void * rhs = group.item(rightIndex++);
  16075. if(helper.match(lhs, rhs))
  16076. {
  16077. matchedLeft = true;
  16078. matchedRight.replace(true, rightIndex-1);
  16079. if(!exclude)
  16080. {
  16081. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  16082. if(ret)
  16083. {
  16084. processed++;
  16085. joinLimit--;
  16086. return ret;
  16087. }
  16088. }
  16089. }
  16090. }
  16091. }
  16092. return NULL;
  16093. }
  16094. }
  16095. };
  16096. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16097. {
  16098. bool forceSpill;
  16099. public:
  16100. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16101. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16102. {
  16103. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16104. }
  16105. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16106. {
  16107. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16108. }
  16109. virtual const StatisticsMapping &queryStatsMapping() const
  16110. {
  16111. return joinStatistics;
  16112. }
  16113. };
  16114. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16115. {
  16116. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16117. }
  16118. //=====================================================================================================
  16119. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16120. {
  16121. private:
  16122. class LookupTable : public CInterface
  16123. {
  16124. public:
  16125. LookupTable(IHThorHashJoinArg &helper)
  16126. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16127. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16128. {
  16129. size = 0;
  16130. }
  16131. virtual const void *find(const void * left) const = 0;
  16132. virtual const void *findNext(const void * left) const = 0;
  16133. protected:
  16134. ICompare * leftRightCompare;
  16135. ICompare * rightCompare;
  16136. IHash * leftHash;
  16137. IHash * rightHash;
  16138. unsigned size;
  16139. };
  16140. class DedupLookupTable : public LookupTable
  16141. {
  16142. public:
  16143. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16144. : LookupTable(helper)
  16145. {
  16146. size = (4*rightRows.length())/3 + 1;
  16147. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16148. ForEachItemIn(idx, rightRows)
  16149. add(rightRows.item(idx));
  16150. }
  16151. ~DedupLookupTable()
  16152. {
  16153. roxiemem::ReleaseRoxieRowArray(size, table);
  16154. free(table);
  16155. }
  16156. virtual const void *find(const void * left) const
  16157. {
  16158. unsigned index = leftHash->hash(left) % size;
  16159. unsigned start = index;
  16160. while (table[index])
  16161. {
  16162. if(leftRightCompare->docompare(left, table[index]) == 0)
  16163. return table[index];
  16164. index++;
  16165. if (index==size)
  16166. index = 0;
  16167. if (index==start)
  16168. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16169. }
  16170. return NULL;
  16171. }
  16172. virtual const void *findNext(const void * left) const
  16173. {
  16174. return NULL;
  16175. }
  16176. protected:
  16177. void add(const void * right)
  16178. {
  16179. unsigned index = rightHash->hash(right) % size;
  16180. unsigned start = index;
  16181. while (table[index])
  16182. {
  16183. if (rightCompare->docompare(table[index], right) == 0)
  16184. {
  16185. ReleaseRoxieRow(right);
  16186. return;
  16187. }
  16188. index++;
  16189. if (index==size)
  16190. index = 0;
  16191. if (index==start)
  16192. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16193. }
  16194. table[index] = right;
  16195. }
  16196. const void * * table;
  16197. };
  16198. class FewLookupTable : public LookupTable
  16199. {
  16200. public:
  16201. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16202. : LookupTable(helper)
  16203. {
  16204. size = (4*rightRows.length())/3 + 1;
  16205. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16206. findex = fstart = BadIndex;
  16207. ForEachItemIn(idx, rightRows)
  16208. add(rightRows.item(idx));
  16209. }
  16210. ~FewLookupTable()
  16211. {
  16212. roxiemem::ReleaseRoxieRowArray(size, table);
  16213. free(table);
  16214. }
  16215. virtual const void *find(const void * left) const
  16216. {
  16217. fstart = leftHash->hash(left) % size;
  16218. findex = fstart;
  16219. return doFind(left);
  16220. }
  16221. virtual const void *findNext(const void * left) const
  16222. {
  16223. if (findex == BadIndex)
  16224. return NULL;
  16225. advance();
  16226. return doFind(left);
  16227. }
  16228. protected:
  16229. void add(const void * right)
  16230. {
  16231. unsigned start = rightHash->hash(right) % size;
  16232. unsigned index = start;
  16233. while (table[index])
  16234. {
  16235. index++;
  16236. if (index==size)
  16237. index = 0;
  16238. if (index==start)
  16239. throwUnexpected(); //table is full, should never happen
  16240. }
  16241. table[index] = right;
  16242. }
  16243. void advance() const
  16244. {
  16245. findex++;
  16246. if(findex==size)
  16247. findex = 0;
  16248. if(findex==fstart)
  16249. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16250. }
  16251. const void *doFind(const void * left) const
  16252. {
  16253. while(table[findex])
  16254. {
  16255. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16256. return table[findex];
  16257. advance();
  16258. }
  16259. findex = BadIndex;
  16260. return NULL;
  16261. }
  16262. const void * * table;
  16263. unsigned mutable fstart;
  16264. unsigned mutable findex;
  16265. static unsigned const BadIndex;
  16266. };
  16267. class ManyLookupTable : public LookupTable
  16268. {
  16269. public:
  16270. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16271. : LookupTable(helper)
  16272. {
  16273. rightRows.swapWith(rowtable);
  16274. UInt64Array groups;
  16275. unsigned numRows = rowtable.length();
  16276. if (numRows)
  16277. {
  16278. unsigned groupStart = 0;
  16279. const void *groupStartRow = rowtable.item(0);
  16280. for (unsigned i=1; i < numRows; i++)
  16281. {
  16282. const void *thisRow = rowtable.item(i);
  16283. if (rightCompare->docompare(groupStartRow, thisRow))
  16284. {
  16285. groups.append(makeint64(groupStart, i-groupStart));
  16286. groupStart = i;
  16287. groupStartRow = thisRow;
  16288. }
  16289. }
  16290. groups.append(makeint64(groupStart, numRows-groupStart));
  16291. }
  16292. size = (4*groups.length())/3 + 1;
  16293. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16294. ForEachItemIn(idx, groups)
  16295. {
  16296. unsigned __int64 group = groups.item(idx);
  16297. unsigned groupstart = high(group);
  16298. const void *row = rowtable.item(groupstart);
  16299. add(row, group);
  16300. }
  16301. }
  16302. ~ManyLookupTable()
  16303. {
  16304. roxiemem::ReleaseRoxieRows(rowtable);
  16305. free(table);
  16306. }
  16307. void add(const void *row, unsigned __int64 group)
  16308. {
  16309. unsigned start = rightHash->hash(row) % size;
  16310. unsigned index = start;
  16311. while (table[index])
  16312. {
  16313. index++;
  16314. if (index==size)
  16315. index = 0;
  16316. if (index==start)
  16317. throwUnexpected(); //table is full, should never happen
  16318. }
  16319. table[index] = group;
  16320. }
  16321. virtual const void *find(const void * left) const
  16322. {
  16323. unsigned index = leftHash->hash(left) % size;
  16324. unsigned start = index;
  16325. while (table[index])
  16326. {
  16327. __uint64 group = table[index];
  16328. currentMatch = high(group);
  16329. const void *right = rowtable.item(currentMatch);
  16330. if (leftRightCompare->docompare(left, right) == 0)
  16331. {
  16332. currentMatch++;
  16333. matchCount = low(group) - 1;
  16334. return right;
  16335. }
  16336. index++;
  16337. if (index==size)
  16338. index = 0;
  16339. if (index==start)
  16340. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16341. }
  16342. matchCount = 0;
  16343. return NULL;
  16344. }
  16345. virtual const void *findNext(const void * left) const
  16346. {
  16347. if (!matchCount)
  16348. return NULL;
  16349. matchCount--;
  16350. return rowtable.item(currentMatch++);
  16351. }
  16352. protected:
  16353. __uint64 *table;
  16354. ConstPointerArray rowtable;
  16355. mutable unsigned currentMatch = 0;
  16356. mutable unsigned matchCount = 0;
  16357. };
  16358. IHThorHashJoinArg &helper;
  16359. bool leftOuterJoin;
  16360. bool exclude;
  16361. bool eog;
  16362. bool many;
  16363. bool dedupRHS;
  16364. bool useFewTable;
  16365. bool matchedGroup;
  16366. const void *left;
  16367. OwnedConstRoxieRow defaultRight;
  16368. Owned<LookupTable> table;
  16369. unsigned keepLimit;
  16370. unsigned atmostLimit;
  16371. unsigned atmostsTriggered;
  16372. unsigned limitLimit;
  16373. unsigned joinCounter;
  16374. bool limitFail;
  16375. bool limitOnFail;
  16376. bool hasGroupLimit;
  16377. bool isSmartJoin;
  16378. unsigned keepCount;
  16379. bool gotMatch;
  16380. bool cloneLeft;
  16381. ConstPointerArray rightGroup;
  16382. aindex_t rightGroupIndex;
  16383. Owned<IException> failingLimit;
  16384. ConstPointerArray filteredRight;
  16385. ThorActivityKind activityKind;
  16386. Owned<IEngineRowAllocator> defaultRightAllocator;
  16387. void createDefaultRight()
  16388. {
  16389. if (!defaultRight)
  16390. {
  16391. if (!defaultRightAllocator)
  16392. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16393. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16394. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16395. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16396. }
  16397. }
  16398. public:
  16399. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16400. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16401. {
  16402. unsigned joinFlags = helper.getJoinFlags();
  16403. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16404. assertex((joinFlags & JFrightouter) == 0);
  16405. exclude = (joinFlags & JFexclude) != 0;
  16406. many = (joinFlags & JFmanylookup) != 0;
  16407. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16408. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16409. left = NULL;
  16410. activityKind = factory->getKind();
  16411. eog = false;
  16412. matchedGroup = false;
  16413. gotMatch = false;
  16414. keepLimit = 0;
  16415. keepCount = 0;
  16416. joinCounter = 0;
  16417. atmostLimit = 0;
  16418. atmostsTriggered = 0;
  16419. limitLimit = 0;
  16420. rightGroupIndex = 0;
  16421. hasGroupLimit = false;
  16422. isSmartJoin = (joinFlags & JFsmart) != 0;
  16423. getLimitType(joinFlags, limitFail, limitOnFail);
  16424. }
  16425. void loadRight()
  16426. {
  16427. ConstPointerArray rightset;
  16428. try
  16429. {
  16430. const void * next;
  16431. while(true)
  16432. {
  16433. next = inputStream1->ungroupedNextRow();
  16434. if(!next)
  16435. break;
  16436. rightset.append(next);
  16437. }
  16438. if (!dedupRHS)
  16439. {
  16440. if (useFewTable)
  16441. {
  16442. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16443. }
  16444. else
  16445. {
  16446. if (!helper.isRightAlreadySorted())
  16447. {
  16448. if (helper.getJoinFlags() & JFunstable)
  16449. {
  16450. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16451. }
  16452. else
  16453. {
  16454. unsigned rightord = rightset.ordinality();
  16455. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16456. void **temp = (void **) tempAttr.bufferBase();
  16457. void **_rows = const_cast<void * *>(rightset.getArray());
  16458. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16459. }
  16460. }
  16461. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16462. }
  16463. }
  16464. else
  16465. {
  16466. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16467. }
  16468. }
  16469. catch (...)
  16470. {
  16471. roxiemem::ReleaseRoxieRows(rightset);
  16472. throw;
  16473. }
  16474. };
  16475. virtual void reset()
  16476. {
  16477. if (atmostsTriggered)
  16478. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16479. CRoxieServerTwoInputActivity::reset();
  16480. ReleaseClearRoxieRow(left);
  16481. defaultRight.clear();
  16482. table.clear();
  16483. }
  16484. virtual bool needsAllocator() const { return true; }
  16485. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16486. {
  16487. eog = false;
  16488. matchedGroup = false;
  16489. left = NULL;
  16490. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16491. keepLimit = helper.getKeepLimit();
  16492. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16493. atmostsTriggered = 0;
  16494. atmostLimit = helper.getJoinLimit();
  16495. limitLimit = helper.getMatchAbortLimit();
  16496. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16497. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16498. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16499. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16500. switch (activityKind)
  16501. {
  16502. case TAKlookupjoin:
  16503. case TAKlookupdenormalizegroup:
  16504. case TAKsmartjoin:
  16505. case TAKsmartdenormalizegroup:
  16506. if (leftOuterJoin)
  16507. createDefaultRight();
  16508. break;
  16509. }
  16510. if (limitOnFail)
  16511. createDefaultRight();
  16512. }
  16513. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16514. {
  16515. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16516. {
  16517. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16518. puller->setInput(0, _sourceIdx, _in);
  16519. _in = puller;
  16520. _sourceIdx = 0;
  16521. }
  16522. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16523. }
  16524. virtual const void * nextRow()
  16525. {
  16526. ActivityTimer t(totalCycles, timeActivities);
  16527. if(!table)
  16528. loadRight();
  16529. switch (activityKind)
  16530. {
  16531. case TAKlookupjoin:
  16532. case TAKsmartjoin:
  16533. return nextRowJoin();
  16534. case TAKlookupdenormalize:
  16535. case TAKlookupdenormalizegroup:
  16536. case TAKsmartdenormalize:
  16537. case TAKsmartdenormalizegroup:
  16538. return nextRowDenormalize();
  16539. }
  16540. throwUnexpected();
  16541. }
  16542. private:
  16543. const void * nextRowJoin()
  16544. {
  16545. if(!table)
  16546. loadRight();
  16547. while(true)
  16548. {
  16549. const void * right = NULL;
  16550. if(!left)
  16551. {
  16552. left = inputStream->nextRow();
  16553. keepCount = keepLimit;
  16554. joinCounter = 0;
  16555. if(!left)
  16556. {
  16557. if (isSmartJoin)
  16558. left = inputStream->nextRow();
  16559. if (!left)
  16560. {
  16561. if(matchedGroup || eog)
  16562. {
  16563. matchedGroup = false;
  16564. eog = true;
  16565. return NULL;
  16566. }
  16567. eog = true;
  16568. continue;
  16569. }
  16570. }
  16571. eog = false;
  16572. gotMatch = false;
  16573. right = getRightFirst();
  16574. }
  16575. else
  16576. right = getRightNext();
  16577. const void * ret = NULL;
  16578. if(failingLimit)
  16579. {
  16580. ret = joinException(left, failingLimit);
  16581. }
  16582. else
  16583. {
  16584. while(right)
  16585. {
  16586. if(helper.match(left, right))
  16587. {
  16588. gotMatch = true;
  16589. if(exclude)
  16590. break;
  16591. ret = joinRecords(left, right, ++joinCounter);
  16592. if(ret)
  16593. {
  16594. processed++;
  16595. break;
  16596. }
  16597. }
  16598. right = getRightNext();
  16599. ret = NULL;
  16600. }
  16601. if(leftOuterJoin && !gotMatch)
  16602. {
  16603. ret = joinRecords(left, defaultRight, 0);
  16604. gotMatch = true;
  16605. }
  16606. }
  16607. if(ret)
  16608. {
  16609. matchedGroup = true;
  16610. processed++;
  16611. if(!many || (--keepCount == 0) || failingLimit)
  16612. {
  16613. ReleaseClearRoxieRow(left);
  16614. failingLimit.clear();
  16615. }
  16616. return ret;
  16617. }
  16618. ReleaseClearRoxieRow(left);
  16619. }
  16620. }
  16621. const void * nextRowDenormalize()
  16622. {
  16623. while(true)
  16624. {
  16625. left = inputStream->nextRow();
  16626. if(!left)
  16627. {
  16628. if (!matchedGroup || isSmartJoin)
  16629. left = inputStream->nextRow();
  16630. if (!left)
  16631. {
  16632. matchedGroup = false;
  16633. return NULL;
  16634. }
  16635. }
  16636. gotMatch = false;
  16637. const void * right = getRightFirst();
  16638. const void * ret = NULL;
  16639. if (failingLimit)
  16640. ret = joinException(left, failingLimit);
  16641. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16642. {
  16643. OwnedConstRoxieRow newLeft;
  16644. newLeft.set(left);
  16645. unsigned rowSize = 0;
  16646. unsigned leftCount = 0;
  16647. keepCount = keepLimit;
  16648. while (right)
  16649. {
  16650. try
  16651. {
  16652. if (helper.match(left, right))
  16653. {
  16654. gotMatch = true;
  16655. if (exclude)
  16656. break;
  16657. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16658. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16659. if (thisSize)
  16660. {
  16661. rowSize = thisSize;
  16662. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16663. }
  16664. if(!many || (--keepCount == 0))
  16665. break;
  16666. }
  16667. right = getRightNext();
  16668. }
  16669. catch (IException *E)
  16670. {
  16671. throw makeWrappedException(E);
  16672. }
  16673. }
  16674. if (rowSize)
  16675. ret = newLeft.getClear();
  16676. else if (leftOuterJoin && !gotMatch)
  16677. {
  16678. ret = left;
  16679. left = NULL;
  16680. }
  16681. }
  16682. else
  16683. {
  16684. filteredRight.kill();
  16685. keepCount = keepLimit;
  16686. while (right)
  16687. {
  16688. if (helper.match(left, right))
  16689. {
  16690. gotMatch = true;
  16691. if(exclude)
  16692. break;
  16693. filteredRight.append(right);
  16694. if(!many || (--keepCount == 0))
  16695. break;
  16696. }
  16697. right = getRightNext();
  16698. }
  16699. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16700. ret = denormalizeRecords(left, filteredRight);
  16701. filteredRight.kill();
  16702. }
  16703. ReleaseRoxieRow(left);
  16704. left = NULL;
  16705. failingLimit.clear();
  16706. if(ret)
  16707. {
  16708. matchedGroup = true;
  16709. processed++;
  16710. return ret;
  16711. }
  16712. }
  16713. }
  16714. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16715. {
  16716. if (cloneLeft)
  16717. {
  16718. LinkRoxieRow(left);
  16719. return left;
  16720. }
  16721. try
  16722. {
  16723. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16724. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16725. if (outSize)
  16726. return rowBuilder.finalizeRowClear(outSize);
  16727. else
  16728. return NULL;
  16729. }
  16730. catch (IException *E)
  16731. {
  16732. throw makeWrappedException(E);
  16733. }
  16734. }
  16735. const void * joinException(const void * left, IException * except)
  16736. {
  16737. try
  16738. {
  16739. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16740. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16741. if (outSize)
  16742. return rowBuilder.finalizeRowClear(outSize);
  16743. else
  16744. return NULL;
  16745. }
  16746. catch (IException *E)
  16747. {
  16748. throw makeWrappedException(E);
  16749. }
  16750. }
  16751. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16752. {
  16753. try
  16754. {
  16755. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16756. unsigned numRows = rows.ordinality();
  16757. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16758. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16759. if (outSize)
  16760. return rowBuilder.finalizeRowClear(outSize);
  16761. else
  16762. return NULL;
  16763. }
  16764. catch (IException *E)
  16765. {
  16766. throw makeWrappedException(E);
  16767. }
  16768. }
  16769. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16770. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16771. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16772. const void *fillRightGroup()
  16773. {
  16774. rightGroup.kill();
  16775. for(const void * right = table->find(left); right; right = table->findNext(left))
  16776. {
  16777. rightGroup.append(right);
  16778. if(rightGroup.ordinality() > limitLimit)
  16779. {
  16780. if(limitFail)
  16781. failLimit();
  16782. gotMatch = true;
  16783. if (ctx->queryDebugContext())
  16784. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16785. if(limitOnFail)
  16786. {
  16787. assertex(!failingLimit);
  16788. try
  16789. {
  16790. failLimit();
  16791. }
  16792. catch(IException * e)
  16793. {
  16794. failingLimit.setown(e);
  16795. }
  16796. assertex(failingLimit != NULL);
  16797. }
  16798. else
  16799. {
  16800. rightGroup.kill();
  16801. }
  16802. break;
  16803. }
  16804. if(rightGroup.ordinality() > atmostLimit)
  16805. {
  16806. atmostsTriggered++;
  16807. rightGroup.kill();
  16808. break;
  16809. }
  16810. }
  16811. rightGroupIndex = 0;
  16812. return readRightGroup();
  16813. }
  16814. void failLimit()
  16815. {
  16816. helper.onMatchAbortLimitExceeded();
  16817. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16818. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16819. {
  16820. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16821. }
  16822. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16823. }
  16824. };
  16825. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16826. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16827. {
  16828. public:
  16829. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16830. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16831. {
  16832. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16833. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16834. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16835. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16836. }
  16837. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16838. {
  16839. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  16840. }
  16841. virtual const StatisticsMapping &queryStatsMapping() const
  16842. {
  16843. return joinStatistics;
  16844. }
  16845. protected:
  16846. bool useFewTable;
  16847. };
  16848. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16849. {
  16850. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16851. }
  16852. //=====================================================================================================
  16853. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16854. {
  16855. private:
  16856. IHThorAllJoinArg &helper;
  16857. bool leftOuterJoin;
  16858. bool rightOuterJoin;
  16859. bool exclude;
  16860. OwnedConstRoxieRow defaultRight;
  16861. OwnedConstRoxieRow defaultLeft;
  16862. Owned<IEngineRowAllocator> defaultRightAllocator;
  16863. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16864. const void *left;
  16865. unsigned countForLeft;
  16866. ConstPointerArray rightset;
  16867. BoolArray matchedRight; // MORE - could use a bitset...
  16868. unsigned keepLimit;
  16869. bool started;
  16870. bool eog;
  16871. bool eos;
  16872. bool matchedLeft;
  16873. bool matchedGroup;
  16874. bool leftIsGrouped;
  16875. bool cloneLeft;
  16876. unsigned rightIndex;
  16877. unsigned joinCounter;
  16878. unsigned rightOrdinality;
  16879. ThorActivityKind activityKind;
  16880. ConstPointerArray filteredRight;
  16881. void createDefaultLeft()
  16882. {
  16883. if (!defaultLeft)
  16884. {
  16885. if (!defaultLeftAllocator)
  16886. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16887. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16888. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16889. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16890. }
  16891. }
  16892. void createDefaultRight()
  16893. {
  16894. if (!defaultRight)
  16895. {
  16896. if (!defaultRightAllocator)
  16897. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16898. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16899. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16900. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16901. }
  16902. }
  16903. public:
  16904. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16905. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16906. {
  16907. unsigned joinFlags = helper.getJoinFlags();
  16908. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16909. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16910. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16911. keepLimit = (unsigned) -1;
  16912. exclude = (joinFlags & JFexclude) != 0;
  16913. left = NULL;
  16914. started = true;
  16915. eog = false;
  16916. eos = false;
  16917. matchedLeft = false;
  16918. matchedGroup = false;
  16919. activityKind = factory->getKind();
  16920. rightIndex = 0;
  16921. rightOrdinality = 0;
  16922. leftIsGrouped = false;
  16923. countForLeft = 0;
  16924. joinCounter = 0;
  16925. }
  16926. virtual void reset()
  16927. {
  16928. defaultRight.clear();
  16929. defaultLeft.clear();
  16930. ReleaseRoxieRows(rightset);
  16931. matchedRight.kill();
  16932. CRoxieServerTwoInputActivity::reset();
  16933. }
  16934. virtual bool needsAllocator() const { return true; }
  16935. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16936. {
  16937. eog = false;
  16938. eos = false;
  16939. matchedLeft = false;
  16940. matchedGroup = false;
  16941. started = false;
  16942. left = NULL;
  16943. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16944. keepLimit = helper.getKeepLimit();
  16945. if(keepLimit==0)
  16946. keepLimit = (unsigned) -1;
  16947. countForLeft = keepLimit;
  16948. joinCounter = 0;
  16949. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16950. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16951. createDefaultRight();
  16952. if(rightOuterJoin)
  16953. createDefaultLeft();
  16954. }
  16955. void loadRight()
  16956. {
  16957. const void * next;
  16958. while(true)
  16959. {
  16960. next = inputStream1->ungroupedNextRow();
  16961. if(!next)
  16962. break;
  16963. rightset.append(next);
  16964. matchedRight.append(false);
  16965. }
  16966. rightIndex = 0;
  16967. joinCounter = 0;
  16968. rightOrdinality = rightset.ordinality();
  16969. }
  16970. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16971. {
  16972. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16973. {
  16974. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16975. puller->setInput(0, _sourceIdx, _in);
  16976. _in = puller;
  16977. _sourceIdx = 0;
  16978. }
  16979. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16980. }
  16981. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16982. {
  16983. // MORE - could share some code with lookup join
  16984. if (cloneLeft)
  16985. {
  16986. LinkRoxieRow(left);
  16987. return left;
  16988. }
  16989. try
  16990. {
  16991. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16992. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16993. if (outSize)
  16994. return rowBuilder.finalizeRowClear(outSize);
  16995. else
  16996. return NULL;
  16997. }
  16998. catch (IException *E)
  16999. {
  17000. throw makeWrappedException(E);
  17001. }
  17002. }
  17003. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  17004. {
  17005. try
  17006. {
  17007. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17008. unsigned numRows = rows.ordinality();
  17009. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17010. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  17011. if (outSize)
  17012. return rowBuilder.finalizeRowClear(outSize);
  17013. else
  17014. return NULL;
  17015. }
  17016. catch (IException *E)
  17017. {
  17018. throw makeWrappedException(E);
  17019. }
  17020. }
  17021. virtual const void *nextRow()
  17022. {
  17023. ActivityTimer t(totalCycles, timeActivities);
  17024. if(!started)
  17025. {
  17026. started = true;
  17027. left = inputStream->nextRow();
  17028. matchedLeft = false;
  17029. countForLeft = keepLimit;
  17030. joinCounter = 0;
  17031. if(left == NULL)
  17032. {
  17033. eos = true;
  17034. return NULL;
  17035. }
  17036. loadRight();
  17037. }
  17038. const void * ret;
  17039. const void * right;
  17040. if(eos)
  17041. return NULL;
  17042. while(true)
  17043. {
  17044. ret = NULL;
  17045. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17046. {
  17047. if(leftOuterJoin && left && !matchedLeft)
  17048. {
  17049. switch(activityKind)
  17050. {
  17051. case TAKalljoin:
  17052. ret = joinRecords(left, defaultRight, 0);
  17053. break;
  17054. case TAKalldenormalize:
  17055. ret = left;
  17056. left = NULL;
  17057. break;
  17058. case TAKalldenormalizegroup:
  17059. filteredRight.kill();
  17060. ret = denormalizeRecords(left, filteredRight);
  17061. break;
  17062. default:
  17063. throwUnexpected();
  17064. }
  17065. }
  17066. rightIndex = 0;
  17067. joinCounter = 0;
  17068. ReleaseRoxieRow(left);
  17069. left = NULL;
  17070. if(ret)
  17071. {
  17072. matchedGroup = true;
  17073. processed++;
  17074. return ret;
  17075. }
  17076. }
  17077. if(!left)
  17078. {
  17079. left = inputStream->nextRow();
  17080. matchedLeft = false;
  17081. countForLeft = keepLimit;
  17082. joinCounter = 0;
  17083. }
  17084. if(!left)
  17085. {
  17086. if(eog)
  17087. {
  17088. eos = true;
  17089. matchedGroup = false;
  17090. return NULL;
  17091. }
  17092. eog = true;
  17093. if (matchedGroup && leftIsGrouped)
  17094. {
  17095. matchedGroup = false;
  17096. return NULL;
  17097. }
  17098. matchedGroup = false;
  17099. continue;
  17100. }
  17101. eog = false;
  17102. switch(activityKind)
  17103. {
  17104. case TAKalljoin:
  17105. while(rightIndex < rightOrdinality)
  17106. {
  17107. right = rightset.item(rightIndex);
  17108. if(helper.match(left, right))
  17109. {
  17110. matchedLeft = true;
  17111. matchedRight.replace(true, rightIndex);
  17112. if(!exclude)
  17113. ret = joinRecords(left, right, ++joinCounter);
  17114. }
  17115. rightIndex++;
  17116. if(ret)
  17117. {
  17118. countForLeft--;
  17119. matchedGroup = true;
  17120. processed++;
  17121. return ret;
  17122. }
  17123. }
  17124. break;
  17125. case TAKalldenormalize:
  17126. {
  17127. OwnedConstRoxieRow newLeft;
  17128. newLeft.set(left);
  17129. unsigned rowSize = 0;
  17130. unsigned leftCount = 0;
  17131. while((rightIndex < rightOrdinality) && countForLeft)
  17132. {
  17133. right = rightset.item(rightIndex);
  17134. if(helper.match(left, right))
  17135. {
  17136. matchedLeft = true;
  17137. matchedRight.replace(true, rightIndex);
  17138. if(!exclude)
  17139. {
  17140. try
  17141. {
  17142. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17143. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  17144. if(thisSize)
  17145. {
  17146. rowSize = thisSize;
  17147. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17148. --countForLeft;
  17149. }
  17150. }
  17151. catch (IException *e)
  17152. {
  17153. throw makeWrappedException(e);
  17154. }
  17155. }
  17156. }
  17157. rightIndex++;
  17158. }
  17159. if(rowSize)
  17160. {
  17161. processed++;
  17162. return newLeft.getClear();
  17163. }
  17164. }
  17165. break;
  17166. case TAKalldenormalizegroup:
  17167. filteredRight.kill();
  17168. while((rightIndex < rightOrdinality) && countForLeft)
  17169. {
  17170. right = rightset.item(rightIndex);
  17171. if(helper.match(left, right))
  17172. {
  17173. matchedLeft = true;
  17174. matchedRight.replace(true, rightIndex);
  17175. filteredRight.append(right);
  17176. --countForLeft;
  17177. }
  17178. ++rightIndex;
  17179. }
  17180. if(!exclude && filteredRight.ordinality())
  17181. {
  17182. ret = denormalizeRecords(left, filteredRight);
  17183. filteredRight.kill();
  17184. if(ret)
  17185. {
  17186. processed++;
  17187. return ret;
  17188. }
  17189. }
  17190. break;
  17191. default:
  17192. throwUnexpected();
  17193. }
  17194. }
  17195. }
  17196. };
  17197. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17198. {
  17199. public:
  17200. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17201. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17202. {
  17203. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17204. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17205. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17206. }
  17207. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17208. {
  17209. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17210. }
  17211. virtual const StatisticsMapping &queryStatsMapping() const
  17212. {
  17213. return joinStatistics;
  17214. }
  17215. };
  17216. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17217. {
  17218. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17219. }
  17220. //=====================================================================================================
  17221. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17222. {
  17223. unsigned limit;
  17224. bool hasBest;
  17225. bool eoi;
  17226. const void **sorted;
  17227. unsigned sortedCount;
  17228. unsigned curIndex;
  17229. IHThorTopNArg &helper;
  17230. ICompare &compare;
  17231. public:
  17232. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17233. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17234. {
  17235. sorted = NULL;
  17236. sortedCount = 0;
  17237. curIndex = 0;
  17238. limit = 0;
  17239. eoi = false;
  17240. hasBest = false;
  17241. }
  17242. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17243. {
  17244. assertex(sorted == NULL);
  17245. sortedCount = 0;
  17246. curIndex = 0;
  17247. eoi = false;
  17248. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17249. limit = (unsigned) helper.getLimit();
  17250. hasBest = helper.hasBest();
  17251. lateStart(parentExtractSize, parentExtract, limit > 0);
  17252. // MORE - should we use an expanding array instead?
  17253. if (limit > 0)
  17254. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17255. }
  17256. virtual void reset()
  17257. {
  17258. if (sorted)
  17259. {
  17260. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17261. curIndex = 0;
  17262. sortedCount = 0;
  17263. ReleaseRoxieRow(sorted);
  17264. sorted = NULL;
  17265. }
  17266. CRoxieServerLateStartActivity::reset();
  17267. }
  17268. bool abortEarly()
  17269. {
  17270. if (hasBest && (sortedCount == limit))
  17271. {
  17272. int compare = helper.compareBest(sorted[sortedCount-1]);
  17273. if (compare == 0)
  17274. {
  17275. if (meta.isGrouped())
  17276. {
  17277. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17278. const void * next;
  17279. while ((next = inputStream->nextRow()) != NULL)
  17280. ReleaseRoxieRow(next);
  17281. }
  17282. else
  17283. eoi = true;
  17284. return true;
  17285. }
  17286. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17287. if (compare < 0)
  17288. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17289. }
  17290. return false;
  17291. }
  17292. void getSorted()
  17293. {
  17294. curIndex = 0;
  17295. sortedCount = 0;
  17296. if(eoi)
  17297. return;
  17298. const void * next;
  17299. while ((next = inputStream->nextRow()) != NULL)
  17300. {
  17301. if (sortedCount < limit)
  17302. {
  17303. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17304. sortedCount++;
  17305. if(abortEarly())
  17306. return;
  17307. }
  17308. else
  17309. {
  17310. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17311. {
  17312. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17313. ReleaseRoxieRow(sorted[sortedCount]);
  17314. if(abortEarly())
  17315. return;
  17316. }
  17317. else
  17318. {
  17319. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17320. }
  17321. }
  17322. }
  17323. }
  17324. virtual const void * nextRow()
  17325. {
  17326. ActivityTimer t(totalCycles, timeActivities);
  17327. if (eof)
  17328. return NULL;
  17329. if (curIndex >= sortedCount)
  17330. {
  17331. bool eog = sortedCount != 0;
  17332. getSorted();
  17333. if(sortedCount == 0)
  17334. {
  17335. eof = true;
  17336. return NULL;
  17337. }
  17338. if (eog)
  17339. return NULL;
  17340. }
  17341. processed++;
  17342. return sorted[curIndex++];
  17343. }
  17344. };
  17345. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17346. {
  17347. public:
  17348. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17349. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17350. {
  17351. }
  17352. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17353. {
  17354. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17355. }
  17356. };
  17357. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17358. {
  17359. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17360. }
  17361. //=================================================================================
  17362. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17363. {
  17364. protected:
  17365. unsigned __int64 rowLimit;
  17366. IHThorLimitArg &helper;
  17367. public:
  17368. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17369. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17370. {
  17371. rowLimit = 0;
  17372. }
  17373. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17374. {
  17375. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17376. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17377. }
  17378. virtual const void *nextRow()
  17379. {
  17380. ActivityTimer t(totalCycles, timeActivities);
  17381. const void * ret = inputStream->nextRow();
  17382. if (ret)
  17383. {
  17384. processed++;
  17385. if (processed > rowLimit)
  17386. {
  17387. ReleaseRoxieRow(ret);
  17388. if (traceLevel > 4)
  17389. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17390. helper.onLimitExceeded();
  17391. }
  17392. }
  17393. return ret;
  17394. }
  17395. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17396. {
  17397. ActivityTimer t(totalCycles, timeActivities);
  17398. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17399. if (ret)
  17400. {
  17401. if (wasCompleteMatch)
  17402. processed++;
  17403. if (processed > rowLimit)
  17404. {
  17405. ReleaseRoxieRow(ret);
  17406. if (traceLevel > 4)
  17407. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17408. helper.onLimitExceeded();
  17409. }
  17410. }
  17411. return ret;
  17412. }
  17413. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17414. {
  17415. return input->gatherConjunctions(collector);
  17416. }
  17417. virtual void resetEOF()
  17418. {
  17419. //Do not reset the rowLimit
  17420. inputStream->resetEOF();
  17421. }
  17422. IInputSteppingMeta * querySteppingMeta()
  17423. {
  17424. return input->querySteppingMeta();
  17425. }
  17426. };
  17427. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17428. {
  17429. public:
  17430. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17431. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17432. {
  17433. }
  17434. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17435. {
  17436. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17437. }
  17438. };
  17439. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17440. {
  17441. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17442. }
  17443. //=====================================================================================================
  17444. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17445. {
  17446. ConstPointerArray buff;
  17447. bool started;
  17448. unsigned index;
  17449. IHThorLimitTransformExtra * transformExtra;
  17450. public:
  17451. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17452. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17453. {
  17454. transformExtra = NULL;
  17455. started = false;
  17456. index = 0;
  17457. if (_onFail)
  17458. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  17459. }
  17460. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17461. {
  17462. started = false;
  17463. index = 0;
  17464. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17465. }
  17466. virtual void reset()
  17467. {
  17468. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17469. buff.kill();
  17470. index = 0;
  17471. started = false;
  17472. CRoxieServerLimitActivity::reset();
  17473. }
  17474. virtual const void *nextRow()
  17475. {
  17476. ActivityTimer t(totalCycles, timeActivities);
  17477. if (!started)
  17478. pullInput();
  17479. if (buff.isItem(index))
  17480. {
  17481. const void * next = buff.item(index++);
  17482. if(next)
  17483. processed++;
  17484. return next;
  17485. }
  17486. return NULL;
  17487. }
  17488. protected:
  17489. void pullInput()
  17490. {
  17491. unsigned count = 0;
  17492. loop
  17493. {
  17494. const void * next = inputStream->nextRow();
  17495. if (next == NULL)
  17496. {
  17497. next = inputStream->nextRow();
  17498. if(next == NULL)
  17499. break;
  17500. buff.append(NULL);
  17501. }
  17502. count++;
  17503. if (count > rowLimit)
  17504. {
  17505. ReleaseRoxieRow(next);
  17506. ReleaseRoxieRows(buff);
  17507. if (ctx->queryDebugContext())
  17508. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17509. if (transformExtra)
  17510. {
  17511. ensureRowAllocator();
  17512. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17513. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  17514. if (outSize)
  17515. buff.append(rowBuilder.finalizeRowClear(outSize));
  17516. }
  17517. break;
  17518. }
  17519. buff.append(next);
  17520. }
  17521. started = true;
  17522. }
  17523. };
  17524. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17525. {
  17526. public:
  17527. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17528. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17529. {
  17530. }
  17531. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17532. {
  17533. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17534. }
  17535. };
  17536. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17537. {
  17538. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17539. }
  17540. //=================================================================================
  17541. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17542. {
  17543. IHThorCatchArg &helper;
  17544. public:
  17545. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17546. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17547. {
  17548. }
  17549. virtual const void *nextRow()
  17550. {
  17551. ActivityTimer t(totalCycles, timeActivities);
  17552. try
  17553. {
  17554. const void *ret = inputStream->nextRow();
  17555. if (ret)
  17556. processed++;
  17557. return ret;
  17558. }
  17559. catch (IException *E)
  17560. {
  17561. E->Release();
  17562. helper.onExceptionCaught();
  17563. }
  17564. catch (...)
  17565. {
  17566. helper.onExceptionCaught();
  17567. }
  17568. throwUnexpected(); // onExceptionCaught should have thrown something
  17569. }
  17570. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17571. {
  17572. try
  17573. {
  17574. ActivityTimer t(totalCycles, timeActivities);
  17575. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17576. if (ret && wasCompleteMatch)
  17577. processed++;
  17578. return ret;
  17579. }
  17580. catch (IException *E)
  17581. {
  17582. E->Release();
  17583. helper.onExceptionCaught();
  17584. }
  17585. catch (...)
  17586. {
  17587. helper.onExceptionCaught();
  17588. }
  17589. throwUnexpected(); // onExceptionCaught should have thrown something
  17590. }
  17591. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17592. {
  17593. return input->gatherConjunctions(collector);
  17594. }
  17595. virtual void resetEOF()
  17596. {
  17597. inputStream->resetEOF(); // MORE - why not in base class?
  17598. }
  17599. IInputSteppingMeta * querySteppingMeta()
  17600. {
  17601. return input->querySteppingMeta();
  17602. }
  17603. };
  17604. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17605. {
  17606. ConstPointerArray buff;
  17607. bool started;
  17608. unsigned index;
  17609. IHThorCatchArg &helper;
  17610. bool createRow;
  17611. public:
  17612. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17613. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17614. {
  17615. started = false;
  17616. index = 0;
  17617. }
  17618. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17619. {
  17620. started = false;
  17621. index = 0;
  17622. try
  17623. {
  17624. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17625. }
  17626. catch (IException *E)
  17627. {
  17628. onException(E);
  17629. started = true;
  17630. }
  17631. catch (...)
  17632. {
  17633. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17634. started = true;
  17635. }
  17636. }
  17637. virtual void reset()
  17638. {
  17639. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17640. buff.kill();
  17641. index = 0;
  17642. started = false;
  17643. CRoxieServerActivity::reset();
  17644. }
  17645. virtual const void *nextRow()
  17646. {
  17647. ActivityTimer t(totalCycles, timeActivities);
  17648. if (!started)
  17649. pullInput();
  17650. if (buff.isItem(index))
  17651. {
  17652. const void * next = buff.item(index++);
  17653. if(next)
  17654. processed++;
  17655. return next;
  17656. }
  17657. return NULL;
  17658. }
  17659. protected:
  17660. void onException(IException *E)
  17661. {
  17662. inputStream->stop();
  17663. ReleaseRoxieRows(buff);
  17664. if (createRow)
  17665. {
  17666. ensureRowAllocator();
  17667. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17668. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17669. if (outSize)
  17670. buff.append(rowBuilder.finalizeRowClear(outSize));
  17671. }
  17672. E->Release();
  17673. }
  17674. void pullInput()
  17675. {
  17676. try
  17677. {
  17678. bool EOGseen = false;
  17679. loop
  17680. {
  17681. const void * next = inputStream->nextRow();
  17682. buff.append(next);
  17683. if (next == NULL)
  17684. {
  17685. if (EOGseen)
  17686. break;
  17687. EOGseen = true;
  17688. }
  17689. else
  17690. EOGseen = false;
  17691. }
  17692. }
  17693. catch (IException *E)
  17694. {
  17695. onException(E);
  17696. }
  17697. catch (...)
  17698. {
  17699. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17700. }
  17701. started = true;
  17702. }
  17703. };
  17704. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17705. {
  17706. public:
  17707. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17708. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17709. {
  17710. }
  17711. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17712. {
  17713. switch (kind)
  17714. {
  17715. case TAKcatch:
  17716. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  17717. case TAKskipcatch:
  17718. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  17719. case TAKcreaterowcatch:
  17720. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  17721. default:
  17722. throwUnexpected();
  17723. }
  17724. }
  17725. };
  17726. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17727. {
  17728. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17729. }
  17730. //=================================================================================
  17731. class CRoxieServerPullActivity : public CRoxieServerActivity
  17732. {
  17733. ConstPointerArray buff;
  17734. bool started;
  17735. unsigned index;
  17736. public:
  17737. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17738. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  17739. {
  17740. started = false;
  17741. index = 0;
  17742. }
  17743. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17744. {
  17745. started = false;
  17746. index = 0;
  17747. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17748. }
  17749. virtual void reset()
  17750. {
  17751. while (buff.isItem(index))
  17752. ReleaseRoxieRow(buff.item(index++));
  17753. buff.kill();
  17754. started = false;
  17755. index = 0;
  17756. CRoxieServerActivity::reset();
  17757. }
  17758. virtual const void *nextRow()
  17759. {
  17760. ActivityTimer t(totalCycles, timeActivities);
  17761. if (!started)
  17762. pullInput();
  17763. if (buff.isItem(index))
  17764. {
  17765. const void * next = buff.item(index++);
  17766. if (next)
  17767. processed++;
  17768. return next;
  17769. }
  17770. return NULL;
  17771. }
  17772. protected:
  17773. void pullInput()
  17774. {
  17775. bool EOGseen = false;
  17776. loop
  17777. {
  17778. const void * next = inputStream->nextRow();
  17779. buff.append(next);
  17780. if (next == NULL)
  17781. {
  17782. if (EOGseen)
  17783. break;
  17784. EOGseen = true;
  17785. }
  17786. else
  17787. EOGseen = false;
  17788. }
  17789. started = true;
  17790. }
  17791. };
  17792. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  17793. {
  17794. public:
  17795. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17796. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17797. {
  17798. }
  17799. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17800. {
  17801. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  17802. }
  17803. };
  17804. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17805. {
  17806. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17807. }
  17808. //=================================================================================
  17809. class CRoxieServerTraceActivity : public CRoxieServerActivity
  17810. {
  17811. public:
  17812. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17813. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  17814. keepLimit(0), skip(0), sample(0)
  17815. {
  17816. assertex(meta.hasXML());
  17817. traceEnabled = defaultTraceEnabled && !isBlind();
  17818. }
  17819. virtual void onCreate(IHThorArg *_colocalParent)
  17820. {
  17821. CRoxieServerActivity::onCreate(_colocalParent);
  17822. if (ctx)
  17823. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  17824. }
  17825. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17826. {
  17827. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17828. if (traceEnabled && helper.canMatchAny())
  17829. {
  17830. keepLimit = helper.getKeepLimit();
  17831. if (keepLimit==(unsigned) -1)
  17832. keepLimit = ctx->queryOptions().traceLimit;
  17833. skip = helper.getSkip();
  17834. sample = helper.getSample();
  17835. if (sample)
  17836. sample--;
  17837. name.setown(helper.getName());
  17838. if (!name)
  17839. name.set("Row");
  17840. }
  17841. else
  17842. keepLimit = 0;
  17843. }
  17844. virtual void stop()
  17845. {
  17846. name.clear();
  17847. CRoxieServerActivity::stop();
  17848. }
  17849. virtual bool isPassThrough()
  17850. {
  17851. return true;
  17852. }
  17853. virtual const void *nextRow()
  17854. {
  17855. ActivityTimer t(totalCycles, timeActivities);
  17856. const void *row = inputStream->nextRow();
  17857. if (row)
  17858. {
  17859. onTrace(row);
  17860. processed++;
  17861. }
  17862. return row;
  17863. }
  17864. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17865. {
  17866. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  17867. ActivityTimer t(totalCycles, timeActivities);
  17868. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17869. if (row)
  17870. {
  17871. onTrace(row);
  17872. processed++;
  17873. }
  17874. return row;
  17875. }
  17876. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17877. {
  17878. return input->gatherConjunctions(collector);
  17879. }
  17880. virtual void resetEOF()
  17881. {
  17882. inputStream->resetEOF();
  17883. }
  17884. IInputSteppingMeta * querySteppingMeta()
  17885. {
  17886. return input->querySteppingMeta();
  17887. }
  17888. protected:
  17889. void onTrace(const void *row)
  17890. {
  17891. if (keepLimit && helper.isValid(row))
  17892. {
  17893. if (skip)
  17894. skip--;
  17895. else if (sample)
  17896. sample--;
  17897. else
  17898. {
  17899. CommonXmlWriter xmlwrite(XWFnoindent);
  17900. meta.toXML((const byte *) row, xmlwrite);
  17901. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  17902. keepLimit--;
  17903. sample = helper.getSample();
  17904. if (sample)
  17905. sample--;
  17906. }
  17907. }
  17908. }
  17909. OwnedRoxieString name;
  17910. IHThorTraceArg &helper;
  17911. unsigned keepLimit;
  17912. unsigned skip;
  17913. unsigned sample;
  17914. bool traceEnabled;
  17915. };
  17916. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  17917. {
  17918. public:
  17919. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17920. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17921. {
  17922. }
  17923. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17924. {
  17925. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  17926. }
  17927. };
  17928. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17929. {
  17930. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17931. }
  17932. //=================================================================================
  17933. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  17934. {
  17935. IHThorCaseArg &helper;
  17936. unsigned cond;
  17937. bool unusedStopped;
  17938. IEngineRowStream *active;
  17939. public:
  17940. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17941. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  17942. {
  17943. unusedStopped = false;
  17944. cond = 0;
  17945. active = NULL;
  17946. }
  17947. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17948. {
  17949. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  17950. cond = helper.getBranch();
  17951. //CHOOSE defaults to the last argument if out of range.
  17952. if (cond >= numInputs)
  17953. cond = numInputs - 1;
  17954. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  17955. startJunction(junctionArray[cond]);
  17956. assertex(numInputs==numStreams);
  17957. for (unsigned idx = 0; idx < numStreams; idx++)
  17958. {
  17959. if (idx!=cond)
  17960. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17961. }
  17962. active = streamArray[cond];
  17963. unusedStopped = true;
  17964. }
  17965. virtual void stop()
  17966. {
  17967. for (unsigned idx = 0; idx < numStreams; idx++)
  17968. {
  17969. if (idx==cond || !unusedStopped)
  17970. streamArray[idx]->stop();
  17971. }
  17972. CRoxieServerMultiInputBaseActivity::stop();
  17973. }
  17974. virtual void reset()
  17975. {
  17976. unusedStopped = false;
  17977. active = NULL;
  17978. CRoxieServerMultiInputBaseActivity::reset();
  17979. }
  17980. virtual const void *nextRow()
  17981. {
  17982. ActivityTimer t(totalCycles, timeActivities);
  17983. if (active)
  17984. {
  17985. const void *ret = active->nextRow();
  17986. if (ret)
  17987. processed++;
  17988. return ret;
  17989. }
  17990. return NULL;
  17991. }
  17992. };
  17993. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17994. {
  17995. bool graphInvariant;
  17996. public:
  17997. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  17998. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17999. {
  18000. graphInvariant = _graphInvariant;
  18001. }
  18002. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18003. {
  18004. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18005. }
  18006. virtual bool isGraphInvariant() const
  18007. {
  18008. return graphInvariant;
  18009. }
  18010. };
  18011. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18012. {
  18013. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18014. }
  18015. //=================================================================================
  18016. class CRoxieServerIfActivity : public CRoxieServerActivity
  18017. {
  18018. IHThorIfArg &helper;
  18019. IFinalRoxieInput *inputTrue;
  18020. IFinalRoxieInput *inputFalse;
  18021. IEngineRowStream *streamTrue;
  18022. IEngineRowStream *streamFalse;
  18023. unsigned sourceIdxFalse = 0;
  18024. unsigned sourceIdxTrue = 0;
  18025. Owned<IStrandJunction> junctionTrue;
  18026. Owned<IStrandJunction> junctionFalse;
  18027. bool cond;
  18028. bool unusedStopped;
  18029. public:
  18030. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18031. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18032. {
  18033. inputFalse = NULL;
  18034. inputTrue = NULL;
  18035. streamTrue = NULL;
  18036. streamFalse = NULL;
  18037. unusedStopped = false;
  18038. cond = false;
  18039. }
  18040. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18041. {
  18042. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18043. cond = helper.getCondition();
  18044. if (cond)
  18045. {
  18046. inputTrue->start(parentExtractSize, parentExtract, paused);
  18047. startJunction(junctionTrue);
  18048. if (streamFalse)
  18049. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18050. }
  18051. else
  18052. {
  18053. if (inputFalse)
  18054. {
  18055. inputFalse->start(parentExtractSize, parentExtract, paused);
  18056. startJunction(junctionFalse);
  18057. }
  18058. streamTrue->stop();
  18059. }
  18060. unusedStopped = true;
  18061. }
  18062. virtual void stop()
  18063. {
  18064. if (!unusedStopped || cond)
  18065. streamTrue->stop();
  18066. if (streamFalse && (!unusedStopped || !cond))
  18067. streamFalse->stop();
  18068. CRoxieServerActivity::stop();
  18069. }
  18070. virtual unsigned __int64 queryLocalCycles() const
  18071. {
  18072. __int64 localCycles = totalCycles.totalCycles;
  18073. localCycles -= inputTrue->queryTotalCycles();
  18074. if (inputFalse)
  18075. localCycles -= inputFalse->queryTotalCycles();
  18076. if (localCycles < 0)
  18077. localCycles = 0;
  18078. return localCycles;
  18079. }
  18080. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18081. {
  18082. switch (idx)
  18083. {
  18084. case 0:
  18085. return inputTrue;
  18086. case 1:
  18087. return inputFalse;
  18088. default:
  18089. return NULL;
  18090. }
  18091. }
  18092. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18093. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18094. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18095. {
  18096. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18097. if (in)
  18098. return in->queryIndexReadActivity();
  18099. return NULL;
  18100. }
  18101. virtual void reset()
  18102. {
  18103. CRoxieServerActivity::reset();
  18104. inputTrue->reset();
  18105. if (inputFalse)
  18106. inputFalse->reset();
  18107. resetJunction(junctionTrue);
  18108. resetJunction(junctionFalse);
  18109. unusedStopped = false;
  18110. }
  18111. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18112. {
  18113. if (idx==1)
  18114. {
  18115. inputFalse = _in;
  18116. sourceIdxFalse = _sourceIdx;
  18117. }
  18118. else
  18119. {
  18120. assertex(!idx);
  18121. inputTrue = _in;
  18122. sourceIdxTrue = _sourceIdx;
  18123. }
  18124. }
  18125. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18126. {
  18127. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18128. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18129. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18130. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18131. }
  18132. virtual const void *nextRow()
  18133. {
  18134. ActivityTimer t(totalCycles, timeActivities);
  18135. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18136. if (in)
  18137. {
  18138. const void * ret;
  18139. if ((ret = in->nextRow()) != NULL)
  18140. processed++;
  18141. return ret;
  18142. }
  18143. return NULL;
  18144. }
  18145. };
  18146. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18147. {
  18148. unsigned input2;
  18149. unsigned input2idx;
  18150. bool graphInvariant;
  18151. public:
  18152. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18153. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18154. {
  18155. graphInvariant = _graphInvariant;
  18156. input2 = (unsigned)-1;
  18157. input2idx = (unsigned)-1;
  18158. }
  18159. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18160. {
  18161. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18162. }
  18163. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18164. {
  18165. if (idx==1)
  18166. {
  18167. input2 = source;
  18168. input2idx = sourceidx;
  18169. }
  18170. else
  18171. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18172. }
  18173. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18174. {
  18175. switch (idx)
  18176. {
  18177. case 1:
  18178. sourceidx = input2idx;
  18179. return input2;
  18180. case 0:
  18181. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18182. default:
  18183. return (unsigned) -1;
  18184. }
  18185. }
  18186. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18187. virtual bool isGraphInvariant() const
  18188. {
  18189. return graphInvariant;
  18190. }
  18191. };
  18192. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18193. {
  18194. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18195. }
  18196. //=================================================================================
  18197. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18198. {
  18199. CriticalSection ecrit;
  18200. Owned<IException> exception;
  18201. bool executed;
  18202. public:
  18203. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18204. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18205. {
  18206. executed = false;
  18207. }
  18208. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18209. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18210. {
  18211. CriticalBlock b(ecrit);
  18212. if (exception)
  18213. throw(exception.getLink());
  18214. if (!executed)
  18215. {
  18216. try
  18217. {
  18218. executed = true;
  18219. start(parentExtractSize, parentExtract, false);
  18220. doExecuteAction(parentExtractSize, parentExtract);
  18221. stop();
  18222. }
  18223. catch (IException * E)
  18224. {
  18225. ctx->notifyAbort(E);
  18226. abort();
  18227. exception.set(E);
  18228. throw;
  18229. }
  18230. }
  18231. }
  18232. virtual void reset()
  18233. {
  18234. executed = false;
  18235. exception.clear();
  18236. CRoxieServerActivity::reset();
  18237. }
  18238. virtual const void *nextRow()
  18239. {
  18240. throwUnexpected(); // I am nobody's input
  18241. }
  18242. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18243. {
  18244. return NULL;
  18245. }
  18246. };
  18247. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18248. {
  18249. IHThorIfArg &helper;
  18250. public:
  18251. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18252. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18253. {
  18254. }
  18255. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18256. {
  18257. bool cond;
  18258. {
  18259. ActivityTimer t(totalCycles, timeActivities);
  18260. cond = helper.getCondition();
  18261. }
  18262. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18263. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18264. }
  18265. };
  18266. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18267. {
  18268. bool isRoot;
  18269. public:
  18270. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18271. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18272. {
  18273. }
  18274. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18275. {
  18276. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18277. }
  18278. virtual bool isSink() const
  18279. {
  18280. return isRoot;
  18281. }
  18282. };
  18283. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18284. {
  18285. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18286. }
  18287. //=================================================================================
  18288. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18289. {
  18290. public:
  18291. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18292. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18293. {
  18294. }
  18295. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18296. {
  18297. #ifdef PARALLEL_EXECUTE
  18298. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18299. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18300. #else
  18301. ForEachItemIn(idx, dependencies)
  18302. {
  18303. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18304. }
  18305. #endif
  18306. }
  18307. };
  18308. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18309. {
  18310. bool isRoot;
  18311. public:
  18312. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18313. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18314. {
  18315. assertex(!isRoot); // non-internal should be expanded out..
  18316. }
  18317. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18318. {
  18319. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18320. }
  18321. virtual bool isSink() const
  18322. {
  18323. return isRoot;
  18324. }
  18325. };
  18326. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18327. {
  18328. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18329. }
  18330. //=================================================================================
  18331. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18332. {
  18333. IHThorSequentialArg &helper;
  18334. public:
  18335. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18336. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18337. {
  18338. }
  18339. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18340. {
  18341. unsigned numBranches = helper.numBranches();
  18342. for (unsigned branch=1; branch <= numBranches; branch++)
  18343. executeDependencies(parentExtractSize, parentExtract, branch);
  18344. }
  18345. };
  18346. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18347. {
  18348. bool isRoot;
  18349. public:
  18350. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18351. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18352. {
  18353. }
  18354. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18355. {
  18356. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18357. }
  18358. virtual bool isSink() const
  18359. {
  18360. return isRoot;
  18361. }
  18362. };
  18363. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18364. {
  18365. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18366. }
  18367. //=================================================================================
  18368. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18369. {
  18370. public:
  18371. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18372. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18373. {
  18374. savedExtractSize = 0;
  18375. savedExtract = NULL;
  18376. eofseen = false;
  18377. eogseen = false;
  18378. }
  18379. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18380. {
  18381. savedExtractSize = parentExtractSize;
  18382. savedExtract = parentExtract;
  18383. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18384. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18385. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18386. eofseen = false;
  18387. eogseen = false;
  18388. }
  18389. virtual void stop()
  18390. {
  18391. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18392. {
  18393. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18394. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18395. }
  18396. else if (state != STATEstopped)
  18397. {
  18398. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18399. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18400. }
  18401. CRoxieServerActivity::stop();
  18402. }
  18403. virtual const void *nextRow()
  18404. {
  18405. try
  18406. {
  18407. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18408. const void *ret = inputStream->nextRow();
  18409. if (!ret)
  18410. {
  18411. if (eogseen)
  18412. eofseen = true;
  18413. else
  18414. eogseen = true;
  18415. }
  18416. else
  18417. eogseen = false;
  18418. return ret;
  18419. }
  18420. catch (...)
  18421. {
  18422. aborted = true;
  18423. throw;
  18424. }
  18425. }
  18426. protected:
  18427. const byte *savedExtract;
  18428. unsigned savedExtractSize;
  18429. bool eofseen;
  18430. bool eogseen;
  18431. };
  18432. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18433. {
  18434. public:
  18435. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18436. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18437. {
  18438. }
  18439. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18440. {
  18441. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18442. }
  18443. };
  18444. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18445. {
  18446. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18447. }
  18448. //=================================================================================
  18449. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18450. {
  18451. public:
  18452. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18453. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18454. {
  18455. savedExtractSize = 0;
  18456. savedExtract = NULL;
  18457. }
  18458. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18459. {
  18460. savedExtractSize = parentExtractSize;
  18461. savedExtract = parentExtract;
  18462. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18463. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18464. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18465. }
  18466. virtual void stop()
  18467. {
  18468. if (state != STATEstopped)
  18469. {
  18470. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18471. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18472. }
  18473. CRoxieServerActionBaseActivity::stop();
  18474. }
  18475. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18476. {
  18477. executeDependencies(parentExtractSize, parentExtract, 1);
  18478. }
  18479. protected:
  18480. unsigned savedExtractSize;
  18481. const byte *savedExtract;
  18482. };
  18483. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18484. {
  18485. public:
  18486. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18488. {
  18489. }
  18490. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18491. {
  18492. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18493. }
  18494. virtual bool isSink() const
  18495. {
  18496. return isRoot;
  18497. }
  18498. private:
  18499. bool isRoot;
  18500. };
  18501. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18502. {
  18503. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18504. }
  18505. //=================================================================================
  18506. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18507. {
  18508. INlpParseAlgorithm * algorithm;
  18509. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18510. {
  18511. protected:
  18512. IHThorParseArg &helper;
  18513. INlpParser * parser;
  18514. INlpResultIterator * rowIter;
  18515. const void * in;
  18516. char * curSearchText;
  18517. size32_t curSearchTextLen;
  18518. bool processRecord(const void * inRec)
  18519. {
  18520. if (helper.searchTextNeedsFree())
  18521. rtlFree(curSearchText);
  18522. curSearchTextLen = 0;
  18523. curSearchText = NULL;
  18524. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18525. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18526. }
  18527. public:
  18528. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18529. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18530. {
  18531. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18532. rowIter = parser->queryResultIter();
  18533. in = NULL;
  18534. curSearchText = NULL;
  18535. curSearchTextLen = 0;
  18536. }
  18537. ~ParseProcessor()
  18538. {
  18539. ::Release(parser);
  18540. }
  18541. virtual void start()
  18542. {
  18543. StrandProcessor::start();
  18544. numProcessedLastGroup = 0;
  18545. curSearchTextLen = 0;
  18546. curSearchText = NULL;
  18547. in = NULL;
  18548. parser->reset();
  18549. }
  18550. virtual void reset()
  18551. {
  18552. if (helper.searchTextNeedsFree())
  18553. rtlFree(curSearchText);
  18554. curSearchText = NULL;
  18555. ReleaseClearRoxieRow(in);
  18556. StrandProcessor::reset();
  18557. }
  18558. virtual const void * nextRow()
  18559. {
  18560. ActivityTimer t(totalCycles, timeActivities);
  18561. loop
  18562. {
  18563. if (rowIter->isValid())
  18564. {
  18565. OwnedConstRoxieRow out = rowIter->getRow();
  18566. rowIter->next();
  18567. processed++;
  18568. return out.getClear();
  18569. }
  18570. ReleaseClearRoxieRow(in);
  18571. in = inputStream->nextRow();
  18572. if (!in)
  18573. {
  18574. if (processed == numProcessedLastGroup)
  18575. in = inputStream->nextRow();
  18576. if (!in)
  18577. {
  18578. processed = numProcessedLastGroup;
  18579. return NULL;
  18580. }
  18581. in = inputStream->nextRow();
  18582. if (!in)
  18583. return NULL;
  18584. }
  18585. processRecord(in);
  18586. rowIter->first();
  18587. }
  18588. }
  18589. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18590. {
  18591. try
  18592. {
  18593. return helper.transform(self, curRecord, results, walker);
  18594. }
  18595. catch (IException *E)
  18596. {
  18597. throw parent.makeWrappedException(E);
  18598. }
  18599. }
  18600. };
  18601. public:
  18602. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  18603. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  18604. {
  18605. }
  18606. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18607. {
  18608. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  18609. onStartStrands();
  18610. }
  18611. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  18612. {
  18613. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  18614. }
  18615. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  18616. };
  18617. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  18618. {
  18619. Owned<INlpParseAlgorithm> algorithm;
  18620. Owned<IHThorParseArg> helper;
  18621. StrandOptions strandOptions;
  18622. public:
  18623. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18624. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  18625. {
  18626. helper.setown((IHThorParseArg *) helperFactory());
  18627. algorithm.setown(createThorParser(rc, *helper));
  18628. optStableInput = false;
  18629. }
  18630. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18631. {
  18632. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  18633. }
  18634. };
  18635. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  18636. {
  18637. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  18638. }
  18639. //=====================================================================================================
  18640. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  18641. {
  18642. IHThorWorkUnitWriteArg &helper;
  18643. bool isReread;
  18644. bool grouped;
  18645. IRoxieServerContext *serverContext;
  18646. public:
  18647. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  18648. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  18649. {
  18650. grouped = (helper.getFlags() & POFgrouped) != 0;
  18651. serverContext = NULL;
  18652. }
  18653. virtual void onCreate(IHThorArg *_colocalParent)
  18654. {
  18655. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18656. serverContext = ctx->queryServerContext();
  18657. if (!serverContext)
  18658. {
  18659. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  18660. }
  18661. }
  18662. virtual bool needsAllocator() const { return true; }
  18663. virtual void onExecute()
  18664. {
  18665. int sequence = helper.getSequence();
  18666. const char *storedName = helper.queryName();
  18667. if (!storedName)
  18668. storedName = "Dataset";
  18669. MemoryBuffer result;
  18670. bool saveInContext = (int) sequence < 0 || isReread;
  18671. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  18672. meta.set(input->queryOutputMeta());
  18673. Owned<IOutputRowSerializer> rowSerializer;
  18674. Owned<IXmlWriter> xmlwriter;
  18675. bool appendRaw = false;
  18676. IHpccProtocolResultsWriter *results = NULL;
  18677. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  18678. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  18679. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  18680. if ((int) sequence >= 0)
  18681. {
  18682. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  18683. if (results)
  18684. {
  18685. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  18686. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  18687. }
  18688. }
  18689. size32_t outputLimitBytes = 0;
  18690. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  18691. if (workunit)
  18692. {
  18693. size32_t outputLimit;
  18694. if (helper.getFlags() & POFmaxsize)
  18695. outputLimit = helper.getMaxSize();
  18696. else
  18697. {
  18698. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  18699. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  18700. }
  18701. if (outputLimit>defaultDaliResultOutputMax)
  18702. 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);
  18703. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  18704. outputLimitBytes = outputLimit * 0x100000;
  18705. }
  18706. if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
  18707. {
  18708. ensureRowAllocator();
  18709. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  18710. }
  18711. __int64 initialProcessed = processed;
  18712. RtlLinkedDatasetBuilder builder(rowAllocator);
  18713. loop
  18714. {
  18715. const void *row = inputStream->nextRow();
  18716. if (saveInContext)
  18717. {
  18718. if (row || grouped)
  18719. builder.append(row);
  18720. }
  18721. if (grouped && (processed != initialProcessed))
  18722. {
  18723. if (workunit)
  18724. result.append(row == NULL);
  18725. if (results)
  18726. {
  18727. if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
  18728. {
  18729. char val = (char)(row == NULL);
  18730. nativeResults->appendRaw(sequence, 1, &val);
  18731. }
  18732. else if (xmlwriter)
  18733. {
  18734. xmlwriter->outputBeginNested("Row", false);
  18735. xmlwriter->outputCString("1", "@__GroupBreak__");
  18736. xmlwriter->outputEndNested("Row");
  18737. }
  18738. }
  18739. }
  18740. if (!row)
  18741. {
  18742. row = inputStream->nextRow();
  18743. if (!row)
  18744. break;
  18745. if (saveInContext)
  18746. builder.append(row);
  18747. }
  18748. processed++;
  18749. if (workunit)
  18750. {
  18751. CThorDemoRowSerializer serializerTarget(result);
  18752. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18753. }
  18754. if ((int) sequence >= 0)
  18755. {
  18756. if (appendRaw && nativeResults)
  18757. {
  18758. // MORE - should be able to serialize straight to the response...
  18759. MemoryBuffer rowbuff;
  18760. CThorDemoRowSerializer serializerTarget(rowbuff);
  18761. rowSerializer->serialize(serializerTarget, (const byte *) row);
  18762. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  18763. }
  18764. else if (xmlwriter)
  18765. {
  18766. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  18767. helper.serializeXml((byte *) row, *xmlwriter);
  18768. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  18769. results->finalizeXmlRow(sequence);
  18770. }
  18771. else if (nativeResults)
  18772. {
  18773. SimpleOutputWriter x;
  18774. helper.serializeXml((byte *) row, x);
  18775. x.newline();
  18776. nativeResults->appendSimpleRow(sequence, x.str());
  18777. }
  18778. }
  18779. ReleaseRoxieRow(row);
  18780. if (outputLimitBytes && result.length() > outputLimitBytes)
  18781. {
  18782. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  18783. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  18784. const char *name = helper.queryName();
  18785. if (name)
  18786. errMsg.append("name=").append(name);
  18787. else
  18788. errMsg.append("sequence=").append(helper.getSequence());
  18789. errMsg.append(")");
  18790. throw MakeStringExceptionDirect(0, errMsg.str());
  18791. }
  18792. }
  18793. if (xmlwriter)
  18794. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  18795. if (saveInContext)
  18796. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18797. if (workunit)
  18798. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  18799. }
  18800. };
  18801. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  18802. {
  18803. bool isReread;
  18804. public:
  18805. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18806. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18807. {
  18808. isReread = usageCount > 0;
  18809. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  18810. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18811. }
  18812. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18813. {
  18814. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  18815. }
  18816. };
  18817. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18818. {
  18819. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18820. }
  18821. //=====================================================================================================
  18822. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  18823. {
  18824. IHThorDictionaryWorkUnitWriteArg &helper;
  18825. IRoxieServerContext *serverContext;
  18826. public:
  18827. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  18828. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  18829. {
  18830. serverContext = NULL;
  18831. }
  18832. virtual void onCreate(IHThorArg *_colocalParent)
  18833. {
  18834. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  18835. serverContext = ctx->queryServerContext();
  18836. if (!serverContext)
  18837. {
  18838. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  18839. }
  18840. }
  18841. virtual bool needsAllocator() const { return true; }
  18842. virtual void onExecute()
  18843. {
  18844. int sequence = helper.getSequence();
  18845. const char *storedName = helper.queryName();
  18846. assertex(storedName && *storedName);
  18847. assertex(sequence < 0);
  18848. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18849. loop
  18850. {
  18851. const void *row = inputStream->ungroupedNextRow();
  18852. if (!row)
  18853. break;
  18854. builder.appendOwn(row);
  18855. processed++;
  18856. }
  18857. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18858. }
  18859. };
  18860. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18861. {
  18862. public:
  18863. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18864. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18865. {
  18866. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18867. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18868. }
  18869. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18870. {
  18871. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  18872. }
  18873. };
  18874. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18875. {
  18876. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18877. }
  18878. //=================================================================================
  18879. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18880. {
  18881. IHThorRemoteResultArg &helper;
  18882. public:
  18883. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18884. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18885. {
  18886. }
  18887. virtual void onExecute()
  18888. {
  18889. OwnedConstRoxieRow row = inputStream->nextRow();
  18890. helper.sendResult(row); // should be only one row or something has gone wrong!
  18891. }
  18892. };
  18893. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18894. {
  18895. public:
  18896. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18897. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  18898. {
  18899. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18900. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18901. }
  18902. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18903. {
  18904. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  18905. }
  18906. };
  18907. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  18908. {
  18909. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  18910. }
  18911. //=================================================================================
  18912. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18913. {
  18914. IHThorXmlParseArg &helper;
  18915. Owned<IXMLParse> xmlParser;
  18916. const void * in;
  18917. char * srchStr;
  18918. unsigned numProcessedLastGroup;
  18919. bool srchStrNeedsFree;
  18920. Owned<IColumnProvider> lastMatch;
  18921. public:
  18922. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  18923. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18924. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  18925. helper((IHThorXmlParseArg &)basehelper)
  18926. {
  18927. srchStrNeedsFree = helper.searchTextNeedsFree();
  18928. numProcessedLastGroup = 0;
  18929. srchStr = NULL;
  18930. in = NULL;
  18931. }
  18932. ~CRoxieServerXmlParseActivity()
  18933. {
  18934. }
  18935. virtual bool needsAllocator() const { return true; }
  18936. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18937. {
  18938. numProcessedLastGroup = 0;
  18939. srchStr = NULL;
  18940. in = NULL;
  18941. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18942. }
  18943. virtual void reset()
  18944. {
  18945. if (helper.searchTextNeedsFree())
  18946. rtlFree(srchStr);
  18947. srchStr = NULL;
  18948. ReleaseClearRoxieRow(in);
  18949. xmlParser.clear();
  18950. CRoxieServerActivity::reset();
  18951. }
  18952. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18953. {
  18954. lastMatch.set(&entry);
  18955. }
  18956. virtual const void *nextRow()
  18957. {
  18958. ActivityTimer t(totalCycles, timeActivities);
  18959. loop
  18960. {
  18961. if(xmlParser)
  18962. {
  18963. loop
  18964. {
  18965. if(!xmlParser->next())
  18966. {
  18967. if (srchStrNeedsFree)
  18968. {
  18969. rtlFree(srchStr);
  18970. srchStr = NULL;
  18971. }
  18972. xmlParser.clear();
  18973. break;
  18974. }
  18975. if(lastMatch)
  18976. {
  18977. try
  18978. {
  18979. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18980. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18981. lastMatch.clear();
  18982. if (outSize)
  18983. {
  18984. processed++;
  18985. return rowBuilder.finalizeRowClear(outSize);
  18986. }
  18987. }
  18988. catch (IException *E)
  18989. {
  18990. throw makeWrappedException(E);
  18991. }
  18992. }
  18993. }
  18994. }
  18995. ReleaseClearRoxieRow(in);
  18996. in = inputStream->nextRow();
  18997. if(!in)
  18998. {
  18999. if(numProcessedLastGroup == processed)
  19000. in = inputStream->nextRow();
  19001. if(!in)
  19002. {
  19003. numProcessedLastGroup = processed;
  19004. return NULL;
  19005. }
  19006. }
  19007. size32_t srchLen;
  19008. helper.getSearchText(srchLen, srchStr, in);
  19009. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19010. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19011. }
  19012. }
  19013. };
  19014. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19015. {
  19016. public:
  19017. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19018. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19019. {
  19020. }
  19021. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19022. {
  19023. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19024. }
  19025. };
  19026. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19027. {
  19028. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19029. }
  19030. //=====================================================================================================
  19031. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19032. {
  19033. protected:
  19034. IHThorDiskReadBaseArg &helper;
  19035. IHThorCompoundExtra * compoundHelper;
  19036. RemoteActivityId remoteId; // Note we copy it rather than reference
  19037. Owned<CSkippableRemoteResultAdaptor> remote;
  19038. unsigned numParts;
  19039. unsigned __int64 rowLimit;
  19040. unsigned __int64 stopAfter;
  19041. Linked<IInMemoryIndexManager> manager;
  19042. Owned<IInMemoryIndexCursor> cursor;
  19043. Owned<IDirectReader> reader;
  19044. CThorContiguousRowBuffer deserializeSource;
  19045. Owned<ISourceRowPrefetcher> prefetcher;
  19046. bool eof;
  19047. bool isKeyed;
  19048. bool variableFileName;
  19049. bool isOpt;
  19050. bool sorted;
  19051. bool maySkip;
  19052. bool isLocal;
  19053. bool forceRemote;
  19054. CachedOutputMetaData diskSize;
  19055. Owned<const IResolvedFile> varFileInfo;
  19056. Owned<IFileIOArray> varFiles;
  19057. inline bool useRemote()
  19058. {
  19059. return remote != NULL && (forceRemote || numParts > 1);
  19060. }
  19061. public:
  19062. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19063. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19064. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19065. helper((IHThorDiskReadBaseArg &)basehelper),
  19066. numParts(_numParts),
  19067. remoteId(_remoteId),
  19068. manager(_manager),
  19069. isLocal(_isLocal),
  19070. sorted(_sorted),
  19071. maySkip(_maySkip),
  19072. deserializeSource(NULL)
  19073. {
  19074. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19075. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19076. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19077. compoundHelper = NULL;
  19078. eof = false;
  19079. rowLimit = (unsigned __int64) -1;
  19080. isKeyed = false;
  19081. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19082. diskSize.set(helper.queryDiskRecordSize());
  19083. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19084. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19085. }
  19086. virtual const IResolvedFile *queryVarFileInfo() const
  19087. {
  19088. return varFileInfo;
  19089. }
  19090. virtual void onCreate(IHThorArg *_colocalParent)
  19091. {
  19092. CRoxieServerActivity::onCreate(_colocalParent);
  19093. if (remote)
  19094. remote->onCreate(_colocalParent);
  19095. }
  19096. virtual bool needsAllocator() const { return true; }
  19097. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19098. {
  19099. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19100. if (compoundHelper)
  19101. {
  19102. rowLimit = compoundHelper->getRowLimit();
  19103. stopAfter = compoundHelper->getChooseNLimit();
  19104. }
  19105. if (!helper.canMatchAny())
  19106. eof = true;
  19107. else
  19108. {
  19109. if (variableFileName)
  19110. {
  19111. OwnedRoxieString fileName(helper.getFileName());
  19112. varFileInfo.setown(resolveLFN(fileName, isOpt));
  19113. numParts = 0;
  19114. if (varFileInfo)
  19115. numParts = varFileInfo->getNumParts();
  19116. }
  19117. if (!numParts)
  19118. {
  19119. eof = true;
  19120. }
  19121. else if (useRemote())
  19122. {
  19123. remote->onStart(parentExtractSize, parentExtract);
  19124. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19125. unsigned fileNo = 0;
  19126. // Translation into a message per channel done elsewhere....
  19127. remote->getMem(0, fileNo, 0);
  19128. remote->flush();
  19129. remote->senddone();
  19130. }
  19131. else
  19132. {
  19133. if (variableFileName)
  19134. {
  19135. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19136. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  19137. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  19138. }
  19139. assertex(manager != NULL);
  19140. helper.createSegmentMonitors(this);
  19141. if (cursor)
  19142. {
  19143. isKeyed = cursor->selectKey();
  19144. cursor->reset();
  19145. }
  19146. if (!isKeyed)
  19147. {
  19148. reader.setown(manager->createReader(0, 0, 1));
  19149. deserializeSource.setStream(reader);
  19150. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  19151. }
  19152. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  19153. }
  19154. }
  19155. }
  19156. virtual void append(IKeySegmentMonitor *segment)
  19157. {
  19158. if (!segment->isWild())
  19159. {
  19160. if (!cursor)
  19161. cursor.setown(manager->createCursor());
  19162. cursor->append(segment);
  19163. }
  19164. }
  19165. virtual unsigned ordinality() const
  19166. {
  19167. return cursor ? cursor->ordinality() : 0;
  19168. }
  19169. virtual IKeySegmentMonitor *item(unsigned idx) const
  19170. {
  19171. return cursor ? cursor->item(idx) : 0;
  19172. }
  19173. virtual void setMergeBarrier(unsigned barrierOffset)
  19174. {
  19175. // no merging so no issue...
  19176. }
  19177. virtual void stop()
  19178. {
  19179. if (useRemote())
  19180. remote->onStop();
  19181. CRoxieServerActivity::stop();
  19182. }
  19183. virtual void reset()
  19184. {
  19185. if (useRemote())
  19186. {
  19187. processed = remote->processed;
  19188. remote->processed = 0;
  19189. remote->onReset();
  19190. }
  19191. varFileInfo.clear();
  19192. eof = false;
  19193. if (cursor)
  19194. cursor->reset();
  19195. deserializeSource.clearStream();
  19196. CRoxieServerActivity::reset();
  19197. }
  19198. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19199. {
  19200. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19201. }
  19202. virtual void onLimitExceeded(bool isKeyed)
  19203. {
  19204. if (traceLevel > 4)
  19205. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19206. assertex(compoundHelper);
  19207. if (isKeyed) // MORE does this exist for diskread? should it?
  19208. {
  19209. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19210. {
  19211. if (ctx->queryDebugContext())
  19212. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19213. throw makeLimitSkipException(true);
  19214. }
  19215. else
  19216. {
  19217. UNIMPLEMENTED;
  19218. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19219. }
  19220. }
  19221. else
  19222. {
  19223. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19224. {
  19225. if (ctx->queryDebugContext())
  19226. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19227. throw makeLimitSkipException(false);
  19228. }
  19229. else
  19230. compoundHelper->onLimitExceeded();
  19231. }
  19232. }
  19233. virtual const void * createLimitFailRow(bool isKeyed)
  19234. {
  19235. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19236. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  19237. assertex(limitTransformExtra);
  19238. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19239. if (outSize)
  19240. return rowBuilder.finalizeRowClear(outSize);
  19241. return NULL;
  19242. }
  19243. };
  19244. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19245. {
  19246. IHThorCompoundReadExtra * readHelper;
  19247. ConstPointerArray readrows;
  19248. bool readAheadDone;
  19249. unsigned readIndex;
  19250. public:
  19251. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19252. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19253. {
  19254. compoundHelper = (IHThorDiskReadArg *)&helper;
  19255. readHelper = (IHThorDiskReadArg *)&helper;
  19256. readAheadDone = false;
  19257. readIndex = 0;
  19258. }
  19259. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19260. {
  19261. rowLimit = compoundHelper->getRowLimit();
  19262. stopAfter = compoundHelper->getChooseNLimit();
  19263. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19264. readAheadDone = false;
  19265. readIndex = 0;
  19266. }
  19267. virtual void reset()
  19268. {
  19269. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19270. readrows.kill();
  19271. readAheadDone = false;
  19272. readIndex = 0;
  19273. CRoxieServerDiskReadBaseActivity::reset();
  19274. }
  19275. virtual const void *nextRow()
  19276. {
  19277. if (eof)
  19278. return NULL;
  19279. else if (useRemote())
  19280. return remote->nextRow();
  19281. else if (maySkip)
  19282. {
  19283. if (!readAheadDone)
  19284. {
  19285. unsigned preprocessed = 0;
  19286. while (!eof)
  19287. {
  19288. const void *row = _nextRow();
  19289. if (row)
  19290. preprocessed++;
  19291. if (preprocessed > rowLimit)
  19292. {
  19293. ReleaseRoxieRow(row);
  19294. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19295. readrows.kill();
  19296. readIndex = 0;
  19297. eof = true;
  19298. if (ctx->queryDebugContext())
  19299. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19300. if (helper.getFlags() & TDRlimitskips)
  19301. return NULL;
  19302. else if (helper.getFlags() & TDRlimitcreates)
  19303. return createLimitFailRow(false);
  19304. else
  19305. throwUnexpected();
  19306. }
  19307. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19308. {
  19309. eof = true;
  19310. ReleaseRoxieRow(row);
  19311. break;
  19312. }
  19313. readrows.append(row);
  19314. }
  19315. readAheadDone = true;
  19316. }
  19317. if (readrows.isItem(readIndex))
  19318. {
  19319. const void *ret = readrows.item(readIndex++);
  19320. if (ret)
  19321. processed++;
  19322. return ret;
  19323. }
  19324. else
  19325. {
  19326. eof = true;
  19327. return NULL;
  19328. }
  19329. }
  19330. else
  19331. {
  19332. const void *ret = _nextRow();
  19333. if (ret)
  19334. {
  19335. processed++;
  19336. if (processed > rowLimit)
  19337. {
  19338. if (traceLevel > 4)
  19339. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19340. ReleaseRoxieRow(ret);
  19341. compoundHelper->onLimitExceeded();
  19342. throwUnexpected(); // onLimitExceeded is not supposed to return
  19343. }
  19344. if (processed > stopAfter) // MORE - bit of a strange place to check
  19345. {
  19346. eof = true;
  19347. ReleaseRoxieRow(ret);
  19348. return NULL;
  19349. }
  19350. }
  19351. return ret;
  19352. }
  19353. }
  19354. const void *_nextRow()
  19355. {
  19356. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19357. unsigned transformedSize = 0;
  19358. if (isKeyed)
  19359. {
  19360. loop
  19361. {
  19362. const void *nextCandidate = cursor->nextMatch();
  19363. if (!nextCandidate)
  19364. {
  19365. eof = true;
  19366. return NULL;
  19367. }
  19368. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  19369. if (transformedSize)
  19370. break;
  19371. }
  19372. }
  19373. else // use reader...
  19374. {
  19375. assertex(reader != NULL);
  19376. loop
  19377. {
  19378. if (deserializeSource.eos())
  19379. {
  19380. eof = true;
  19381. return NULL;
  19382. }
  19383. prefetcher->readAhead(deserializeSource);
  19384. const byte *nextRec = deserializeSource.queryRow();
  19385. if (cursor && cursor->isFiltered(nextRec))
  19386. transformedSize = 0;
  19387. else
  19388. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19389. deserializeSource.finishedRow();
  19390. if (transformedSize)
  19391. break;
  19392. }
  19393. }
  19394. return rowBuilder.finalizeRowClear(transformedSize);
  19395. }
  19396. };
  19397. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19398. {
  19399. IHThorXmlReadArg * readHelper;
  19400. Owned<IXmlToRowTransformer> rowTransformer;
  19401. Owned<IXMLParse> xmlParser;
  19402. Owned<IColumnProvider> lastMatch;
  19403. unsigned __int64 fileoffset;
  19404. public:
  19405. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19406. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  19407. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  19408. {
  19409. compoundHelper = NULL;
  19410. readHelper = (IHThorXmlReadArg *)&helper;
  19411. fileoffset = 0;
  19412. }
  19413. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19414. {
  19415. rowLimit = readHelper->getRowLimit();
  19416. stopAfter = readHelper->getChooseNLimit();
  19417. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19418. if (!useRemote())
  19419. {
  19420. rowTransformer.set(readHelper->queryTransformer());
  19421. assertex(reader != NULL);
  19422. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19423. if (factory->getKind()==TAKjsonread)
  19424. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19425. else
  19426. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19427. }
  19428. }
  19429. virtual void reset()
  19430. {
  19431. CRoxieServerDiskReadBaseActivity::reset();
  19432. rowTransformer.clear();
  19433. xmlParser.clear();
  19434. }
  19435. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19436. {
  19437. fileoffset = startOffset;
  19438. lastMatch.set(&entry);
  19439. }
  19440. //interface IThorDiskCallback
  19441. virtual unsigned __int64 getFilePosition(const void * row)
  19442. {
  19443. return fileoffset;
  19444. }
  19445. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19446. {
  19447. return reader->makeFilePositionLocal(fileoffset);
  19448. }
  19449. virtual const char * queryLogicalFilename(const void * row)
  19450. {
  19451. return reader->queryThorDiskCallback()->queryLogicalFilename(row);
  19452. }
  19453. virtual const void *nextRow()
  19454. {
  19455. if (eof)
  19456. return NULL;
  19457. else if (useRemote())
  19458. return remote->nextRow();
  19459. assertex(xmlParser != NULL);
  19460. try
  19461. {
  19462. while (!eof)
  19463. {
  19464. //call to next() will callback on the IXmlSelect interface
  19465. bool gotNext = false;
  19466. gotNext = xmlParser->next();
  19467. if(!gotNext)
  19468. eof = true;
  19469. else if (lastMatch)
  19470. {
  19471. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19472. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19473. lastMatch.clear();
  19474. fileoffset = 0;
  19475. if (sizeGot)
  19476. {
  19477. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19478. if (processed > rowLimit)
  19479. {
  19480. if (traceLevel > 4)
  19481. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19482. readHelper->onLimitExceeded();
  19483. throwUnexpected(); // onLimitExceeded is not supposed to return
  19484. }
  19485. processed++;
  19486. if (processed > stopAfter) // MORE - bit of a strange place to check
  19487. {
  19488. eof = true;
  19489. return NULL;
  19490. }
  19491. return ret.getClear();
  19492. }
  19493. }
  19494. }
  19495. return NULL;
  19496. }
  19497. catch(IException *E)
  19498. {
  19499. throw makeWrappedException(E);
  19500. }
  19501. }
  19502. };
  19503. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19504. {
  19505. IHThorCsvReadArg *readHelper;
  19506. ICsvParameters * csvInfo;
  19507. unsigned headerLines;
  19508. unsigned maxDiskSize;
  19509. CSVSplitter csvSplitter;
  19510. unsigned __int64 localOffset;
  19511. const char *quotes;
  19512. const char *separators;
  19513. const char *terminators;
  19514. const char *escapes;
  19515. size32_t maxRowSize;
  19516. public:
  19517. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19518. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  19519. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19520. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  19521. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19522. {
  19523. compoundHelper = NULL;
  19524. readHelper = (IHThorCsvReadArg *)&helper;
  19525. rowLimit = readHelper->getRowLimit();
  19526. stopAfter = readHelper->getChooseNLimit();
  19527. csvInfo = readHelper->queryCsvParameters();
  19528. maxDiskSize = csvInfo->queryMaxSize();
  19529. localOffset = 0;
  19530. headerLines = 0;
  19531. }
  19532. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19533. {
  19534. rowLimit = readHelper->getRowLimit();
  19535. stopAfter = readHelper->getChooseNLimit();
  19536. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19537. if (!useRemote())
  19538. {
  19539. headerLines = csvInfo->queryHeaderLen();
  19540. if (headerLines && isLocal && reader->queryFilePart() != 1)
  19541. 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...
  19542. if (!eof)
  19543. {
  19544. if (varFileInfo)
  19545. {
  19546. const IPropertyTree *options = varFileInfo->queryProperties();
  19547. if (options)
  19548. {
  19549. quotes = options->queryProp("@csvQuote");
  19550. separators = options->queryProp("@csvSeparate");
  19551. terminators = options->queryProp("@csvTerminate");
  19552. escapes = options->queryProp("@csvEscape");
  19553. }
  19554. }
  19555. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19556. }
  19557. }
  19558. }
  19559. virtual const void *nextRow()
  19560. {
  19561. if (eof)
  19562. return NULL;
  19563. else if (useRemote())
  19564. return remote->nextRow();
  19565. try
  19566. {
  19567. while (!eof)
  19568. {
  19569. if (reader->eos())
  19570. {
  19571. eof = true;
  19572. break;
  19573. }
  19574. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  19575. size32_t rowSize = 4096; // MORE - make configurable
  19576. size32_t thisLineLength;
  19577. loop
  19578. {
  19579. size32_t avail;
  19580. const void *peek = reader->peek(rowSize, avail);
  19581. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  19582. if (thisLineLength < rowSize || avail < rowSize)
  19583. break;
  19584. if (rowSize == maxRowSize)
  19585. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  19586. if (rowSize >= maxRowSize/2)
  19587. rowSize = maxRowSize;
  19588. else
  19589. rowSize += rowSize;
  19590. }
  19591. if (headerLines)
  19592. {
  19593. headerLines--;
  19594. reader->skip(thisLineLength);
  19595. }
  19596. else
  19597. {
  19598. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19599. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19600. reader->skip(thisLineLength);
  19601. if (transformedSize)
  19602. {
  19603. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19604. if (processed > rowLimit)
  19605. {
  19606. readHelper->onLimitExceeded();
  19607. throwUnexpected(); // onLimitExceeded is not supposed to return
  19608. }
  19609. processed++;
  19610. if (processed > stopAfter) // MORE - bit of a strange place to check
  19611. {
  19612. eof = true;
  19613. return NULL;
  19614. }
  19615. return ret.getClear();
  19616. }
  19617. }
  19618. }
  19619. return NULL;
  19620. }
  19621. catch(IException *E)
  19622. {
  19623. throw makeWrappedException(E);
  19624. }
  19625. }
  19626. virtual void reset()
  19627. {
  19628. CRoxieServerDiskReadBaseActivity::reset();
  19629. csvSplitter.reset();
  19630. localOffset = 0;
  19631. }
  19632. virtual unsigned __int64 getFilePosition(const void * row)
  19633. {
  19634. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  19635. }
  19636. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19637. {
  19638. UNIMPLEMENTED;
  19639. }
  19640. };
  19641. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  19642. {
  19643. IHThorDiskNormalizeArg *normalizeHelper;
  19644. bool firstPending;
  19645. public:
  19646. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  19647. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  19648. {
  19649. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  19650. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  19651. firstPending = true;
  19652. }
  19653. virtual void reset()
  19654. {
  19655. firstPending = true;
  19656. CRoxieServerDiskReadBaseActivity::reset();
  19657. }
  19658. virtual const void *nextRow()
  19659. {
  19660. if (eof)
  19661. return NULL;
  19662. else if (useRemote())
  19663. return remote->nextRow();
  19664. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19665. unsigned transformedSize = 0;
  19666. if (isKeyed)
  19667. {
  19668. loop
  19669. {
  19670. while (firstPending)
  19671. {
  19672. const void *nextCandidate = cursor->nextMatch();
  19673. if (!nextCandidate)
  19674. {
  19675. eof = true;
  19676. return NULL;
  19677. }
  19678. if (normalizeHelper->first(nextCandidate))
  19679. {
  19680. firstPending = false;
  19681. break;
  19682. }
  19683. }
  19684. transformedSize = normalizeHelper->transform(rowBuilder);
  19685. firstPending = !normalizeHelper->next();
  19686. if (transformedSize)
  19687. break;
  19688. }
  19689. }
  19690. else
  19691. {
  19692. assertex(reader != NULL);
  19693. loop
  19694. {
  19695. while (firstPending)
  19696. {
  19697. if (deserializeSource.eos())
  19698. {
  19699. eof = true;
  19700. return NULL;
  19701. }
  19702. prefetcher->readAhead(deserializeSource);
  19703. const byte *nextRec = deserializeSource.queryRow();
  19704. if (!cursor || !cursor->isFiltered(nextRec))
  19705. {
  19706. if (normalizeHelper->first(nextRec))
  19707. firstPending = false;
  19708. }
  19709. deserializeSource.finishedRow();
  19710. }
  19711. transformedSize = normalizeHelper->transform(rowBuilder);
  19712. firstPending = !normalizeHelper->next();
  19713. if (transformedSize)
  19714. break;
  19715. }
  19716. }
  19717. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  19718. processed++;
  19719. if (processed > rowLimit)
  19720. {
  19721. compoundHelper->onLimitExceeded();
  19722. throwUnexpected(); // onLimitExceeded is not supposed to return
  19723. }
  19724. if (processed > stopAfter) // MORE - bit of a strange place to check
  19725. {
  19726. eof = true;
  19727. return NULL;
  19728. }
  19729. return recBuffer.getClear();
  19730. }
  19731. };
  19732. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  19733. {
  19734. protected:
  19735. bool done;
  19736. public:
  19737. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19738. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  19739. done(false)
  19740. {
  19741. }
  19742. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19743. {
  19744. done = false;
  19745. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19746. }
  19747. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  19748. {
  19749. if (idx==(unsigned)-1)
  19750. idx = 0;
  19751. return idx ? NULL: this;
  19752. }
  19753. };
  19754. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  19755. {
  19756. IHThorDiskCountArg & countHelper;
  19757. unsigned __int64 choosenLimit;
  19758. IHThorSourceCountLimit *limitHelper;
  19759. unsigned __int64 getSkippedCount()
  19760. {
  19761. unsigned flags = countHelper.getFlags();
  19762. if (flags & TDRlimitskips)
  19763. return 0;
  19764. else if (flags & TDRlimitcreates)
  19765. return 1;
  19766. else
  19767. {
  19768. assertex(limitHelper);
  19769. if (traceLevel > 4)
  19770. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19771. limitHelper->onLimitExceeded();
  19772. throwUnexpected(); // onLimitExceeded should always throw exception
  19773. }
  19774. }
  19775. public:
  19776. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19777. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19778. countHelper((IHThorDiskCountArg &)basehelper)
  19779. {
  19780. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19781. choosenLimit = 0;
  19782. }
  19783. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19784. {
  19785. choosenLimit = countHelper.getChooseNLimit();
  19786. if (limitHelper)
  19787. {
  19788. rowLimit = limitHelper->getRowLimit();
  19789. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  19790. }
  19791. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19792. }
  19793. virtual const void *nextRow()
  19794. {
  19795. ActivityTimer t(totalCycles, timeActivities);
  19796. if (done) return NULL;
  19797. done = true;
  19798. unsigned __int64 totalCount = 0;
  19799. if (helper.canMatchAny() && !eof)
  19800. {
  19801. if (useRemote())
  19802. {
  19803. loop
  19804. {
  19805. const void * next = remote->nextRow();
  19806. if (!next)
  19807. break;
  19808. if (meta.getFixedSize() == 1)
  19809. totalCount += *(byte *)next;
  19810. else
  19811. totalCount += *(unsigned __int64 *)next;
  19812. ReleaseRoxieRow(next);
  19813. if (totalCount > rowLimit)
  19814. {
  19815. totalCount = getSkippedCount();
  19816. break;
  19817. }
  19818. else if (totalCount >= choosenLimit)
  19819. {
  19820. totalCount = choosenLimit;
  19821. break;
  19822. }
  19823. }
  19824. }
  19825. else
  19826. {
  19827. if (isKeyed)
  19828. {
  19829. loop
  19830. {
  19831. const void *nextCandidate = cursor->nextMatch();
  19832. if (!nextCandidate)
  19833. break;
  19834. totalCount += countHelper.numValid(nextCandidate);
  19835. if (totalCount > rowLimit)
  19836. {
  19837. totalCount = getSkippedCount();
  19838. break;
  19839. }
  19840. else if (totalCount >= choosenLimit)
  19841. {
  19842. totalCount = choosenLimit;
  19843. break;
  19844. }
  19845. }
  19846. }
  19847. else
  19848. {
  19849. assertex(reader != NULL);
  19850. while (!deserializeSource.eos())
  19851. {
  19852. prefetcher->readAhead(deserializeSource);
  19853. const byte *nextRec = deserializeSource.queryRow();
  19854. if (!cursor || !cursor->isFiltered(nextRec))
  19855. {
  19856. totalCount += countHelper.numValid(nextRec);
  19857. }
  19858. deserializeSource.finishedRow();
  19859. if (totalCount > rowLimit)
  19860. {
  19861. totalCount = getSkippedCount();
  19862. break;
  19863. }
  19864. else if (totalCount >= choosenLimit)
  19865. {
  19866. totalCount = choosenLimit;
  19867. break;
  19868. }
  19869. }
  19870. }
  19871. }
  19872. }
  19873. size32_t rowSize = meta.getFixedSize();
  19874. void * result = rowAllocator->createRow();
  19875. if (rowSize == 1)
  19876. *(byte *)result = (byte)totalCount;
  19877. else
  19878. {
  19879. assertex(rowSize == sizeof(unsigned __int64));
  19880. *(unsigned __int64 *)result = totalCount;
  19881. }
  19882. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19883. }
  19884. };
  19885. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19886. {
  19887. IHThorCompoundAggregateExtra & aggregateHelper;
  19888. public:
  19889. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19890. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19891. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19892. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19893. {
  19894. }
  19895. const void * gatherMerged()
  19896. {
  19897. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19898. size32_t finalSize = 0;
  19899. if (useRemote())
  19900. {
  19901. const void * firstRow = remote->nextRow();
  19902. if (!firstRow)
  19903. {
  19904. rowBuilder.ensureRow();
  19905. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19906. }
  19907. else
  19908. {
  19909. // NOTE need to clone this because going to modify below, could special case 1 row only
  19910. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19911. ReleaseRoxieRow(firstRow);
  19912. }
  19913. loop
  19914. {
  19915. const void * next = remote->nextRow();
  19916. if (!next)
  19917. break;
  19918. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19919. ReleaseRoxieRow(next);
  19920. }
  19921. }
  19922. else
  19923. {
  19924. aggregateHelper.clearAggregate(rowBuilder);
  19925. if (helper.canMatchAny() && !eof)
  19926. {
  19927. if (isKeyed)
  19928. {
  19929. loop
  19930. {
  19931. const void *next = cursor->nextMatch();
  19932. if (!next)
  19933. break;
  19934. aggregateHelper.processRow(rowBuilder, next);
  19935. }
  19936. }
  19937. else
  19938. {
  19939. assertex(reader != NULL);
  19940. while (!deserializeSource.eos())
  19941. {
  19942. prefetcher->readAhead(deserializeSource);
  19943. const byte *nextRec = deserializeSource.queryRow();
  19944. if (!cursor || !cursor->isFiltered(nextRec))
  19945. {
  19946. aggregateHelper.processRow(rowBuilder, nextRec);
  19947. }
  19948. deserializeSource.finishedRow();
  19949. }
  19950. }
  19951. }
  19952. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19953. }
  19954. return rowBuilder.finalizeRowClear(finalSize);
  19955. }
  19956. virtual const void *nextRow()
  19957. {
  19958. ActivityTimer t(totalCycles, timeActivities);
  19959. if (done) return NULL;
  19960. const void * ret = gatherMerged();
  19961. done = true;
  19962. return ret;
  19963. }
  19964. };
  19965. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19966. {
  19967. IHThorDiskGroupAggregateArg & aggregateHelper;
  19968. RowAggregator resultAggregator;
  19969. bool gathered;
  19970. public:
  19971. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19972. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19973. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19974. resultAggregator(aggregateHelper, aggregateHelper),
  19975. gathered(false)
  19976. {
  19977. }
  19978. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19979. {
  19980. gathered= false;
  19981. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19982. resultAggregator.start(rowAllocator);
  19983. }
  19984. virtual void reset()
  19985. {
  19986. resultAggregator.reset();
  19987. CRoxieServerDiskAggregateBaseActivity::reset();
  19988. }
  19989. void gatherMerged()
  19990. {
  19991. if (useRemote())
  19992. {
  19993. loop
  19994. {
  19995. const void * next = remote->nextRow();
  19996. if (!next)
  19997. break;
  19998. resultAggregator.mergeElement(next);
  19999. ReleaseRoxieRow(next);
  20000. }
  20001. }
  20002. else
  20003. {
  20004. if (helper.canMatchAny() && !eof)
  20005. {
  20006. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  20007. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  20008. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  20009. ctx->queryCodeContext(), activityId);
  20010. processor->doQuery(NULL, 0, 0, 0);
  20011. }
  20012. }
  20013. gathered = true;
  20014. }
  20015. virtual const void *nextRow()
  20016. {
  20017. ActivityTimer t(totalCycles, timeActivities);
  20018. if (done)
  20019. return NULL;
  20020. if (!gathered)
  20021. gatherMerged();
  20022. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20023. if (next)
  20024. {
  20025. processed++;
  20026. return next->finalizeRowClear();
  20027. }
  20028. done = true;
  20029. return NULL;
  20030. }
  20031. };
  20032. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20033. {
  20034. public:
  20035. RemoteActivityId remoteId;
  20036. bool isLocal;
  20037. bool sorted;
  20038. bool maySkip;
  20039. bool variableFileName;
  20040. Owned<IFileIOArray> files;
  20041. Owned<IInMemoryIndexManager> manager;
  20042. Owned<const IResolvedFile> datafile;
  20043. const char *quotes;
  20044. const char *separators;
  20045. const char *terminators;
  20046. const char *escapes;
  20047. size32_t maxCsvRowSize;
  20048. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20049. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20050. {
  20051. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20052. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20053. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20054. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20055. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20056. quotes = separators = terminators = escapes = NULL;
  20057. if (!variableFileName)
  20058. {
  20059. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20060. OwnedRoxieString fileName(helper->getFileName());
  20061. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20062. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20063. if (isLocal || isSimple)
  20064. {
  20065. if (datafile)
  20066. {
  20067. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20068. files.setown(datafile->getIFileIOArray(isOpt, channel));
  20069. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  20070. const IPropertyTree *options = datafile->queryProperties();
  20071. if (options)
  20072. {
  20073. quotes = options->queryProp("@csvQuote");
  20074. separators = options->queryProp("@csvSeparate");
  20075. terminators = options->queryProp("@csvTerminate");
  20076. escapes = options->queryProp("@csvEscape");
  20077. }
  20078. }
  20079. else
  20080. manager.setown(getEmptyIndexManager());
  20081. }
  20082. }
  20083. switch (kind)
  20084. {
  20085. case TAKcsvread:
  20086. {
  20087. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20088. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20089. if (workunit)
  20090. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20091. break;
  20092. }
  20093. default:
  20094. maxCsvRowSize = 0; // unused
  20095. }
  20096. }
  20097. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20098. {
  20099. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20100. switch (kind)
  20101. {
  20102. case TAKcsvread:
  20103. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  20104. quotes, separators, terminators, escapes, maxCsvRowSize);
  20105. case TAKxmlread:
  20106. case TAKjsonread:
  20107. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20108. case TAKdiskread:
  20109. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  20110. case TAKdisknormalize:
  20111. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  20112. case TAKdiskcount:
  20113. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20114. case TAKdiskaggregate:
  20115. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20116. case TAKdiskgroupaggregate:
  20117. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
  20118. }
  20119. throwUnexpected();
  20120. }
  20121. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20122. {
  20123. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20124. }
  20125. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20126. {
  20127. if (datafile)
  20128. addXrefFileInfo(reply, datafile);
  20129. else
  20130. {
  20131. // Temporarily resolve the file
  20132. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20133. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20134. {
  20135. OwnedRoxieString fileName(helper->getFileName());
  20136. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20137. if (temp)
  20138. addXrefFileInfo(reply, temp);
  20139. }
  20140. }
  20141. }
  20142. virtual const StatisticsMapping &queryStatsMapping() const
  20143. {
  20144. return diskStatistics;
  20145. }
  20146. };
  20147. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20148. {
  20149. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20150. }
  20151. //=================================================================================
  20152. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20153. {
  20154. protected:
  20155. IHThorIndexReadBaseArg &indexHelper;
  20156. IHThorSteppedSourceExtra * steppedExtra;
  20157. Linked<IKeyArray> keySet;
  20158. Linked<TranslatorArray> translators;
  20159. CSkippableRemoteResultAdaptor remote;
  20160. CIndexTransformCallback callback;
  20161. bool sorted;
  20162. bool variableFileName;
  20163. bool variableInfoPending;
  20164. bool isOpt;
  20165. bool isLocal;
  20166. unsigned __int64 rowLimit;
  20167. unsigned __int64 keyedLimit;
  20168. unsigned __int64 choosenLimit;
  20169. unsigned accepted;
  20170. unsigned rejected;
  20171. unsigned seekGEOffset;
  20172. Owned<IKeyManager> tlk;
  20173. Owned<const IResolvedFile> varFileInfo;
  20174. const RemoteActivityId &remoteId;
  20175. void setVariableFileInfo()
  20176. {
  20177. OwnedRoxieString indexName(indexHelper.getFileName());
  20178. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20179. if (varFileInfo)
  20180. {
  20181. translators.setown(new TranslatorArray) ;
  20182. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20183. }
  20184. variableInfoPending = false;
  20185. }
  20186. public:
  20187. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20188. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20189. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20190. keySet(_keySet),
  20191. translators(_translators),
  20192. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20193. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20194. remoteId(_remoteId),
  20195. sorted(_sorted),
  20196. isLocal(_isLocal)
  20197. {
  20198. indexHelper.setCallback(&callback);
  20199. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20200. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20201. variableInfoPending = false;
  20202. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20203. seekGEOffset = 0;
  20204. // started = false;
  20205. rejected = accepted = 0;
  20206. rowLimit = choosenLimit = keyedLimit = 0;
  20207. }
  20208. virtual const IResolvedFile *queryVarFileInfo() const
  20209. {
  20210. return varFileInfo;
  20211. }
  20212. virtual void onCreate(IHThorArg *_colocalParent)
  20213. {
  20214. CRoxieServerActivity::onCreate(_colocalParent);
  20215. remote.onCreate(_colocalParent);
  20216. }
  20217. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20218. {
  20219. accepted = 0;
  20220. rejected = 0;
  20221. rowLimit = (unsigned __int64) -1;
  20222. keyedLimit = (unsigned __int64 ) -1;
  20223. choosenLimit = I64C(0x7fffffffffffffff);
  20224. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20225. remote.onStart(parentExtractSize, parentExtract);
  20226. variableInfoPending = variableFileName;
  20227. }
  20228. void processAllKeys()
  20229. {
  20230. try
  20231. {
  20232. if (indexHelper.canMatchAny())
  20233. {
  20234. if (variableInfoPending)
  20235. setVariableFileInfo();
  20236. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20237. if (keySet)
  20238. {
  20239. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20240. // 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
  20241. // However order is probably better to iterate fileno's inside partnos
  20242. // MORE - also not properly supporting STEPPED I fear.
  20243. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20244. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20245. {
  20246. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20247. if (thisBase)
  20248. {
  20249. unsigned fileNo = 0;
  20250. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20251. if (!thisKey->isTopLevelKey())
  20252. {
  20253. if (keyedLimit != (unsigned __int64) -1)
  20254. {
  20255. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20256. {
  20257. Owned<IKeyManager> countKey;
  20258. countKey.setown(createKeyManager(thisKey, 0, this));
  20259. countKey->setLayoutTranslator(translators->item(fileNo));
  20260. createSegmentMonitors(countKey);
  20261. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20262. if (count > keyedLimit)
  20263. {
  20264. if (traceLevel > 4)
  20265. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20266. onLimitExceeded(true);
  20267. }
  20268. }
  20269. }
  20270. }
  20271. if (seekGEOffset && !thisKey->isTopLevelKey())
  20272. {
  20273. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  20274. }
  20275. else
  20276. {
  20277. tlk.setown(createKeyManager(thisKey, 0, this));
  20278. tlk->setLayoutTranslator(translators->item(fileNo));
  20279. }
  20280. createSegmentMonitors(tlk);
  20281. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20282. {
  20283. StringBuffer out;
  20284. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20285. CTXLOG("Using filter %s", out.str());
  20286. if (ctx->queryProbeManager())
  20287. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20288. }
  20289. tlk->reset();
  20290. loop // for each file part
  20291. {
  20292. //block for TransformCallbackAssociation
  20293. {
  20294. TransformCallbackAssociation associate(callback, tlk);
  20295. if (thisKey->isTopLevelKey())
  20296. {
  20297. if (thisKey->isFullySorted())
  20298. {
  20299. while (tlk->lookup(false))
  20300. {
  20301. unsigned slavePart = (unsigned) tlk->queryFpos();
  20302. if (slavePart)
  20303. {
  20304. accepted++;
  20305. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20306. if (sorted && numChannels>1)
  20307. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20308. }
  20309. }
  20310. }
  20311. else
  20312. {
  20313. // MORE - we could check whether there are any matching parts if we wanted.
  20314. // If people are in the habit of sending null values that would be worthwhile
  20315. remote.getMem(0, fileNo, 0);
  20316. }
  20317. }
  20318. else
  20319. {
  20320. if (processSingleKey(thisKey, translators->item(fileNo)))
  20321. break;
  20322. }
  20323. }
  20324. if (++fileNo < thisBase->numParts())
  20325. {
  20326. thisKey = thisBase->queryPart(fileNo);
  20327. tlk->setKey(thisKey);
  20328. tlk->setLayoutTranslator(translators->item(fileNo));
  20329. tlk->reset();
  20330. }
  20331. else
  20332. break;
  20333. }
  20334. tlk->releaseSegmentMonitors();
  20335. tlk->setKey(NULL);
  20336. }
  20337. }
  20338. }
  20339. }
  20340. remote.flush();
  20341. remote.senddone();
  20342. }
  20343. catch (IException *E)
  20344. {
  20345. remote.setException(E);
  20346. }
  20347. }
  20348. virtual void createSegmentMonitors(IKeyManager *key)
  20349. {
  20350. indexHelper.createSegmentMonitors(key);
  20351. key->finishSegmentMonitors();
  20352. }
  20353. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  20354. virtual void reset()
  20355. {
  20356. if (accepted)
  20357. noteStatistic(StNumIndexAccepted, accepted);
  20358. if (rejected)
  20359. noteStatistic(StNumIndexRejected, rejected);
  20360. remote.onReset();
  20361. CRoxieServerActivity::reset();
  20362. if (varFileInfo)
  20363. {
  20364. keySet.clear();
  20365. varFileInfo.clear();
  20366. }
  20367. variableInfoPending = false;
  20368. }
  20369. virtual void stop()
  20370. {
  20371. remote.onStop();
  20372. CRoxieServerActivity::stop();
  20373. }
  20374. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20375. {
  20376. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20377. }
  20378. };
  20379. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20380. {
  20381. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20382. public:
  20383. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20384. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  20385. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  20386. {
  20387. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20388. }
  20389. virtual void reset()
  20390. {
  20391. remote.onReset();
  20392. CRoxieServerIndexActivity::reset();
  20393. }
  20394. virtual const void *nextRow()
  20395. {
  20396. ActivityTimer t(totalCycles, timeActivities);
  20397. try
  20398. {
  20399. const void *ret = remote.nextRow();
  20400. if (ret)
  20401. processed++;
  20402. return ret;
  20403. }
  20404. catch (IException *E)
  20405. {
  20406. throw makeWrappedException(E);
  20407. }
  20408. }
  20409. protected:
  20410. virtual const void * createLimitFailRow(bool isKeyed)
  20411. {
  20412. ensureRowAllocator();
  20413. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20414. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20415. if (outSize)
  20416. return rowBuilder.finalizeRowClear(outSize);
  20417. return NULL;
  20418. }
  20419. };
  20420. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20421. {
  20422. protected:
  20423. IHThorCompoundReadExtra & readHelper;
  20424. ISteppingMeta *rawMeta = nullptr;
  20425. CSteppingMeta steppingMeta;
  20426. unsigned * seekSizes = nullptr;
  20427. bool optimizeSteppedPostFilter;
  20428. ISteppingMeta * projectedMeta = nullptr;
  20429. unsigned maxSeekLookahead;
  20430. public:
  20431. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20432. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20433. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  20434. readHelper((IHThorIndexReadArg &)basehelper)
  20435. {
  20436. rawMeta = readHelper.queryRawSteppingMeta();
  20437. unsigned flags = indexHelper.getFlags();
  20438. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20439. seekSizes = NULL;
  20440. maxSeekLookahead = _maxSeekLookahead;
  20441. if (rawMeta)
  20442. {
  20443. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20444. unsigned maxFields = rawMeta->getNumFields();
  20445. seekGEOffset = fields[0].offset;
  20446. seekSizes = new unsigned[maxFields];
  20447. seekSizes[0] = fields[0].size;
  20448. for (unsigned i=1; i < maxFields; i++)
  20449. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20450. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20451. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20452. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20453. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20454. steppingMeta.init(useMeta, hasPostFilter);
  20455. }
  20456. }
  20457. ~CRoxieServerIndexReadActivity()
  20458. {
  20459. delete [] seekSizes;
  20460. }
  20461. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20462. {
  20463. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20464. steppingMeta.setDistributed();
  20465. if (steppedExtra)
  20466. steppingMeta.setExtra(steppedExtra);
  20467. rowLimit = readHelper.getRowLimit();
  20468. keyedLimit = readHelper.getKeyedLimit();
  20469. choosenLimit = readHelper.getChooseNLimit();
  20470. if (!paused)
  20471. processAllKeys();
  20472. }
  20473. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20474. {
  20475. public:
  20476. IMPLEMENT_IINTERFACE;
  20477. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20478. {
  20479. Link();
  20480. return const_cast<LazyLocalKeyReader*> (this);
  20481. }
  20482. virtual const void *getMessageHeader(unsigned &length) const
  20483. {
  20484. length = 0;
  20485. return NULL;
  20486. }
  20487. virtual const void *getMessageMetadata(unsigned &length) const
  20488. {
  20489. length = 0;
  20490. return NULL;
  20491. }
  20492. virtual void discard() const
  20493. {
  20494. // nothing to do.
  20495. }
  20496. unsigned keyedCount;
  20497. unsigned matched;
  20498. bool EOFseen;
  20499. Owned<IKeyIndexSet> keySet;
  20500. Owned<IKeyManager> tlk;
  20501. CRoxieServerIndexReadActivity &owner;
  20502. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  20503. : owner(_owner)
  20504. {
  20505. keyedCount = 0;
  20506. matched = 0;
  20507. EOFseen = false;
  20508. keySet.setown(createKeyIndexSet());
  20509. keySet->addIndex(LINK(key));
  20510. if (owner.seekGEOffset)
  20511. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  20512. else
  20513. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  20514. tlk->setLayoutTranslator(trans);
  20515. owner.indexHelper.createSegmentMonitors(tlk);
  20516. tlk->finishSegmentMonitors();
  20517. tlk->reset();
  20518. }
  20519. virtual const void *getNext(int length)
  20520. {
  20521. TransformCallbackAssociation associate(owner.callback, tlk);
  20522. while (tlk->lookup(true))
  20523. {
  20524. keyedCount++;
  20525. if (keyedCount > owner.keyedLimit)
  20526. {
  20527. owner.onLimitExceeded(true); // Should throw exception
  20528. throwUnexpected();
  20529. }
  20530. size32_t transformedSize;
  20531. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20532. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  20533. try
  20534. {
  20535. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20536. owner.callback.finishedRow();
  20537. }
  20538. catch (IException *E)
  20539. {
  20540. throw owner.makeWrappedException(E);
  20541. }
  20542. if (transformedSize)
  20543. {
  20544. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20545. matched++;
  20546. if (matched > owner.rowLimit)
  20547. {
  20548. owner.onLimitExceeded(false); // Should throw exception
  20549. throwUnexpected();
  20550. }
  20551. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20552. {
  20553. break;
  20554. }
  20555. owner.accepted++;
  20556. return result.getClear();
  20557. }
  20558. else
  20559. owner.rejected++;
  20560. }
  20561. EOFseen = true;
  20562. return NULL;
  20563. }
  20564. virtual bool atEOF() const
  20565. {
  20566. return EOFseen;
  20567. }
  20568. virtual bool isSerialized() const
  20569. {
  20570. return false;
  20571. }
  20572. };
  20573. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20574. {
  20575. ensureRowAllocator();
  20576. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  20577. return false;
  20578. }
  20579. virtual void onLimitExceeded(bool isKeyed)
  20580. {
  20581. if (traceLevel > 4)
  20582. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20583. if (isKeyed)
  20584. {
  20585. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20586. {
  20587. if (ctx->queryDebugContext())
  20588. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20589. throw makeLimitSkipException(true);
  20590. }
  20591. else
  20592. readHelper.onKeyedLimitExceeded();
  20593. }
  20594. else
  20595. {
  20596. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20597. {
  20598. if (ctx->queryDebugContext())
  20599. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20600. throw makeLimitSkipException(false);
  20601. }
  20602. else
  20603. readHelper.onLimitExceeded();
  20604. }
  20605. }
  20606. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  20607. {
  20608. out.append((unsigned short) numFields);
  20609. out.append((unsigned short) seekLen);
  20610. out.append((unsigned short) stepExtra.queryFlags());
  20611. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  20612. if (seeks)
  20613. {
  20614. unsigned lookahead = 40000/seekLen;
  20615. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  20616. lookahead = maxSeekLookahead;
  20617. seeks->ensureFilled(seek, numFields, lookahead);
  20618. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  20619. unsigned serialized = 1; // rawseek is always serialized...
  20620. unsigned patchLength = out.length();
  20621. out.append(serialized); // NOTE - we come back and patch with the actual value...
  20622. out.append(seekLen, rawSeek);
  20623. if (seeks->ordinality())
  20624. {
  20625. const void *lastSeek = rawSeek;
  20626. byte *nextSeek = NULL;
  20627. if (projectedMeta)
  20628. nextSeek = (byte *) alloca(seekLen);
  20629. for (unsigned i = 0; i < seeks->ordinality(); i++)
  20630. {
  20631. if (projectedMeta)
  20632. {
  20633. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  20634. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20635. }
  20636. else
  20637. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  20638. int diff = memcmp(nextSeek, lastSeek, seekLen);
  20639. if (diff > 0)
  20640. {
  20641. serialized++;
  20642. out.append(seekLen, nextSeek);
  20643. lastSeek = (const byte *) out.reserve(0) - seekLen;
  20644. }
  20645. }
  20646. unsigned length = out.length();
  20647. out.setWritePos(patchLength);
  20648. out.append(serialized);
  20649. out.setWritePos(length);
  20650. }
  20651. }
  20652. else
  20653. {
  20654. out.append(false);
  20655. out.append(1);
  20656. out.append(seekLen, rawSeek);
  20657. }
  20658. }
  20659. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20660. {
  20661. ActivityTimer t(totalCycles, timeActivities);
  20662. try
  20663. {
  20664. unsigned seeklen = 0;
  20665. const void *rawSeek = NULL;
  20666. if (seek && numFields)
  20667. {
  20668. seeklen = seekSizes[numFields-1];
  20669. rawSeek = (const byte *)seek + seekGEOffset;
  20670. if (projectedMeta)
  20671. {
  20672. byte * temp = (byte *) alloca(seeklen);
  20673. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  20674. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20675. rawSeek = (byte *)temp;
  20676. }
  20677. }
  20678. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  20679. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  20680. processed++;
  20681. return ret;
  20682. }
  20683. catch (IException *E)
  20684. {
  20685. throw makeWrappedException(E);
  20686. }
  20687. }
  20688. virtual IInputSteppingMeta * querySteppingMeta()
  20689. {
  20690. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20691. return &steppingMeta;
  20692. return NULL;
  20693. }
  20694. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20695. {
  20696. if (variableInfoPending)
  20697. setVariableFileInfo();
  20698. return this;
  20699. }
  20700. virtual IKeyArray *getKeySet() const
  20701. {
  20702. return keySet.getLink();
  20703. }
  20704. virtual const IResolvedFile *getVarFileInfo() const
  20705. {
  20706. return varFileInfo.getLink();
  20707. }
  20708. virtual TranslatorArray *getTranslators() const
  20709. {
  20710. return translators.getLink();
  20711. }
  20712. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20713. {
  20714. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20715. }
  20716. virtual IRoxieServerActivity *queryActivity() { return this; }
  20717. virtual const RemoteActivityId& queryRemoteId() const
  20718. {
  20719. return remoteId;
  20720. }
  20721. };
  20722. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  20723. {
  20724. IHThorCompoundReadExtra & readHelper;
  20725. IHThorIndexReadBaseArg & indexHelper;
  20726. IHThorSourceLimitTransformExtra * limitTransformExtra;
  20727. IHThorSteppedSourceExtra * steppedExtra;
  20728. bool eof;
  20729. Linked<IKeyArray>keySet;
  20730. Owned<IKeyIndexSet>keyIndexSet;
  20731. Owned<IKeyManager> tlk;
  20732. Linked<TranslatorArray> translators;
  20733. CIndexTransformCallback callback;
  20734. unsigned __int64 keyedLimit;
  20735. unsigned rowLimit;
  20736. unsigned chooseNLimit;
  20737. unsigned accepted;
  20738. unsigned rejected;
  20739. unsigned keyedCount;
  20740. ISteppingMeta * rawMeta;
  20741. ISteppingMeta * projectedMeta;
  20742. size32_t seekGEOffset;
  20743. unsigned * seekSizes;
  20744. CSteppingMeta steppingMeta;
  20745. Owned<const IResolvedFile> varFileInfo;
  20746. const RemoteActivityId &remoteId;
  20747. bool firstRead;
  20748. bool variableFileName;
  20749. bool variableInfoPending;
  20750. bool isOpt;
  20751. bool isLocal;
  20752. bool optimizeSteppedPostFilter;
  20753. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  20754. void initKeySet()
  20755. {
  20756. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  20757. {
  20758. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  20759. }
  20760. keyIndexSet.setown(createKeyIndexSet());
  20761. for (unsigned part = 0; part < keySet->length(); part++)
  20762. {
  20763. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  20764. if (kib)
  20765. {
  20766. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  20767. {
  20768. IKeyIndex *k = kib->queryPart(subpart);
  20769. if (k)
  20770. {
  20771. assertex(!k->isTopLevelKey());
  20772. keyIndexSet->addIndex(LINK(k));
  20773. }
  20774. }
  20775. }
  20776. }
  20777. }
  20778. void setVariableFileInfo()
  20779. {
  20780. OwnedRoxieString indexName(indexHelper.getFileName());
  20781. varFileInfo.setown(resolveLFN(indexName, isOpt));
  20782. translators.setown(new TranslatorArray) ;
  20783. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  20784. initKeySet();
  20785. variableInfoPending = false;
  20786. }
  20787. void onEOF()
  20788. {
  20789. callback.setManager(NULL);
  20790. eof = true;
  20791. tlk.clear();
  20792. }
  20793. public:
  20794. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20795. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  20796. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20797. readHelper((IHThorIndexReadArg &)basehelper),
  20798. indexHelper((IHThorIndexReadArg &)basehelper),
  20799. translators(_translatorArray),
  20800. keySet(_keyArray),
  20801. isLocal(_isLocal),
  20802. remoteId(_remoteId)
  20803. {
  20804. rowLimit = 0;
  20805. keyedLimit = 0;
  20806. chooseNLimit = 0;
  20807. indexHelper.setCallback(&callback);
  20808. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  20809. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  20810. unsigned flags = indexHelper.getFlags();
  20811. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20812. variableInfoPending = false;
  20813. isOpt = (flags & TIRoptional) != 0;
  20814. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20815. firstRead = true;
  20816. accepted = 0;
  20817. rejected = 0;
  20818. keyedCount = 0;
  20819. eof = false;
  20820. rawMeta = readHelper.queryRawSteppingMeta();
  20821. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20822. seekGEOffset = 0;
  20823. seekSizes = NULL;
  20824. if (rawMeta)
  20825. {
  20826. // MORE - should check all keys in maxFields list can actually be keyed.
  20827. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20828. unsigned maxFields = rawMeta->getNumFields();
  20829. seekGEOffset = fields[0].offset;
  20830. seekSizes = new unsigned[maxFields];
  20831. seekSizes[0] = fields[0].size;
  20832. for (unsigned i=1; i < maxFields; i++)
  20833. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20834. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20835. if (projectedMeta)
  20836. steppingMeta.init(projectedMeta, hasPostFilter);
  20837. else
  20838. steppingMeta.init(rawMeta, hasPostFilter);
  20839. }
  20840. }
  20841. virtual const IResolvedFile *queryVarFileInfo() const
  20842. {
  20843. return varFileInfo;
  20844. }
  20845. ~CRoxieServerSimpleIndexReadActivity()
  20846. {
  20847. delete [] seekSizes;
  20848. }
  20849. virtual bool needsAllocator() const { return true; }
  20850. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20851. {
  20852. firstRead = true;
  20853. accepted = 0;
  20854. rejected = 0;
  20855. keyedCount = 0;
  20856. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20857. if (steppedExtra)
  20858. steppingMeta.setExtra(steppedExtra);
  20859. eof = !indexHelper.canMatchAny();
  20860. if (variableFileName)
  20861. variableInfoPending = true;
  20862. else
  20863. {
  20864. variableInfoPending = false;
  20865. if (!keyIndexSet)
  20866. initKeySet();
  20867. }
  20868. }
  20869. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20870. {
  20871. if (variableInfoPending)
  20872. setVariableFileInfo();
  20873. return this;
  20874. }
  20875. virtual IKeyArray *getKeySet() const
  20876. {
  20877. return keySet.getLink();
  20878. }
  20879. virtual const IResolvedFile *getVarFileInfo() const
  20880. {
  20881. return varFileInfo.getLink();
  20882. }
  20883. virtual TranslatorArray *getTranslators() const
  20884. {
  20885. return translators.getLink();
  20886. }
  20887. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20888. {
  20889. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20890. }
  20891. virtual IRoxieServerActivity *queryActivity() { return this; }
  20892. virtual const RemoteActivityId& queryRemoteId() const
  20893. {
  20894. return remoteId;
  20895. }
  20896. const void *nextRow()
  20897. {
  20898. bool matched = true;
  20899. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  20900. }
  20901. unsigned __int64 checkCount(unsigned __int64 limit)
  20902. {
  20903. unsigned numParts = keyIndexSet->numParts();
  20904. unsigned __int64 result = 0;
  20905. for (unsigned i = 0; i < numParts; i++)
  20906. {
  20907. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20908. countTlk->setLayoutTranslator(translators->item(i));
  20909. indexHelper.createSegmentMonitors(countTlk);
  20910. countTlk->finishSegmentMonitors();
  20911. result += countTlk->checkCount(limit-result);
  20912. if (result > limit)
  20913. break;
  20914. }
  20915. return result;
  20916. }
  20917. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20918. {
  20919. ActivityTimer t(totalCycles, timeActivities);
  20920. if (eof)
  20921. return NULL;
  20922. if (firstRead)
  20923. {
  20924. if (variableInfoPending)
  20925. setVariableFileInfo();
  20926. rowLimit = (unsigned) readHelper.getRowLimit();
  20927. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20928. unsigned numParts = keyIndexSet->numParts();
  20929. if (!numParts)
  20930. {
  20931. onEOF();
  20932. return NULL;
  20933. }
  20934. if (numParts > 1 || seekGEOffset)
  20935. {
  20936. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20937. // note that we don't set up translator because we don't support it. If that ever changes...
  20938. }
  20939. else
  20940. {
  20941. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20942. tlk->setLayoutTranslator(translators->item(0));
  20943. }
  20944. indexHelper.createSegmentMonitors(tlk);
  20945. tlk->finishSegmentMonitors();
  20946. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20947. {
  20948. StringBuffer out;
  20949. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20950. CTXLOG("Using filter %s", out.str());
  20951. if (ctx->queryProbeManager())
  20952. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20953. }
  20954. tlk->reset();
  20955. callback.setManager(tlk);
  20956. keyedLimit = readHelper.getKeyedLimit();
  20957. if (keyedLimit != (unsigned __int64) -1)
  20958. {
  20959. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20960. {
  20961. unsigned __int64 count = checkCount(keyedLimit);
  20962. if (count > keyedLimit)
  20963. {
  20964. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20965. readHelper.onKeyedLimitExceeded();
  20966. const void * ret = NULL;
  20967. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20968. ret = createKeyedLimitOnFailRow();
  20969. onEOF();
  20970. return ret;
  20971. }
  20972. keyedLimit = (unsigned __int64) -1;
  20973. }
  20974. }
  20975. firstRead = false;
  20976. }
  20977. if (accepted == chooseNLimit)
  20978. {
  20979. onEOF();
  20980. return NULL;
  20981. }
  20982. const byte * rawSeek = NULL;
  20983. unsigned seekSize = 0;
  20984. if (seek)
  20985. {
  20986. seekSize = seekSizes[numFields-1];
  20987. rawSeek = (const byte *)seek + seekGEOffset;
  20988. if (projectedMeta)
  20989. {
  20990. byte *temp = (byte *) alloca(seekSize);
  20991. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20992. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20993. rawSeek = (byte *)temp;
  20994. }
  20995. #ifdef _DEBUG
  20996. // StringBuffer seekStr;
  20997. // for (unsigned i = 0; i < seekSize; i++)
  20998. // {
  20999. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21000. // }
  21001. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21002. #endif
  21003. }
  21004. const byte * originalRawSeek = rawSeek;
  21005. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21006. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21007. {
  21008. checkAbort();
  21009. keyedCount++;
  21010. if (keyedCount > keyedLimit)
  21011. {
  21012. readHelper.onKeyedLimitExceeded();
  21013. break;
  21014. }
  21015. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  21016. #ifdef _DEBUG
  21017. // StringBuffer recstr;
  21018. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21019. // for (unsigned i = 0; i < size; i++)
  21020. // {
  21021. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21022. // }
  21023. // DBGLOG("nextRowGE Got %s", recstr.str());
  21024. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21025. assertex(!"smart seek failure");
  21026. #endif
  21027. size32_t transformedSize;
  21028. rowBuilder.ensureRow();
  21029. try
  21030. {
  21031. transformedSize = readHelper.transform(rowBuilder, keyRow);
  21032. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21033. //then return a mismatch record - so the join code can start seeking on the other input.
  21034. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21035. {
  21036. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21037. {
  21038. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  21039. if (transformedSize != 0)
  21040. wasCompleteMatch = false;
  21041. }
  21042. }
  21043. callback.finishedRow();
  21044. }
  21045. catch (IException *E)
  21046. {
  21047. throw makeWrappedException(E);
  21048. }
  21049. if (transformedSize)
  21050. {
  21051. accepted++;
  21052. if (accepted > rowLimit)
  21053. {
  21054. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21055. {
  21056. throwUnexpected(); // should not have used simple variant if maySkip set...
  21057. }
  21058. if (traceLevel > 4)
  21059. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21060. readHelper.onLimitExceeded();
  21061. break;
  21062. }
  21063. processed++;
  21064. #ifdef _DEBUG
  21065. // const byte *ret = (const byte *) out.get();
  21066. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21067. // queryOutputMeta()->toXML(ret, xmlwrite);
  21068. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21069. #endif
  21070. return rowBuilder.finalizeRowClear(transformedSize);
  21071. }
  21072. else
  21073. rejected++;
  21074. rawSeek = NULL;
  21075. }
  21076. onEOF();
  21077. return NULL;
  21078. }
  21079. virtual void reset()
  21080. {
  21081. onEOF();
  21082. if (accepted)
  21083. noteStatistic(StNumIndexAccepted, accepted);
  21084. if (rejected)
  21085. noteStatistic(StNumIndexRejected, rejected);
  21086. if (variableFileName)
  21087. {
  21088. varFileInfo.clear();
  21089. translators.clear();
  21090. }
  21091. variableInfoPending = false;
  21092. CRoxieServerActivity::reset();
  21093. }
  21094. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21095. {
  21096. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21097. }
  21098. virtual IInputSteppingMeta * querySteppingMeta()
  21099. {
  21100. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21101. return &steppingMeta;
  21102. return NULL;
  21103. }
  21104. protected:
  21105. const void * createKeyedLimitOnFailRow()
  21106. {
  21107. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21108. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  21109. if (outSize)
  21110. return rowBuilder.finalizeRowClear(outSize);
  21111. return NULL;
  21112. }
  21113. };
  21114. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  21115. {
  21116. public:
  21117. Owned<IKeyArray> keySet;
  21118. Owned<TranslatorArray> translatorArray;
  21119. Owned<IDefRecordMeta> activityMeta;
  21120. RemoteActivityId remoteId;
  21121. bool isSimple;
  21122. bool isLocal;
  21123. bool maySkip;
  21124. bool sorted;
  21125. bool variableFileName;
  21126. bool enableFieldTranslation;
  21127. unsigned maxSeekLookahead;
  21128. Owned<const IResolvedFile> indexfile;
  21129. CRoxieServerSideCache *cache;
  21130. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21131. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  21132. {
  21133. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21134. unsigned flags = indexHelper->getFlags();
  21135. sorted = (flags & TIRunordered) == 0;
  21136. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21137. rtlDataAttr indexLayoutMeta;
  21138. size32_t indexLayoutSize;
  21139. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21140. assertex(indexLayoutSize==0);
  21141. MemoryBuffer m;
  21142. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21143. activityMeta.setown(deserializeRecordMeta(m, true));
  21144. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  21145. translatorArray.setown(new TranslatorArray);
  21146. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21147. if (!variableFileName)
  21148. {
  21149. bool isOpt = (flags & TIRoptional) != 0;
  21150. OwnedRoxieString indexName(indexHelper->getFileName());
  21151. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21152. if (indexfile)
  21153. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21154. }
  21155. isSimple = isLocal;
  21156. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  21157. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  21158. {
  21159. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21160. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  21161. isSimple = true;
  21162. }
  21163. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  21164. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  21165. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  21166. }
  21167. ~CRoxieServerBaseIndexActivityFactory()
  21168. {
  21169. delete cache;
  21170. }
  21171. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21172. {
  21173. if (indexfile)
  21174. addXrefFileInfo(reply, indexfile);
  21175. else
  21176. {
  21177. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  21178. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  21179. {
  21180. OwnedRoxieString indexName(indexHelper->getFileName());
  21181. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  21182. if (temp)
  21183. addXrefFileInfo(reply, temp);
  21184. }
  21185. }
  21186. }
  21187. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  21188. {
  21189. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  21190. }
  21191. virtual IRoxieServerSideCache *queryServerSideCache() const
  21192. {
  21193. return cache;
  21194. }
  21195. virtual bool getEnableFieldTranslation() const
  21196. {
  21197. return enableFieldTranslation;
  21198. }
  21199. virtual IDefRecordMeta *queryActivityMeta() const
  21200. {
  21201. return activityMeta;
  21202. }
  21203. virtual const StatisticsMapping &queryStatsMapping() const
  21204. {
  21205. return indexStatistics;
  21206. }
  21207. };
  21208. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21209. {
  21210. public:
  21211. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21212. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21213. {
  21214. }
  21215. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21216. {
  21217. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21218. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21219. else if (isSimple && !maySkip)
  21220. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21221. else
  21222. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  21223. }
  21224. };
  21225. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21226. {
  21227. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21228. }
  21229. //--------------------------------------------------------------------------------------------------------------------------
  21230. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21231. {
  21232. bool done;
  21233. public:
  21234. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21235. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21236. {
  21237. done = false;
  21238. }
  21239. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21240. {
  21241. done = false;
  21242. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21243. }
  21244. virtual bool needsAllocator() const { return true; }
  21245. virtual const void *nextRow()
  21246. {
  21247. ActivityTimer t(totalCycles, timeActivities);
  21248. if (done) return NULL;
  21249. done = true;
  21250. size32_t rowSize = meta.getFixedSize();
  21251. void * nullRow = rowAllocator->createRow();
  21252. if (rowSize == 1)
  21253. *(byte *)nullRow = 0;
  21254. else
  21255. {
  21256. assertex(rowSize == sizeof(unsigned __int64));
  21257. *(unsigned __int64 *)nullRow = 0;
  21258. }
  21259. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21260. }
  21261. };
  21262. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21263. {
  21264. IHThorCompoundCountExtra & countHelper;
  21265. IHThorSourceCountLimit * limitHelper;
  21266. bool done;
  21267. public:
  21268. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21269. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21270. countHelper((IHThorIndexCountArg &)basehelper),
  21271. done(false)
  21272. {
  21273. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  21274. }
  21275. virtual bool needsAllocator() const { return true; }
  21276. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21277. {
  21278. done = false;
  21279. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21280. choosenLimit = countHelper.getChooseNLimit();
  21281. if (limitHelper)
  21282. {
  21283. rowLimit = limitHelper->getRowLimit();
  21284. keyedLimit = limitHelper->getKeyedLimit();
  21285. }
  21286. if (!paused)
  21287. processAllKeys();
  21288. }
  21289. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21290. {
  21291. unsigned __int64 count = 0;
  21292. if (countHelper.hasFilter())
  21293. {
  21294. while (tlk->lookup(true))
  21295. {
  21296. try
  21297. {
  21298. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  21299. callback.finishedRow();
  21300. }
  21301. catch (IException *E)
  21302. {
  21303. throw makeWrappedException(E);
  21304. }
  21305. accepted++;
  21306. if (count >= choosenLimit) // MORE - what about limit?
  21307. break;
  21308. }
  21309. }
  21310. else
  21311. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21312. if (count)
  21313. {
  21314. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21315. if (count > choosenLimit)
  21316. count = choosenLimit;
  21317. void * recBuffer = rowAllocator->createRow();
  21318. if (meta.getFixedSize() == 1)
  21319. *(byte *)recBuffer = (byte)count;
  21320. else
  21321. {
  21322. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21323. *(unsigned __int64 *)recBuffer = count;
  21324. }
  21325. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21326. result->append(recBuffer);
  21327. remote.injectResult(result.getClear());
  21328. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21329. if (count >= choosenLimit)
  21330. return true;
  21331. }
  21332. return false;
  21333. }
  21334. virtual void onLimitExceeded(bool isKeyed)
  21335. {
  21336. if (traceLevel > 4)
  21337. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21338. if (isKeyed)
  21339. {
  21340. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21341. {
  21342. if (ctx->queryDebugContext())
  21343. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21344. throw makeLimitSkipException(true);
  21345. }
  21346. else
  21347. {
  21348. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  21349. limitHelper->onKeyedLimitExceeded();
  21350. }
  21351. }
  21352. else
  21353. {
  21354. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21355. {
  21356. if (ctx->queryDebugContext())
  21357. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21358. throw makeLimitSkipException(false);
  21359. }
  21360. else
  21361. {
  21362. assertex(limitHelper);
  21363. limitHelper->onLimitExceeded();
  21364. }
  21365. }
  21366. }
  21367. virtual const void *createLimitFailRow(bool isKeyed)
  21368. {
  21369. throwUnexpected();
  21370. }
  21371. virtual const void *nextRow()
  21372. {
  21373. ActivityTimer t(totalCycles, timeActivities);
  21374. if (done) return NULL;
  21375. done = true;
  21376. unsigned __int64 totalCount = 0;
  21377. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21378. try
  21379. {
  21380. loop
  21381. {
  21382. const void * next = remote.nextRow();
  21383. if (!next)
  21384. break;
  21385. if (meta.getFixedSize() == 1)
  21386. totalCount += *(byte *)next;
  21387. else
  21388. totalCount += *(unsigned __int64 *) next;
  21389. ReleaseRoxieRow(next);
  21390. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21391. break;
  21392. }
  21393. if (totalCount > rowLimit)
  21394. {
  21395. unsigned flags = indexHelper.getFlags();
  21396. if (flags & TIRlimitskips)
  21397. totalCount = 0;
  21398. else if (flags & TIRlimitcreates)
  21399. totalCount = 1;
  21400. else
  21401. {
  21402. assertex(limitHelper);
  21403. limitHelper->onLimitExceeded();
  21404. }
  21405. }
  21406. else if (totalCount > choosenLimit)
  21407. totalCount = choosenLimit;
  21408. }
  21409. catch (IException *E)
  21410. {
  21411. if (QUERYINTERFACE(E, LimitSkipException))
  21412. {
  21413. totalCount = 0;
  21414. unsigned flags = indexHelper.getFlags();
  21415. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21416. {
  21417. if (flags & TIRkeyedlimitcreates)
  21418. totalCount++;
  21419. }
  21420. else
  21421. {
  21422. if (flags & TIRlimitcreates)
  21423. totalCount++;
  21424. }
  21425. if (totalCount > choosenLimit)
  21426. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21427. E->Release();
  21428. }
  21429. else
  21430. throw ;
  21431. }
  21432. void * result = rowAllocator->createRow();
  21433. if (meta.getFixedSize() == 1)
  21434. *(byte *)result = (byte)totalCount;
  21435. else
  21436. {
  21437. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21438. *(unsigned __int64 *)result = totalCount;
  21439. }
  21440. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21441. }
  21442. };
  21443. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21444. {
  21445. public:
  21446. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21447. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21448. {
  21449. }
  21450. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21451. {
  21452. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21453. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21454. // else if (isSimple)
  21455. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21456. else
  21457. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21458. }
  21459. };
  21460. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21461. {
  21462. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21463. }
  21464. //--------------------------------------------------------------------------------------------------------------------------
  21465. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21466. {
  21467. IHThorIndexAggregateArg &aggregateHelper;
  21468. bool done;
  21469. public:
  21470. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21471. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21472. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21473. {
  21474. done = false;
  21475. }
  21476. virtual bool needsAllocator() const { return true; }
  21477. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21478. {
  21479. done = false;
  21480. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21481. }
  21482. virtual const void *nextRow()
  21483. {
  21484. ActivityTimer t(totalCycles, timeActivities);
  21485. if (done) return NULL;
  21486. done = true;
  21487. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21488. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21489. return rowBuilder.finalizeRowClear(thisSize);
  21490. }
  21491. };
  21492. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21493. {
  21494. IHThorCompoundAggregateExtra & aggregateHelper;
  21495. bool done;
  21496. public:
  21497. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21498. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21499. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21500. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21501. done(false)
  21502. {
  21503. }
  21504. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21505. {
  21506. done = false;
  21507. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21508. if (!paused)
  21509. processAllKeys();
  21510. }
  21511. virtual bool needsAllocator() const { return true; }
  21512. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21513. {
  21514. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21515. while (tlk->lookup(true))
  21516. {
  21517. if (!rowBuilder.exists())
  21518. {
  21519. rowBuilder.ensureRow();
  21520. aggregateHelper.clearAggregate(rowBuilder);
  21521. }
  21522. try
  21523. {
  21524. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  21525. callback.finishedRow();
  21526. }
  21527. catch (IException *E)
  21528. {
  21529. throw makeWrappedException(E);
  21530. }
  21531. accepted++;
  21532. }
  21533. if (aggregateHelper.processedAnyRows())
  21534. {
  21535. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21536. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21537. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21538. result->append(recBuffer);
  21539. remote.injectResult(result.getClear());
  21540. }
  21541. return false;
  21542. }
  21543. virtual void onLimitExceeded(bool isKeyed)
  21544. {
  21545. if (traceLevel > 4)
  21546. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21547. throwUnexpected();
  21548. }
  21549. virtual const void *createLimitFailRow(bool isKeyed)
  21550. {
  21551. throwUnexpected();
  21552. }
  21553. const void * gatherMerged()
  21554. {
  21555. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21556. const void * firstRow = remote.nextRow();
  21557. size32_t finalSize = 0;
  21558. if (!firstRow)
  21559. {
  21560. rowBuilder.ensureRow();
  21561. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21562. }
  21563. else
  21564. {
  21565. // NOTE need to clone this because going to modify below, could special case 1 row only
  21566. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21567. ReleaseRoxieRow(firstRow);
  21568. }
  21569. loop
  21570. {
  21571. const void * next = remote.nextRow();
  21572. if (!next)
  21573. break;
  21574. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21575. ReleaseRoxieRow(next);
  21576. }
  21577. return rowBuilder.finalizeRowClear(finalSize);
  21578. }
  21579. virtual const void *nextRow()
  21580. {
  21581. ActivityTimer t(totalCycles, timeActivities);
  21582. if (done) return NULL;
  21583. const void * ret = gatherMerged();
  21584. done = true;
  21585. return ret;
  21586. }
  21587. };
  21588. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21589. {
  21590. public:
  21591. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21592. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21593. {
  21594. }
  21595. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21596. {
  21597. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21598. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21599. // else if (isSimple)
  21600. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21601. else
  21602. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21603. }
  21604. };
  21605. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21606. {
  21607. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21608. }
  21609. //--------------------------------------------------------------------------------------------------------------------------
  21610. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21611. {
  21612. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21613. RowAggregator singleAggregator;
  21614. RowAggregator resultAggregator;
  21615. unsigned groupSegCount;
  21616. bool gathered;
  21617. bool eof;
  21618. public:
  21619. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21620. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  21621. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  21622. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21623. singleAggregator(aggregateHelper, aggregateHelper),
  21624. resultAggregator(aggregateHelper, aggregateHelper),
  21625. gathered(false), eof(true)
  21626. {
  21627. groupSegCount = 0;
  21628. }
  21629. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21630. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21631. {
  21632. eof = false;
  21633. gathered= false;
  21634. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21635. groupSegCount = 0;
  21636. if (!paused)
  21637. processAllKeys();
  21638. resultAggregator.start(rowAllocator);
  21639. }
  21640. virtual bool needsAllocator() const { return true; }
  21641. virtual void reset()
  21642. {
  21643. resultAggregator.reset();
  21644. CRoxieServerIndexActivity::reset();
  21645. }
  21646. virtual void processRow(const void * next)
  21647. {
  21648. singleAggregator.addRow(next);
  21649. }
  21650. virtual void createSegmentMonitors(IKeyManager *key)
  21651. {
  21652. unsigned groupSegSize;
  21653. ThorActivityKind kind = factory->getKind();
  21654. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21655. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  21656. else
  21657. groupSegSize = 0;
  21658. if (groupSegSize)
  21659. {
  21660. key->setMergeBarrier(groupSegSize);
  21661. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21662. unsigned numSegs = tlk->ordinality();
  21663. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  21664. {
  21665. IKeySegmentMonitor *seg = tlk->item(segNo);
  21666. if (seg->getOffset()+seg->getSize()==groupSegSize)
  21667. {
  21668. groupSegCount = segNo+1;
  21669. break;
  21670. }
  21671. }
  21672. assertex(groupSegCount);
  21673. }
  21674. else
  21675. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21676. }
  21677. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21678. {
  21679. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21680. singleAggregator.start(rowAllocator);
  21681. ThorActivityKind kind = factory->getKind();
  21682. while (tlk->lookup(true))
  21683. {
  21684. try
  21685. {
  21686. if (groupSegCount && !trans)
  21687. {
  21688. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  21689. callback.finishedRow();
  21690. if (kind==TAKindexgroupcount)
  21691. {
  21692. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  21693. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  21694. }
  21695. if (!tlk->nextRange(groupSegCount))
  21696. break;
  21697. }
  21698. else
  21699. {
  21700. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  21701. callback.finishedRow();
  21702. }
  21703. }
  21704. catch (IException *E)
  21705. {
  21706. throw makeWrappedException(E);
  21707. }
  21708. accepted++;
  21709. }
  21710. loop
  21711. {
  21712. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  21713. if (!next)
  21714. break;
  21715. size32_t size = next->querySize();
  21716. result->append(next->finalizeRowClear());
  21717. }
  21718. remote.injectResult(result.getClear());
  21719. singleAggregator.reset();
  21720. return false;
  21721. }
  21722. virtual void onLimitExceeded(bool isKeyed)
  21723. {
  21724. if (traceLevel > 4)
  21725. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21726. throwUnexpected();
  21727. }
  21728. virtual const void *createLimitFailRow(bool isKeyed)
  21729. {
  21730. throwUnexpected();
  21731. }
  21732. void gatherMerged()
  21733. {
  21734. gathered = true;
  21735. loop
  21736. {
  21737. const void * next = remote.nextRow();
  21738. if (!next)
  21739. break;
  21740. resultAggregator.mergeElement(next);
  21741. ReleaseRoxieRow(next);
  21742. }
  21743. }
  21744. virtual const void *nextRow()
  21745. {
  21746. ActivityTimer t(totalCycles, timeActivities);
  21747. if (eof)
  21748. return NULL;
  21749. if (!gathered)
  21750. gatherMerged();
  21751. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  21752. if (next)
  21753. {
  21754. processed++;
  21755. return next->finalizeRowClear();
  21756. }
  21757. eof = true;
  21758. return NULL;
  21759. }
  21760. };
  21761. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21762. {
  21763. public:
  21764. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21765. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21766. {
  21767. }
  21768. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21769. {
  21770. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21771. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21772. // else if (isSimple)
  21773. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21774. else
  21775. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  21776. }
  21777. };
  21778. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21779. {
  21780. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21781. }
  21782. //--------------------------------------------------------------------------------------------------------------------------
  21783. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  21784. {
  21785. IHThorCompoundNormalizeExtra & readHelper;
  21786. public:
  21787. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21788. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  21789. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  21790. readHelper((IHThorIndexNormalizeArg &)basehelper)
  21791. {
  21792. }
  21793. virtual bool needsAllocator() const { return true; }
  21794. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21795. {
  21796. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21797. rowLimit = readHelper.getRowLimit();
  21798. keyedLimit = readHelper.getKeyedLimit();
  21799. choosenLimit = readHelper.getChooseNLimit();
  21800. if (!paused)
  21801. processAllKeys();
  21802. }
  21803. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  21804. {
  21805. unsigned keyedCount = 0;
  21806. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21807. while (tlk->lookup(true))
  21808. {
  21809. keyedCount++;
  21810. if (keyedCount > keyedLimit)
  21811. {
  21812. if (traceLevel > 4)
  21813. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21814. onLimitExceeded(true);
  21815. break;
  21816. }
  21817. size32_t transformedSize;
  21818. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  21819. {
  21820. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21821. do
  21822. {
  21823. if (accepted>=choosenLimit)
  21824. break;
  21825. rowBuilder.ensureRow();
  21826. try
  21827. {
  21828. transformedSize = readHelper.transform(rowBuilder);
  21829. }
  21830. catch (IException *E)
  21831. {
  21832. throw makeWrappedException(E);
  21833. }
  21834. if (transformedSize)
  21835. {
  21836. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  21837. result->append(rowBuilder.finalizeRowClear(transformedSize));
  21838. accepted++;
  21839. }
  21840. else
  21841. rejected++;
  21842. } while (readHelper.next());
  21843. remote.injectResult(result.getClear());
  21844. callback.finishedRow();
  21845. if (accepted>=choosenLimit)
  21846. return true;
  21847. }
  21848. }
  21849. return false;
  21850. }
  21851. virtual void onLimitExceeded(bool isKeyed)
  21852. {
  21853. if (traceLevel > 4)
  21854. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21855. if (isKeyed)
  21856. {
  21857. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21858. {
  21859. if (ctx->queryDebugContext())
  21860. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21861. throw makeLimitSkipException(true);
  21862. }
  21863. else
  21864. readHelper.onKeyedLimitExceeded();
  21865. }
  21866. else
  21867. {
  21868. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21869. {
  21870. if (ctx->queryDebugContext())
  21871. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21872. throw makeLimitSkipException(false);
  21873. }
  21874. else
  21875. readHelper.onLimitExceeded();
  21876. }
  21877. }
  21878. virtual const void *createLimitFailRow(bool isKeyed)
  21879. {
  21880. UNIMPLEMENTED;
  21881. }
  21882. };
  21883. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21884. {
  21885. public:
  21886. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21887. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21888. {
  21889. }
  21890. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21891. {
  21892. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21893. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21894. else
  21895. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21896. }
  21897. };
  21898. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21899. {
  21900. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21901. }
  21902. //=================================================================================
  21903. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21904. {
  21905. IHThorFetchBaseArg &helper;
  21906. IHThorFetchContext * fetchContext;
  21907. Linked<IFilePartMap> map;
  21908. CRemoteResultAdaptor remote;
  21909. RecordPullerThread puller;
  21910. bool needsRHS;
  21911. bool variableFileName;
  21912. bool isOpt;
  21913. Owned<const IResolvedFile> varFileInfo;
  21914. public:
  21915. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21916. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21917. {
  21918. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21919. needsRHS = helper.transformNeedsRhs();
  21920. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21921. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21922. }
  21923. virtual const IResolvedFile *queryVarFileInfo() const
  21924. {
  21925. return varFileInfo;
  21926. }
  21927. virtual void onCreate(IHThorArg *_colocalParent)
  21928. {
  21929. CRoxieServerActivity::onCreate(_colocalParent);
  21930. remote.onCreate(_colocalParent);
  21931. }
  21932. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21933. {
  21934. if (idx)
  21935. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  21936. puller.setInput(this, _sourceIdx, _in);
  21937. }
  21938. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  21939. {
  21940. puller.connectInputStreams(ctx, consumerOrdered);
  21941. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  21942. }
  21943. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  21944. {
  21945. if (idx==0)
  21946. return puller.queryInput();
  21947. else
  21948. return NULL;
  21949. }
  21950. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21951. {
  21952. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21953. remote.onStart(parentExtractSize, parentExtract);
  21954. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21955. if (variableFileName)
  21956. {
  21957. OwnedRoxieString fname(fetchContext->getFileName());
  21958. varFileInfo.setown(resolveLFN(fname, isOpt));
  21959. if (varFileInfo)
  21960. map.setown(varFileInfo->getFileMap());
  21961. }
  21962. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21963. }
  21964. virtual void stop()
  21965. {
  21966. // Called from remote, so no need to call back to it....
  21967. puller.stop();
  21968. CRoxieServerActivity::stop();
  21969. }
  21970. virtual void reset()
  21971. {
  21972. processed = remote.processed;
  21973. remote.processed = 0;
  21974. puller.reset();
  21975. if (variableFileName)
  21976. {
  21977. varFileInfo.clear();
  21978. map.clear();
  21979. }
  21980. CRoxieServerActivity::reset();
  21981. }
  21982. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  21983. {
  21984. if (idx==(unsigned)-1)
  21985. idx = 0;
  21986. return idx ? NULL : &remote;
  21987. }
  21988. virtual void processRow(const void *row)
  21989. {
  21990. // called from puller thread
  21991. offset_t rp = fetchContext->extractPosition(row);
  21992. unsigned partNo;
  21993. if (isLocalFpos(rp))
  21994. partNo = getLocalFposPart(rp) + 1;
  21995. else
  21996. partNo = map->mapOffset(rp);
  21997. if (needsRHS)
  21998. {
  21999. Owned<IEngineRowAllocator> extractAllocator = createRowAllocator(helper.queryExtractedSize());
  22000. RtlDynamicRowBuilder rb(extractAllocator, true);
  22001. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22002. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22003. *(offset_t *) block = rp;
  22004. block += sizeof(rp);
  22005. *(unsigned *) block = rhsSize;
  22006. block += sizeof(rhsSize);
  22007. memcpy(block, rb.row(), rhsSize);
  22008. }
  22009. else
  22010. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22011. ReleaseRoxieRow(row);
  22012. }
  22013. void processEOG()
  22014. {
  22015. #ifdef FETCH_PRESERVES_GROUPING
  22016. UNIMPLEMENTED;
  22017. #endif
  22018. // else discard is correct
  22019. }
  22020. void processGroup(const ConstPointerArray &)
  22021. {
  22022. throwUnexpected();
  22023. }
  22024. void processDone()
  22025. {
  22026. // called from puller thread
  22027. remote.flush();
  22028. remote.senddone();
  22029. }
  22030. virtual bool fireException(IException *e)
  22031. {
  22032. return remote.fireException(e);
  22033. }
  22034. virtual void onLimitExceeded(bool isKeyed)
  22035. {
  22036. if (traceLevel > 4)
  22037. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22038. if (isKeyed)
  22039. throwUnexpected();
  22040. helper.onLimitExceeded();
  22041. }
  22042. virtual const void *createLimitFailRow(bool isKeyed)
  22043. {
  22044. UNIMPLEMENTED;
  22045. }
  22046. virtual const void *nextRow()
  22047. {
  22048. throwUnexpected(); // I am nobody's input
  22049. }
  22050. };
  22051. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22052. {
  22053. RemoteActivityId remoteId;
  22054. Owned<IFilePartMap> map;
  22055. bool variableFileName;
  22056. Owned<const IResolvedFile> datafile;
  22057. public:
  22058. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22059. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22060. {
  22061. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22062. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22063. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22064. if (!variableFileName)
  22065. {
  22066. OwnedRoxieString fname(fetchContext->getFileName());
  22067. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22068. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  22069. true, true,
  22070. _queryFactory.queryWorkUnit(), true));
  22071. if (datafile)
  22072. map.setown(datafile->getFileMap());
  22073. }
  22074. }
  22075. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22076. {
  22077. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22078. }
  22079. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22080. {
  22081. if (datafile)
  22082. addXrefFileInfo(reply, datafile);
  22083. else
  22084. {
  22085. // Temporarily resolve the file
  22086. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22087. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  22088. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22089. {
  22090. OwnedRoxieString fileName(fetchContext->getFileName());
  22091. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22092. if (temp)
  22093. addXrefFileInfo(reply, temp);
  22094. }
  22095. }
  22096. }
  22097. virtual const StatisticsMapping &queryStatsMapping() const
  22098. {
  22099. return diskStatistics;
  22100. }
  22101. };
  22102. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22103. {
  22104. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22105. }
  22106. // MORE - is there any point keeping this now?
  22107. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22108. {
  22109. public:
  22110. Owned<const IResolvedFile> indexfile;
  22111. Owned<const IResolvedFile> datafile;
  22112. StringAttr fileName;
  22113. StringAttr indexName;
  22114. Owned<IKeyArray> keySet;
  22115. Owned<IFileIOArray> files;
  22116. TranslatorArray layoutTranslators;
  22117. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22118. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22119. {
  22120. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22121. {
  22122. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22123. return; // ignore 'spills'
  22124. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22125. ThorActivityKind kind = getActivityKind(_graphNode);
  22126. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22127. {
  22128. fileName.set(queryNodeFileName(_graphNode, kind));
  22129. indexName.set(queryNodeIndexName(_graphNode, kind));
  22130. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22131. {
  22132. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22133. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22134. if (indexfile)
  22135. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  22136. }
  22137. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22138. {
  22139. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22140. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22141. if (datafile)
  22142. {
  22143. if (isLocal)
  22144. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22145. }
  22146. }
  22147. }
  22148. }
  22149. catch(IException *E)
  22150. {
  22151. StringBuffer errors;
  22152. E->errorMessage(errors);
  22153. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22154. E->Release();
  22155. }
  22156. }
  22157. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), sanitizeSourceFile(__FILE__), __LINE__); }
  22158. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22159. {
  22160. if (!allFilesDynamic)
  22161. {
  22162. if (datafile)
  22163. addXrefFileInfo(reply, datafile);
  22164. if (indexfile)
  22165. addXrefFileInfo(reply, indexfile);
  22166. }
  22167. else
  22168. {
  22169. Owned<const IResolvedFile> temp;
  22170. if (fileName.length())
  22171. {
  22172. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22173. if (temp)
  22174. addXrefFileInfo(reply, temp);
  22175. }
  22176. if (indexName.length())
  22177. {
  22178. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22179. if (temp)
  22180. addXrefFileInfo(reply, temp);
  22181. }
  22182. }
  22183. }
  22184. };
  22185. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22186. {
  22187. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22188. }
  22189. //=====================================================================================================
  22190. // Keyed joins...
  22191. //
  22192. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22193. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22194. // 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
  22195. // the transform and returns rows that are created.
  22196. // 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)
  22197. //
  22198. //=====================================================================================================
  22199. class CJoinGroup;
  22200. interface IJoinProcessor
  22201. {
  22202. virtual void processEOG() = 0;
  22203. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22204. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22205. virtual bool fireException(IException *E) = 0;
  22206. virtual void processCompletedGroups() = 0;
  22207. };
  22208. //------------------------------------------------------------------------------------------------------
  22209. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22210. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22211. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22212. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22213. // per-query limits etc (Note that the pointer array block is not though).
  22214. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22215. //
  22216. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22217. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22218. // initial count when created.
  22219. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22220. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22221. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22222. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22223. // remaining reference and the JoinGroup will be processed and destroyed.
  22224. //
  22225. //------------------------------------------------------------------------------------------------------
  22226. class CJoinGroup : public CInterface
  22227. {
  22228. protected:
  22229. const void *left; // LHS row
  22230. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22231. atomic_t endMarkersPending; // How many slave responses still waiting for
  22232. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22233. unsigned lastPartNo;
  22234. unsigned pos;
  22235. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22236. public:
  22237. #undef new
  22238. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22239. {
  22240. return a->allocate(size, activityId);
  22241. }
  22242. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22243. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22244. #endif
  22245. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22246. {
  22247. ReleaseRoxieRow(ptr);
  22248. }
  22249. void operator delete(void *ptr)
  22250. {
  22251. ReleaseRoxieRow(ptr);
  22252. }
  22253. public:
  22254. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22255. {
  22256. #ifdef TRACE_JOINGROUPS
  22257. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22258. #endif
  22259. candidates = 0;
  22260. lastPartNo = 0;
  22261. pos = 0;
  22262. left = _left;
  22263. groupStart = _groupStart;
  22264. if (_groupStart)
  22265. {
  22266. atomic_inc(&_groupStart->endMarkersPending);
  22267. }
  22268. atomic_set(&endMarkersPending, 1);
  22269. }
  22270. ~CJoinGroup()
  22271. {
  22272. #ifdef TRACE_JOINGROUPS
  22273. DBGLOG("Destroying joinGroup %p", this);
  22274. #endif
  22275. if (left)
  22276. {
  22277. ReleaseRoxieRow(left);
  22278. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22279. rows.kill();
  22280. }
  22281. }
  22282. inline bool isHeadRecord() const
  22283. {
  22284. return left==NULL;
  22285. }
  22286. inline bool complete() const
  22287. {
  22288. return atomic_read(&endMarkersPending) == 0;
  22289. }
  22290. #ifdef TRACE_JOINGROUPS
  22291. inline void notePending(unsigned lineNo)
  22292. #else
  22293. inline void notePending()
  22294. #endif
  22295. {
  22296. assert(!complete());
  22297. atomic_inc(&endMarkersPending);
  22298. #ifdef TRACE_JOINGROUPS
  22299. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22300. #endif
  22301. }
  22302. inline bool inGroup(CJoinGroup *leader) const
  22303. {
  22304. return groupStart==leader;
  22305. }
  22306. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22307. {
  22308. // Single threaded by now
  22309. assert(complete());
  22310. return rows.item(idx);
  22311. }
  22312. #ifdef TRACE_JOINGROUPS
  22313. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22314. #else
  22315. bool noteEndReceived(unsigned candidateCount)
  22316. #endif
  22317. {
  22318. assert(!complete());
  22319. if (candidateCount)
  22320. {
  22321. candidates += candidateCount;
  22322. }
  22323. #ifdef TRACE_JOINGROUPS
  22324. 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);
  22325. #endif
  22326. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22327. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22328. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22329. CJoinGroup *localGroupStart = groupStart;
  22330. if (atomic_dec_and_test(&endMarkersPending))
  22331. {
  22332. if (localGroupStart)
  22333. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22334. else
  22335. return true;
  22336. }
  22337. else
  22338. return false;
  22339. }
  22340. inline const void *queryLeft() const
  22341. {
  22342. return left;
  22343. }
  22344. void addRightMatch(KeyedJoinHeader *right)
  22345. {
  22346. assert(!complete());
  22347. unsigned short partNo = right->partNo;
  22348. if (partNo != lastPartNo)
  22349. {
  22350. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22351. if (partNo > lastPartNo)
  22352. pos = rows.length();
  22353. while (pos>0)
  22354. {
  22355. if (rows.item(pos-1)->partNo <= partNo)
  22356. break;
  22357. pos--;
  22358. }
  22359. lastPartNo = partNo;
  22360. }
  22361. rows.add(right, pos);
  22362. pos++;
  22363. }
  22364. inline unsigned rowsSeen() const
  22365. {
  22366. assert(complete());
  22367. return rows.length();
  22368. }
  22369. inline unsigned candidateCount() const
  22370. {
  22371. assert(complete());
  22372. return candidates;
  22373. }
  22374. };
  22375. #ifdef TRACE_JOINGROUPS
  22376. #define notePending() notePending(__LINE__)
  22377. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22378. #endif
  22379. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22380. {
  22381. private:
  22382. SafeQueueOf<const void, true> ready;
  22383. public:
  22384. IHThorKeyedJoinArg &helper;
  22385. unsigned joinProcessed;
  22386. bool isFullKey;
  22387. bool eof;
  22388. bool isSimple;
  22389. bool allPulled;
  22390. ActivityTimeAccumulator totalCycles;
  22391. unsigned activityId;
  22392. RecordPullerThread &puller;
  22393. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22394. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22395. IJoinProcessor &processor;
  22396. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22397. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22398. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22399. : helper(_helper),
  22400. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22401. isFullKey(_isFullKey),
  22402. isSimple(_isSimple),
  22403. puller(_puller),
  22404. processor(_processor),
  22405. activityId(_activity.queryId())
  22406. {
  22407. joinProcessed = 0;
  22408. allPulled = false;
  22409. eof = false;
  22410. }
  22411. virtual void onCreate(IHThorArg *_colocalArg)
  22412. {
  22413. CRemoteResultAdaptor::onCreate(_colocalArg);
  22414. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22415. }
  22416. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22417. {
  22418. eof = false;
  22419. joinProcessed = 0;
  22420. totalCycles.totalCycles = 0;
  22421. allPulled = false;
  22422. assertex(ready.ordinality()==0);
  22423. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22424. }
  22425. virtual void reset()
  22426. {
  22427. CRemoteResultAdaptor::reset();
  22428. while (ready.ordinality())
  22429. {
  22430. const void *goer = ready.dequeue();
  22431. if (goer)
  22432. ReleaseRoxieRow(goer);
  22433. }
  22434. while (injected.ordinality())
  22435. {
  22436. const void *goer = injected.dequeue();
  22437. if (goer)
  22438. ReleaseRoxieRow(goer);
  22439. }
  22440. }
  22441. inline void addResult(const void *row)
  22442. {
  22443. ready.enqueue(row);
  22444. }
  22445. virtual unsigned __int64 queryTotalCycles() const
  22446. {
  22447. return totalCycles.totalCycles;
  22448. }
  22449. virtual const void *nextRow()
  22450. {
  22451. ActivityTimer t(totalCycles, timeActivities);
  22452. loop
  22453. {
  22454. if (eof)
  22455. return NULL;
  22456. processSlaveResults();
  22457. if (ready.ordinality())
  22458. {
  22459. const void *result = ready.dequeue();
  22460. if (result)
  22461. joinProcessed++;
  22462. return result;
  22463. }
  22464. else
  22465. eof = true;
  22466. }
  22467. }
  22468. private:
  22469. void processSlaveResults()
  22470. {
  22471. while (!ready.ordinality())
  22472. {
  22473. KeyedJoinHeader *fetchedData;
  22474. if (isSimple)
  22475. {
  22476. while (!allPulled && !injected.ordinality())
  22477. {
  22478. if (!puller.pullRecords(1))
  22479. {
  22480. puller.done();
  22481. allPulled = true;
  22482. }
  22483. }
  22484. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22485. }
  22486. else
  22487. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22488. if (fetchedData)
  22489. {
  22490. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22491. if (fetchedData->partNo == (unsigned short) -1)
  22492. {
  22493. #ifdef TRACE_JOINGROUPS
  22494. CTXLOG("Got end for group %p", thisGroup);
  22495. #endif
  22496. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22497. ReleaseRoxieRow(fetchedData);
  22498. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22499. }
  22500. else
  22501. {
  22502. #ifdef TRACE_JOINGROUPS
  22503. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22504. #endif
  22505. thisGroup->addRightMatch(fetchedData);
  22506. if (isFullKey)
  22507. {
  22508. #ifdef TRACE_JOINGROUPS
  22509. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22510. #endif
  22511. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22512. }
  22513. }
  22514. }
  22515. else
  22516. break;
  22517. }
  22518. }
  22519. };
  22520. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22521. {
  22522. IHThorKeyedJoinArg &helper;
  22523. Owned<IKeyManager> tlk;
  22524. Linked<IKeyArray> keySet;
  22525. Linked<TranslatorArray> translators;
  22526. CRemoteResultAdaptor remote;
  22527. RecordPullerThread puller;
  22528. IOutputMetaData *indexReadMeta;
  22529. IJoinProcessor *joinHandler;
  22530. bool variableIndexFileName;
  22531. bool indexReadInputRecordVariable;
  22532. bool isLocal;
  22533. Owned<IEngineRowAllocator> indexReadAllocator;
  22534. Owned<const IResolvedFile> varFileInfo;
  22535. IFinalRoxieInput *indexReadInput;
  22536. unsigned indexReadIdx = 0;
  22537. IIndexReadActivityInfo *rootIndex;
  22538. public:
  22539. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22540. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22541. helper((IHThorKeyedJoinArg &)basehelper),
  22542. tlk(createKeyManager(NULL, 0, this)),
  22543. translators(_translators),
  22544. keySet(_keySet),
  22545. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22546. indexReadMeta(_indexReadMeta),
  22547. joinHandler(_joinHandler),
  22548. puller(false),
  22549. isLocal(_isLocal)
  22550. {
  22551. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22552. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22553. indexReadInput = NULL;
  22554. rootIndex = NULL;
  22555. }
  22556. virtual const IResolvedFile *queryVarFileInfo() const
  22557. {
  22558. return varFileInfo;
  22559. }
  22560. virtual void onCreate(IHThorArg *_colocalParent)
  22561. {
  22562. CRoxieServerActivity::onCreate(_colocalParent);
  22563. remote.onCreate(_colocalParent);
  22564. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22565. }
  22566. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22567. {
  22568. if (!idx)
  22569. puller.setInput(this, _sourceIdx, _in);
  22570. else if (idx==1)
  22571. {
  22572. indexReadInput = _in;
  22573. indexReadIdx = _sourceIdx;
  22574. }
  22575. else
  22576. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22577. }
  22578. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22579. {
  22580. puller.connectInputStreams(ctx, consumerOrdered);
  22581. //No rows are read from indexReadInput, so no need to extract the streams
  22582. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22583. }
  22584. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22585. {
  22586. switch (idx)
  22587. {
  22588. case 0:
  22589. return puller.queryInput();
  22590. case 1:
  22591. return indexReadInput;
  22592. default:
  22593. return NULL;
  22594. }
  22595. }
  22596. virtual void serializeExtra(MemoryBuffer &out)
  22597. {
  22598. if (helper.getJoinFlags() & JFindexfromactivity)
  22599. {
  22600. assertex(rootIndex);
  22601. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22602. indexId.serialize(out);
  22603. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22604. MemoryBuffer tmp;
  22605. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22606. if (rootIndex->queryActivity()->queryVarFileInfo())
  22607. {
  22608. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22609. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22610. }
  22611. unsigned ctxlen = tmp.length();
  22612. out.append(ctxlen).append(tmp);
  22613. }
  22614. }
  22615. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22616. {
  22617. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22618. if (indexReadInput)
  22619. {
  22620. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22621. rootIndex = indexReadInput->queryIndexReadActivity();
  22622. if (!rootIndex)
  22623. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22624. }
  22625. remote.onStart(parentExtractSize, parentExtract);
  22626. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22627. if (rootIndex)
  22628. {
  22629. varFileInfo.setown(rootIndex->getVarFileInfo());
  22630. translators.setown(rootIndex->getTranslators());
  22631. keySet.setown(rootIndex->getKeySet());
  22632. }
  22633. else if (variableIndexFileName)
  22634. {
  22635. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22636. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22637. if (varFileInfo)
  22638. {
  22639. translators.setown(new TranslatorArray);
  22640. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  22641. }
  22642. }
  22643. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22644. }
  22645. virtual void stop()
  22646. {
  22647. puller.stop();
  22648. CRoxieServerActivity::stop();
  22649. }
  22650. virtual void reset()
  22651. {
  22652. CRoxieServerActivity::reset();
  22653. puller.reset();
  22654. if (varFileInfo)
  22655. {
  22656. keySet.clear();
  22657. varFileInfo.clear();
  22658. }
  22659. }
  22660. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22661. {
  22662. if (idx==(unsigned)-1)
  22663. idx = 0;
  22664. return idx ? NULL : &remote;
  22665. }
  22666. virtual void processRow(const void *row)
  22667. {
  22668. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22669. // called from front puller thread
  22670. // buffer up an IndexRead request
  22671. if (helper.leftCanMatch(row))
  22672. {
  22673. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  22674. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  22675. OwnedConstRoxieRow extracted;
  22676. if (indexReadSize)
  22677. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  22678. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  22679. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22680. {
  22681. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22682. if (thisBase)
  22683. {
  22684. unsigned fileNo = 0;
  22685. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22686. try
  22687. {
  22688. tlk->setKey(thisKey);
  22689. tlk->setLayoutTranslator(translators->item(fileNo));
  22690. helper.createSegmentMonitors(tlk, extracted);
  22691. if (rootIndex)
  22692. rootIndex->mergeSegmentMonitors(tlk);
  22693. tlk->finishSegmentMonitors();
  22694. tlk->reset();
  22695. loop
  22696. {
  22697. typedef const void * cvp;
  22698. if (thisKey->isTopLevelKey())
  22699. {
  22700. bool locallySorted = !thisKey->isFullySorted();
  22701. while (locallySorted || tlk->lookup(false))
  22702. {
  22703. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22704. if (locallySorted || slavePart)
  22705. {
  22706. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22707. *outputBuffer++ = jg;
  22708. if (indexReadInputRecordVariable)
  22709. {
  22710. *(unsigned *) outputBuffer = indexReadSize;
  22711. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  22712. }
  22713. jg->notePending();
  22714. memcpy(outputBuffer, extracted, indexReadSize);
  22715. if (locallySorted)
  22716. {
  22717. for (unsigned i = 1; i < numChannels; i++)
  22718. jg->notePending();
  22719. break;
  22720. }
  22721. }
  22722. }
  22723. }
  22724. else
  22725. {
  22726. // MORE - this code seems to be duplicated in half keyed
  22727. unsigned accepted = 0;
  22728. unsigned rejected = 0;
  22729. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  22730. jg->notePending();
  22731. unsigned candidateCount = 0;
  22732. while (tlk->lookup(true))
  22733. {
  22734. candidateCount++;
  22735. atomic_inc(&indexRecordsRead);
  22736. KLBlobProviderAdapter adapter(tlk);
  22737. offset_t recptr;
  22738. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22739. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22740. {
  22741. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22742. rhs->fpos = recptr;
  22743. rhs->thisGroup = jg;
  22744. rhs->partNo = partNo;
  22745. result->append(rhs);
  22746. }
  22747. else
  22748. {
  22749. rejected++;
  22750. atomic_inc(&postFiltered);
  22751. }
  22752. }
  22753. // output an end marker for the matches to this group
  22754. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22755. endMarker->fpos = (offset_t) candidateCount;
  22756. endMarker->thisGroup = jg;
  22757. endMarker->partNo = (unsigned short) -1;
  22758. result->append(endMarker);
  22759. remote.injectResult(result.getClear());
  22760. if (accepted)
  22761. noteStatistic(StNumIndexAccepted, accepted);
  22762. if (rejected)
  22763. noteStatistic(StNumIndexRejected, rejected);
  22764. }
  22765. if (++fileNo < thisBase->numParts())
  22766. {
  22767. thisKey = thisBase->queryPart(fileNo);
  22768. tlk->setKey(thisKey);
  22769. tlk->setLayoutTranslator(translators->item(fileNo));
  22770. tlk->reset();
  22771. }
  22772. else
  22773. break;
  22774. }
  22775. tlk->releaseSegmentMonitors();
  22776. tlk->setKey(NULL);
  22777. }
  22778. catch (...)
  22779. {
  22780. tlk->releaseSegmentMonitors();
  22781. tlk->setKey(NULL);
  22782. throw;
  22783. }
  22784. }
  22785. }
  22786. joinHandler->noteEndReceived(jg, 0);
  22787. }
  22788. else
  22789. {
  22790. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  22791. }
  22792. }
  22793. void processGroup(const ConstPointerArray &)
  22794. {
  22795. throwUnexpected();
  22796. }
  22797. virtual void processEOG()
  22798. {
  22799. joinHandler->processEOG();
  22800. }
  22801. virtual void processDone()
  22802. {
  22803. // called from puller thread
  22804. remote.flush();
  22805. remote.senddone();
  22806. }
  22807. virtual void onLimitExceeded(bool isKeyed)
  22808. {
  22809. if (traceLevel > 4)
  22810. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22811. if (isKeyed)
  22812. throwUnexpected();
  22813. helper.onLimitExceeded();
  22814. }
  22815. virtual const void *createLimitFailRow(bool isKeyed)
  22816. {
  22817. throwUnexpected();
  22818. }
  22819. virtual bool fireException(IException *e)
  22820. {
  22821. // called from puller thread on failure
  22822. remote.fireException(LINK(e));
  22823. return joinHandler->fireException(e);
  22824. }
  22825. virtual const void *nextRow()
  22826. {
  22827. throwUnexpected(); // I am nobody's input
  22828. }
  22829. };
  22830. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  22831. {
  22832. protected:
  22833. IHThorKeyedJoinArg &helper;
  22834. KeyedJoinRemoteAdaptor remote;
  22835. RecordPullerThread puller;
  22836. OwnedConstRoxieRow defaultRight;
  22837. Owned<IEngineRowAllocator> defaultRightAllocator;
  22838. unsigned joinFlags;
  22839. unsigned atMost;
  22840. unsigned atmostsTriggered;
  22841. unsigned abortLimit;
  22842. unsigned keepLimit;
  22843. bool limitFail;
  22844. bool limitOnFail;
  22845. bool preserveGroups;
  22846. bool cloneLeft;
  22847. bool isSimple;
  22848. bool isLocal;
  22849. ThorActivityKind activityKind;
  22850. CJoinGroup *groupStart;
  22851. CriticalSection groupsCrit;
  22852. QueueOf<CJoinGroup, false> groups;
  22853. IFinalRoxieInput *indexReadInput;
  22854. unsigned indexReadIdx = 0;
  22855. Owned<IStrandJunction> indexReadJunction;
  22856. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  22857. IIndexReadActivityInfo *rootIndex;
  22858. void createDefaultRight()
  22859. {
  22860. if (!defaultRight)
  22861. {
  22862. if (!defaultRightAllocator)
  22863. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22864. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  22865. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  22866. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  22867. }
  22868. }
  22869. public:
  22870. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  22871. , bool isFull, bool _isSimple, bool _isLocal)
  22872. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22873. helper((IHThorKeyedJoinArg &)basehelper),
  22874. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  22875. joinFlags(_joinFlags),
  22876. preserveGroups(meta.isGrouped()),
  22877. puller(false),
  22878. isSimple(_isSimple),
  22879. isLocal(_isLocal),
  22880. abortLimit(0),
  22881. keepLimit(0),
  22882. atMost(0),
  22883. limitFail(false),
  22884. limitOnFail(false),
  22885. cloneLeft(false)
  22886. {
  22887. groupStart = NULL;
  22888. activityKind = _factory->getKind();
  22889. indexReadInput = NULL;
  22890. rootIndex = NULL;
  22891. atmostsTriggered = 0;
  22892. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22893. }
  22894. virtual void onCreate(IHThorArg *_colocalParent)
  22895. {
  22896. CRoxieServerActivity::onCreate(_colocalParent);
  22897. remote.onCreate(_colocalParent);
  22898. }
  22899. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22900. {
  22901. if (!idx)
  22902. puller.setInput(this, _sourceIdx, _in);
  22903. else if (idx==1)
  22904. {
  22905. indexReadInput = _in;
  22906. indexReadIdx = _sourceIdx;
  22907. }
  22908. else
  22909. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22910. }
  22911. virtual void connectInputStreams(bool consumerOrdered)
  22912. {
  22913. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  22914. puller.connectInputStreams(ctx, consumerOrdered);
  22915. if (indexReadInput)
  22916. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  22917. }
  22918. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22919. {
  22920. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22921. if (indexReadInput)
  22922. {
  22923. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22924. rootIndex = indexReadInput->queryIndexReadActivity();
  22925. if (!rootIndex)
  22926. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22927. }
  22928. remote.onStart(parentExtractSize, parentExtract);
  22929. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22930. atmostsTriggered = 0;
  22931. atMost = helper.getJoinLimit();
  22932. if (atMost == 0) atMost = (unsigned)-1;
  22933. abortLimit = helper.getMatchAbortLimit();
  22934. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22935. keepLimit = helper.getKeepLimit();
  22936. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22937. getLimitType(joinFlags, limitFail, limitOnFail);
  22938. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22939. if (joinFlags & JFleftouter || limitOnFail)
  22940. createDefaultRight();
  22941. }
  22942. virtual void stop()
  22943. {
  22944. puller.stop();
  22945. if (indexReadStream)
  22946. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  22947. CRoxieServerActivity::stop();
  22948. }
  22949. virtual unsigned __int64 queryLocalCycles() const
  22950. {
  22951. __int64 localCycles = remote.totalCycles.totalCycles;
  22952. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22953. if (localCycles < 0)
  22954. localCycles = 0;
  22955. return localCycles;
  22956. }
  22957. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22958. {
  22959. if (idx==0)
  22960. return puller.queryInput();
  22961. else if (idx==1)
  22962. return indexReadInput;
  22963. else
  22964. return NULL;
  22965. }
  22966. virtual void reset()
  22967. {
  22968. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22969. remote.totalCycles.totalCycles = 0;
  22970. processed = remote.joinProcessed;
  22971. remote.joinProcessed = 0;
  22972. defaultRight.clear();
  22973. if (indexReadInput)
  22974. indexReadInput->reset();
  22975. if (atmostsTriggered)
  22976. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22977. CRoxieServerActivity::reset();
  22978. puller.reset();
  22979. while (groups.ordinality())
  22980. {
  22981. ::Release(groups.dequeue());
  22982. }
  22983. }
  22984. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22985. {
  22986. if (idx==(unsigned)-1)
  22987. idx = 0;
  22988. return idx ? NULL : &remote;
  22989. }
  22990. #undef new
  22991. virtual CJoinGroup *createJoinGroup(const void *row)
  22992. {
  22993. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22994. CriticalBlock c(groupsCrit);
  22995. if (preserveGroups && !groupStart)
  22996. {
  22997. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22998. groups.enqueue(groupStart);
  22999. }
  23000. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23001. groups.enqueue(jg);
  23002. return jg;
  23003. }
  23004. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  23005. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  23006. #endif
  23007. void endGroup()
  23008. {
  23009. CriticalBlock c(groupsCrit);
  23010. if (groupStart)
  23011. noteEndReceived(groupStart, 0);
  23012. groupStart = NULL;
  23013. }
  23014. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23015. {
  23016. if (jg->noteEndReceived(candidateCount))
  23017. processCompletedGroups();
  23018. }
  23019. void processCompletedGroups()
  23020. {
  23021. CriticalBlock c(groupsCrit);
  23022. while (groups.ordinality())
  23023. {
  23024. if (!groups.head()->complete())
  23025. break;
  23026. Owned<CJoinGroup> head = groups.dequeue();
  23027. if (preserveGroups)
  23028. {
  23029. assert(head->isHeadRecord());
  23030. assert(groups.head()->inGroup(head));
  23031. unsigned joinGroupSize = 0;
  23032. while (groups.ordinality() && groups.head()->inGroup(head))
  23033. {
  23034. Owned<CJoinGroup> finger = groups.dequeue();
  23035. joinGroupSize += doJoinGroup(finger);
  23036. }
  23037. if (joinGroupSize)
  23038. remote.addResult(NULL);
  23039. }
  23040. else
  23041. doJoinGroup(head);
  23042. }
  23043. }
  23044. void failLimit(const void * left)
  23045. {
  23046. helper.onMatchAbortLimitExceeded();
  23047. CommonXmlWriter xmlwrite(0);
  23048. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23049. {
  23050. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23051. }
  23052. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23053. }
  23054. virtual bool needsAllocator() const { return true; }
  23055. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23056. {
  23057. if (cloneLeft && !except)
  23058. {
  23059. LinkRoxieRow(left);
  23060. remote.addResult((void *) left);
  23061. return 1;
  23062. }
  23063. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23064. unsigned outSize;
  23065. try
  23066. {
  23067. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23068. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  23069. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23070. }
  23071. catch (IException *E)
  23072. {
  23073. throw makeWrappedException(E);
  23074. }
  23075. if (outSize)
  23076. {
  23077. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23078. remote.addResult(shrunk);
  23079. return 1;
  23080. }
  23081. else
  23082. return 0;
  23083. }
  23084. unsigned doJoinGroup(CJoinGroup *jg)
  23085. {
  23086. unsigned matched = jg->rowsSeen();
  23087. unsigned added = 0;
  23088. const void *left = jg->queryLeft();
  23089. if (jg->candidateCount() > abortLimit)
  23090. {
  23091. if (limitFail)
  23092. failLimit(left);
  23093. if (ctx->queryDebugContext())
  23094. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23095. if (limitOnFail)
  23096. {
  23097. Owned<IException> except;
  23098. try
  23099. {
  23100. failLimit(left);
  23101. }
  23102. catch(IException * e)
  23103. {
  23104. except.setown(e);
  23105. }
  23106. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23107. }
  23108. }
  23109. else if (!matched || jg->candidateCount() > atMost)
  23110. {
  23111. if (jg->candidateCount() > atMost)
  23112. atmostsTriggered++;
  23113. switch (joinFlags & JFtypemask)
  23114. {
  23115. case JFleftouter:
  23116. case JFleftonly:
  23117. switch (activityKind)
  23118. {
  23119. case TAKkeyedjoin:
  23120. case TAKkeyeddenormalizegroup:
  23121. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23122. break;
  23123. case TAKkeyeddenormalize:
  23124. LinkRoxieRow(left);
  23125. remote.addResult((void *) left);
  23126. added++;
  23127. break;
  23128. }
  23129. break;
  23130. }
  23131. }
  23132. else if (!(joinFlags & JFexclude))
  23133. {
  23134. unsigned idx = 0;
  23135. switch (activityKind)
  23136. {
  23137. case TAKkeyedjoin:
  23138. while (idx < matched)
  23139. {
  23140. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23141. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  23142. if (added==keepLimit)
  23143. break;
  23144. idx++;
  23145. }
  23146. break;
  23147. case TAKkeyeddenormalize:
  23148. {
  23149. OwnedConstRoxieRow newLeft;
  23150. newLeft.set(left);
  23151. unsigned rowSize = 0;
  23152. unsigned rightAdded = 0;
  23153. while (idx < matched)
  23154. {
  23155. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23156. try
  23157. {
  23158. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23159. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23160. if (transformedSize)
  23161. {
  23162. rowSize = transformedSize;
  23163. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23164. rightAdded++;
  23165. if (rightAdded==keepLimit)
  23166. break;
  23167. }
  23168. idx++;
  23169. }
  23170. catch (IException *E)
  23171. {
  23172. throw makeWrappedException(E);
  23173. }
  23174. }
  23175. if (rowSize)
  23176. {
  23177. remote.addResult(newLeft.getClear());
  23178. added++;
  23179. }
  23180. }
  23181. break;
  23182. case TAKkeyeddenormalizegroup:
  23183. {
  23184. ConstPointerArray extractedRows;
  23185. while (idx < matched && idx < keepLimit)
  23186. {
  23187. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23188. extractedRows.append((void *) &rhs->rhsdata);
  23189. idx++;
  23190. }
  23191. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23192. }
  23193. break;
  23194. }
  23195. }
  23196. return added;
  23197. }
  23198. virtual void processDone()
  23199. {
  23200. // called from puller thread
  23201. remote.flush();
  23202. remote.senddone();
  23203. }
  23204. virtual void onLimitExceeded(bool isKeyed)
  23205. {
  23206. if (traceLevel > 4)
  23207. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23208. if (isKeyed)
  23209. throwUnexpected();
  23210. helper.onLimitExceeded();
  23211. }
  23212. virtual const void *createLimitFailRow(bool isKeyed)
  23213. {
  23214. throwUnexpected();
  23215. }
  23216. virtual bool fireException(IException *e)
  23217. {
  23218. // called from puller thread on failure
  23219. return remote.fireException(e);
  23220. }
  23221. virtual const void *nextRow()
  23222. {
  23223. throwUnexpected(); // I am nobody's input
  23224. }
  23225. };
  23226. #ifdef _MSC_VER
  23227. #pragma warning ( push )
  23228. #pragma warning ( disable: 4355 )
  23229. #endif
  23230. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23231. {
  23232. CRoxieServerFullKeyedJoinHead head;
  23233. Owned<IEngineRowAllocator> fetchInputAllocator;
  23234. Linked<IFilePartMap> map;
  23235. bool variableFetchFileName;
  23236. Owned<const IResolvedFile> varFetchFileInfo;
  23237. CachedOutputMetaData fetchInputFields;
  23238. public:
  23239. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  23240. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23241. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23242. head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  23243. map(_map)
  23244. {
  23245. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23246. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23247. }
  23248. virtual const IResolvedFile *queryVarFileInfo() const
  23249. {
  23250. return varFetchFileInfo;
  23251. }
  23252. virtual void onCreate(IHThorArg *_colocalParent)
  23253. {
  23254. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23255. head.onCreate(_colocalParent);
  23256. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23257. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23258. }
  23259. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23260. {
  23261. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23262. if (variableFetchFileName)
  23263. {
  23264. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23265. OwnedRoxieString fname(helper.getFileName());
  23266. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  23267. if (varFetchFileInfo)
  23268. map.setown(varFetchFileInfo->getFileMap());
  23269. }
  23270. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23271. }
  23272. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23273. {
  23274. head.setInput(idx, _sourceIdx, _in);
  23275. }
  23276. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23277. {
  23278. connectInputStreams(consumerOrdered);
  23279. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23280. }
  23281. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23282. {
  23283. return head.queryInput(idx);
  23284. }
  23285. virtual void processRow(const void *_rhs)
  23286. {
  23287. // called from puller thread
  23288. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23289. CJoinGroup *jg = rhs->thisGroup;
  23290. if (rhs->partNo != (unsigned short) -1)
  23291. {
  23292. unsigned partNo = map->mapOffset(rhs->fpos);
  23293. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23294. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23295. if (fetchInputFields.isVariableSize())
  23296. {
  23297. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23298. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23299. ReleaseRoxieRow(rhs);
  23300. jg->notePending();
  23301. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23302. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23303. }
  23304. else
  23305. {
  23306. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23307. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23308. ReleaseRoxieRow(rhs);
  23309. jg->notePending();
  23310. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23311. }
  23312. }
  23313. else
  23314. {
  23315. unsigned candidateCount = (unsigned) rhs->fpos;
  23316. // CTXLOG("Full keyed join - all results back from index");
  23317. ReleaseRoxieRow(rhs);
  23318. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23319. }
  23320. }
  23321. virtual void processEOG()
  23322. {
  23323. // called from front puller thread
  23324. if (preserveGroups)
  23325. endGroup();
  23326. }
  23327. void processGroup(const ConstPointerArray &)
  23328. {
  23329. throwUnexpected();
  23330. }
  23331. };
  23332. #ifdef _MSC_VER
  23333. #pragma warning ( pop )
  23334. #endif
  23335. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23336. {
  23337. IOutputMetaData *indexReadMeta;
  23338. Owned<IEngineRowAllocator> indexReadAllocator;
  23339. Owned<IKeyManager> tlk;
  23340. bool variableIndexFileName;
  23341. bool indexReadInputRecordVariable;
  23342. Owned<const IResolvedFile> varFileInfo;
  23343. Linked<TranslatorArray> translators;
  23344. Linked<IKeyArray> keySet;
  23345. Owned<IOutputMetaData> joinPrefixedMeta;
  23346. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23347. public:
  23348. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  23349. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23350. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23351. indexReadMeta(_indexReadMeta),
  23352. tlk(createKeyManager(NULL, 0, this)),
  23353. keySet(_keySet),
  23354. translators(_translators)
  23355. {
  23356. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23357. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23358. }
  23359. virtual void serializeExtra(MemoryBuffer &out)
  23360. {
  23361. if (helper.getJoinFlags() & JFindexfromactivity)
  23362. {
  23363. assertex(rootIndex);
  23364. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23365. indexId.serialize(out);
  23366. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23367. MemoryBuffer tmp;
  23368. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23369. if (rootIndex->queryActivity()->queryVarFileInfo())
  23370. {
  23371. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23372. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23373. }
  23374. unsigned ctxlen = tmp.length();
  23375. out.append(ctxlen).append(tmp);
  23376. }
  23377. }
  23378. virtual void onCreate(IHThorArg *_colocalParent)
  23379. {
  23380. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23381. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23382. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23383. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23384. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23385. }
  23386. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23387. {
  23388. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23389. if (rootIndex)
  23390. {
  23391. varFileInfo.setown(rootIndex->getVarFileInfo());
  23392. translators.setown(rootIndex->getTranslators());
  23393. keySet.setown(rootIndex->getKeySet());
  23394. }
  23395. else if (variableIndexFileName)
  23396. {
  23397. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23398. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23399. if (varFileInfo)
  23400. {
  23401. translators.setown(new TranslatorArray);
  23402. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  23403. }
  23404. }
  23405. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23406. }
  23407. virtual const IResolvedFile *queryVarFileInfo() const
  23408. {
  23409. return varFileInfo;
  23410. }
  23411. virtual void reset()
  23412. {
  23413. CRoxieServerKeyedJoinBase::reset();
  23414. if (varFileInfo)
  23415. {
  23416. keySet.clear();
  23417. varFileInfo.clear();
  23418. }
  23419. }
  23420. virtual void processRow(const void *row)
  23421. {
  23422. // called from front puller thread
  23423. // buffer up an IndexRead request
  23424. if (helper.leftCanMatch(row) && keySet)
  23425. {
  23426. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23427. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23428. OwnedConstRoxieRow extracted;
  23429. if (indexReadRecordSize)
  23430. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23431. CJoinGroup *jg = createJoinGroup(row);
  23432. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23433. {
  23434. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23435. if (thisBase)
  23436. {
  23437. unsigned fileNo = 0;
  23438. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23439. tlk->setKey(thisKey);
  23440. tlk->setLayoutTranslator(translators->item(fileNo));
  23441. helper.createSegmentMonitors(tlk, extracted);
  23442. if (rootIndex)
  23443. rootIndex->mergeSegmentMonitors(tlk);
  23444. tlk->finishSegmentMonitors();
  23445. try
  23446. {
  23447. tlk->reset();
  23448. loop
  23449. {
  23450. typedef const void * cvp;
  23451. if (thisKey && thisKey->isTopLevelKey())
  23452. {
  23453. bool locallySorted = (!thisKey->isFullySorted());
  23454. while (locallySorted || tlk->lookup(false))
  23455. {
  23456. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  23457. if (locallySorted || slavePart)
  23458. {
  23459. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23460. *outputBuffer++ = jg;
  23461. if (indexReadInputRecordVariable)
  23462. {
  23463. *(unsigned *) outputBuffer = indexReadRecordSize;
  23464. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23465. }
  23466. jg->notePending();
  23467. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23468. if (locallySorted)
  23469. {
  23470. for (unsigned i = 1; i < numChannels; i++)
  23471. jg->notePending();
  23472. break;
  23473. }
  23474. }
  23475. }
  23476. }
  23477. else
  23478. {
  23479. unsigned accepted = 0;
  23480. unsigned rejected = 0;
  23481. Owned<CRowArrayMessageResult> result;
  23482. if (!isSimple)
  23483. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23484. // MORE - This code seems to be duplicated in keyedJoinHead
  23485. jg->notePending();
  23486. unsigned candidateCount = 0;
  23487. while (tlk->lookup(true))
  23488. {
  23489. candidateCount++;
  23490. atomic_inc(&indexRecordsRead);
  23491. KLBlobProviderAdapter adapter(tlk);
  23492. offset_t recptr;
  23493. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  23494. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  23495. {
  23496. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23497. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23498. accepted++;
  23499. KLBlobProviderAdapter adapter(tlk);
  23500. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  23501. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23502. rec->fpos = recptr;
  23503. rec->thisGroup = jg;
  23504. rec->partNo = partNo;
  23505. if (isSimple)
  23506. remote.injected.enqueue(rec);
  23507. else
  23508. result->append(rec);
  23509. }
  23510. else
  23511. {
  23512. rejected++;
  23513. atomic_inc(&postFiltered);
  23514. }
  23515. }
  23516. // output an end marker for the matches to this group
  23517. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23518. rec->fpos = (offset_t) candidateCount;
  23519. rec->thisGroup = jg;
  23520. rec->partNo = (unsigned short) -1;
  23521. if (isSimple)
  23522. remote.injected.enqueue(rec);
  23523. else
  23524. {
  23525. result->append(rec);
  23526. remote.injectResult(result.getClear());
  23527. }
  23528. if (accepted)
  23529. noteStatistic(StNumIndexAccepted, accepted);
  23530. if (rejected)
  23531. noteStatistic(StNumIndexRejected, rejected);
  23532. }
  23533. if (++fileNo < thisBase->numParts())
  23534. {
  23535. thisKey = thisBase->queryPart(fileNo);
  23536. tlk->setKey(thisKey);
  23537. tlk->setLayoutTranslator(translators->item(fileNo));
  23538. tlk->reset();
  23539. }
  23540. else
  23541. break;
  23542. }
  23543. tlk->releaseSegmentMonitors();
  23544. tlk->setKey(NULL);
  23545. }
  23546. catch (...)
  23547. {
  23548. tlk->releaseSegmentMonitors();
  23549. tlk->setKey(NULL);
  23550. throw;
  23551. }
  23552. }
  23553. }
  23554. noteEndReceived(jg, 0);
  23555. }
  23556. else
  23557. {
  23558. noteEndReceived(createJoinGroup(row), 0);
  23559. }
  23560. }
  23561. virtual void processEOG()
  23562. {
  23563. // called from front puller thread
  23564. if (preserveGroups)
  23565. endGroup();
  23566. }
  23567. void processGroup(const ConstPointerArray &)
  23568. {
  23569. throwUnexpected();
  23570. }
  23571. };
  23572. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23573. {
  23574. Owned<const IResolvedFile> indexfile;
  23575. Owned<const IResolvedFile> datafile;
  23576. Owned<IKeyArray> keySet;
  23577. Owned<TranslatorArray> translatorArray;
  23578. Owned<IDefRecordMeta> activityMeta;
  23579. RemoteActivityId headId;
  23580. RemoteActivityId tailId;
  23581. IOutputMetaData *indexReadMeta;
  23582. Owned<IFilePartMap> map;
  23583. Owned<IFileIOArray> files;
  23584. unsigned joinFlags;
  23585. bool isHalfKeyed;
  23586. bool isLocal;
  23587. bool enableFieldTranslation;
  23588. bool variableFetchFileName;
  23589. bool variableIndexFileName;
  23590. bool isSimple;
  23591. public:
  23592. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23593. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23594. {
  23595. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23596. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23597. isSimple = isLocal;
  23598. rtlDataAttr indexLayoutMeta;
  23599. size32_t indexLayoutSize;
  23600. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23601. assertex(indexLayoutSize== 0);
  23602. MemoryBuffer m;
  23603. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  23604. activityMeta.setown(deserializeRecordMeta(m, true));
  23605. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  23606. translatorArray.setown(new TranslatorArray);
  23607. joinFlags = helper->getJoinFlags();
  23608. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23609. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23610. if (!variableIndexFileName)
  23611. {
  23612. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23613. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23614. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23615. if (indexfile)
  23616. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  23617. }
  23618. if (keySet && keySet->length()==1 && !isSimple)
  23619. {
  23620. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23621. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23622. isSimple = true;
  23623. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23624. }
  23625. if (!simpleLocalKeyedJoins)
  23626. isSimple = false;
  23627. isHalfKeyed = !helper->diskAccessRequired();
  23628. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  23629. if (!isHalfKeyed && !variableFetchFileName)
  23630. {
  23631. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  23632. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  23633. if (datafile)
  23634. {
  23635. if (isLocal)
  23636. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  23637. else
  23638. map.setown(datafile->getFileMap());
  23639. }
  23640. }
  23641. }
  23642. virtual bool getEnableFieldTranslation() const
  23643. {
  23644. return enableFieldTranslation;
  23645. }
  23646. virtual IDefRecordMeta *queryActivityMeta() const
  23647. {
  23648. return activityMeta;
  23649. }
  23650. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23651. {
  23652. if (isHalfKeyed)
  23653. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  23654. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  23655. else
  23656. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  23657. headId, keySet, translatorArray, indexReadMeta,
  23658. tailId, map, joinFlags, isLocal);
  23659. }
  23660. virtual const StatisticsMapping &queryStatsMapping() const
  23661. {
  23662. return keyedJoinStatistics;
  23663. }
  23664. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  23665. {
  23666. if (datafile)
  23667. addXrefFileInfo(reply, datafile);
  23668. if (indexfile)
  23669. addXrefFileInfo(reply, indexfile);
  23670. }
  23671. };
  23672. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  23673. {
  23674. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  23675. }
  23676. //=================================================================================
  23677. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  23678. {
  23679. protected:
  23680. Owned<ISoapCallHelper> soaphelper;
  23681. IHThorSoapActionArg & helper;
  23682. StringBuffer authToken;
  23683. bool eof;
  23684. CriticalSection crit;
  23685. ClientCertificate *pClientCert;
  23686. public:
  23687. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  23688. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23689. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  23690. {
  23691. eof = false;
  23692. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  23693. pClientCert = &clientCert;
  23694. else
  23695. pClientCert = NULL;
  23696. }
  23697. // ISoapCallRowProvider
  23698. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  23699. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  23700. virtual const void * getNextRow() { return NULL; };
  23701. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  23702. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23703. {
  23704. eof = false;
  23705. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23706. authToken.append(ctx->queryAuthToken());
  23707. }
  23708. virtual void reset()
  23709. {
  23710. // MORE - Shouldn't we make sure thread is stopped etc???
  23711. soaphelper.clear();
  23712. CRoxieServerActivity::reset();
  23713. }
  23714. // IRoxieAbortMonitor
  23715. virtual void checkForAbort() { checkAbort(); }
  23716. };
  23717. //---------------------------------------------------------------------------
  23718. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  23719. {
  23720. IHThorSoapCallArg & callHelper;
  23721. public:
  23722. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23723. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23724. {
  23725. }
  23726. virtual IHThorSoapCallArg * queryCallHelper()
  23727. {
  23728. return &callHelper;
  23729. }
  23730. virtual bool needsAllocator() const { return true; }
  23731. virtual const void *nextRow()
  23732. {
  23733. ActivityTimer t(totalCycles, timeActivities);
  23734. if(eof) return NULL;
  23735. if (soaphelper == NULL)
  23736. {
  23737. if (factory->getKind()==TAKhttp_rowdataset)
  23738. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23739. else
  23740. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  23741. soaphelper->start();
  23742. }
  23743. OwnedConstRoxieRow ret = soaphelper->getRow();
  23744. if (!ret)
  23745. {
  23746. eof = true;
  23747. return NULL;
  23748. }
  23749. ++processed;
  23750. return ret.getClear();
  23751. }
  23752. };
  23753. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  23754. {
  23755. public:
  23756. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23757. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23758. {
  23759. }
  23760. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23761. {
  23762. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  23763. }
  23764. virtual const StatisticsMapping &queryStatsMapping() const
  23765. {
  23766. return soapStatistics;
  23767. }
  23768. };
  23769. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23770. {
  23771. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23772. }
  23773. //---------------------------------------------------------------------------
  23774. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  23775. {
  23776. public:
  23777. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23778. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23779. {}
  23780. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23781. {
  23782. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  23783. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  23784. soaphelper->start();
  23785. soaphelper->waitUntilDone();
  23786. IException *e = soaphelper->getError();
  23787. soaphelper.clear();
  23788. if (e)
  23789. throw e;
  23790. }
  23791. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23792. {
  23793. return NULL;
  23794. }
  23795. virtual const void *nextRow()
  23796. {
  23797. throwUnexpected(); // I am nobody's input
  23798. }
  23799. };
  23800. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  23801. {
  23802. bool isRoot;
  23803. public:
  23804. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23805. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23806. {
  23807. }
  23808. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23809. {
  23810. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  23811. }
  23812. virtual bool isSink() const
  23813. {
  23814. return isRoot;
  23815. }
  23816. virtual const StatisticsMapping &queryStatsMapping() const
  23817. {
  23818. return soapStatistics;
  23819. }
  23820. };
  23821. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23822. {
  23823. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23824. }
  23825. //---------------------------------------------------------------------------
  23826. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  23827. {
  23828. IHThorSoapCallArg & callHelper;
  23829. public:
  23830. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23831. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  23832. {
  23833. }
  23834. virtual IHThorSoapCallArg * queryCallHelper()
  23835. {
  23836. return &callHelper;
  23837. }
  23838. virtual const void *getNextRow()
  23839. {
  23840. CriticalBlock b(crit); // MORE - why ?
  23841. return inputStream->ungroupedNextRow();
  23842. }
  23843. virtual bool needsAllocator() const { return true; }
  23844. virtual const void *nextRow()
  23845. {
  23846. ActivityTimer t(totalCycles, timeActivities);
  23847. if(eof) return NULL;
  23848. if (soaphelper == NULL)
  23849. {
  23850. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  23851. soaphelper->start();
  23852. }
  23853. OwnedConstRoxieRow ret = soaphelper->getRow();
  23854. if (!ret)
  23855. {
  23856. eof = true;
  23857. return NULL;
  23858. }
  23859. ++processed;
  23860. return ret.getClear();
  23861. }
  23862. };
  23863. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  23864. {
  23865. public:
  23866. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23867. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  23868. {
  23869. }
  23870. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23871. {
  23872. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  23873. }
  23874. virtual const StatisticsMapping &queryStatsMapping() const
  23875. {
  23876. return soapStatistics;
  23877. }
  23878. };
  23879. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  23880. {
  23881. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  23882. }
  23883. //---------------------------------------------------------------------------
  23884. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  23885. {
  23886. public:
  23887. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  23888. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  23889. {}
  23890. virtual const void *getNextRow()
  23891. {
  23892. CriticalBlock b(crit); // MORE - Why?
  23893. const void *nextrec = inputStream->ungroupedNextRow();
  23894. if (nextrec)
  23895. processed++;
  23896. return nextrec;
  23897. }
  23898. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23899. {
  23900. try
  23901. {
  23902. start(parentExtractSize, parentExtract, false);
  23903. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  23904. soaphelper->start();
  23905. soaphelper->waitUntilDone();
  23906. IException *e = soaphelper->getError();
  23907. soaphelper.clear();
  23908. if (e)
  23909. throw e;
  23910. stop();
  23911. }
  23912. catch (IException *E)
  23913. {
  23914. ctx->notifyAbort(E);
  23915. abort();
  23916. throw;
  23917. }
  23918. catch(...)
  23919. {
  23920. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  23921. ctx->notifyAbort(E);
  23922. abort();
  23923. throw;
  23924. }
  23925. }
  23926. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23927. {
  23928. return NULL;
  23929. }
  23930. virtual const void *nextRow()
  23931. {
  23932. throwUnexpected(); // I am nobody's input
  23933. }
  23934. };
  23935. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23936. {
  23937. bool isRoot;
  23938. public:
  23939. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23940. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  23941. {
  23942. }
  23943. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  23944. {
  23945. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  23946. }
  23947. virtual bool isSink() const
  23948. {
  23949. return isRoot;
  23950. }
  23951. virtual const StatisticsMapping &queryStatsMapping() const
  23952. {
  23953. return soapStatistics;
  23954. }
  23955. };
  23956. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  23957. {
  23958. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  23959. }
  23960. //=====================================================================================================
  23961. class CGraphResults : implements IRoxieGraphResults, public CInterface
  23962. {
  23963. IArrayOf<IGraphResult> results;
  23964. CriticalSection cs;
  23965. IGraphResult & select(unsigned idx)
  23966. {
  23967. CriticalBlock procedure(cs);
  23968. if (idx >= results.ordinality())
  23969. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23970. return results.item(idx);
  23971. }
  23972. public:
  23973. IMPLEMENT_IINTERFACE
  23974. void clear()
  23975. {
  23976. CriticalBlock procedure(cs);
  23977. results.kill();
  23978. }
  23979. virtual IEngineRowStream * createIterator(unsigned id)
  23980. {
  23981. return select(id).createIterator();
  23982. }
  23983. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23984. {
  23985. select(id).getLinkedResult(count, ret);
  23986. }
  23987. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23988. {
  23989. select(id).getLinkedResult(count, ret);
  23990. }
  23991. virtual const void * getLinkedRowResult(unsigned id)
  23992. {
  23993. return select(id).getLinkedRowResult();
  23994. }
  23995. void setResult(unsigned id, IGraphResult * result)
  23996. {
  23997. CriticalBlock procedure(cs);
  23998. if (results.ordinality() <= id)
  23999. {
  24000. while (results.ordinality() < id)
  24001. results.append(*new CGraphResult);
  24002. results.append(*LINK(result));
  24003. }
  24004. else
  24005. results.replace(*LINK(result), id);
  24006. }
  24007. void appendResult(IGraphResult * result)
  24008. {
  24009. CriticalBlock procedure(cs);
  24010. results.append(*LINK(result));
  24011. }
  24012. };
  24013. //===================================================================================================================
  24014. class CPseudoArg : implements IHThorArg, public CInterface
  24015. {
  24016. public:
  24017. IMPLEMENT_IINTERFACE
  24018. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  24019. };
  24020. class CPseudoActivity : public CRoxieServerActivity
  24021. {
  24022. public:
  24023. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24024. virtual const void *nextRow()
  24025. {
  24026. throwUnexpected(); // I am nobody's input
  24027. }
  24028. };
  24029. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24030. {
  24031. protected:
  24032. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24033. {
  24034. SpinLock abortLock;
  24035. bool aborted;
  24036. Owned<IException> exception;
  24037. public:
  24038. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24039. {
  24040. aborted = false;
  24041. }
  24042. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24043. virtual void notifyAbort(IException *E)
  24044. {
  24045. SpinBlock b(abortLock);
  24046. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24047. {
  24048. aborted = true;
  24049. exception.set(E);
  24050. }
  24051. }
  24052. virtual void checkAbort()
  24053. {
  24054. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24055. {
  24056. SpinBlock b(abortLock);
  24057. if (!exception)
  24058. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24059. throw exception.getLink();
  24060. }
  24061. IndirectSlaveContext::checkAbort();
  24062. }
  24063. virtual ICodeContext *queryCodeContext()
  24064. {
  24065. return codeContext;
  24066. }
  24067. void setCodeContext(ICodeContext * _codeContext)
  24068. {
  24069. codeContext = _codeContext;
  24070. }
  24071. void setLoopCounter(unsigned _loopCounter)
  24072. {
  24073. loopCounter = _loopCounter;
  24074. }
  24075. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24076. {
  24077. childGraphs.setValue(id, childGraph);
  24078. }
  24079. virtual IActivityGraph * queryChildGraph(unsigned id)
  24080. {
  24081. if (queryTraceLevel() > 10)
  24082. CTXLOG("resolveChildGraph %d", id);
  24083. IActivityGraph *childGraph = childGraphs.getValue(id);
  24084. assertex(childGraph);
  24085. return childGraph;
  24086. }
  24087. // 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
  24088. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24089. {
  24090. logctx.getLogPrefix(ret);
  24091. if (loopCounter)
  24092. ret.appendf("{%u}", loopCounter);
  24093. return ret;
  24094. }
  24095. protected:
  24096. const IRoxieContextLogger &logctx;
  24097. unsigned loopCounter;
  24098. ICodeContext * codeContext;
  24099. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24100. } graphSlaveContext;
  24101. class ActivityGraphCodeContext : public IndirectCodeContext
  24102. {
  24103. public:
  24104. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24105. {
  24106. if ((unsigned) activityId == container->queryId())
  24107. return container;
  24108. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24109. if (match)
  24110. return match->queryLocalGraph();
  24111. return IndirectCodeContext::resolveLocalQuery(activityId);
  24112. }
  24113. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24114. {
  24115. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24116. return LINK(match->queryChildGraph());
  24117. }
  24118. virtual unsigned getGraphLoopCounter() const
  24119. {
  24120. return container->queryLoopCounter(); // only called if value is valid
  24121. }
  24122. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24123. {
  24124. slaveContext = _slaveContext;
  24125. container = _container;
  24126. }
  24127. protected:
  24128. IRoxieSlaveContext * slaveContext;
  24129. CActivityGraph * container;
  24130. } graphCodeContext;
  24131. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24132. IArrayOf<IRoxieServerActivity> activities;
  24133. IArrayOf<IRoxieProbe> probes;
  24134. IRoxieServerActivityCopyArray sinks;
  24135. StringAttr graphName;
  24136. Owned<CGraphResults> results;
  24137. CGraphResults graphLoopResults;
  24138. ActivityArray & graphDefinition;
  24139. CriticalSection evaluateCrit;
  24140. IProbeManager *probeManager;
  24141. unsigned id;
  24142. unsigned loopCounter;
  24143. public:
  24144. IMPLEMENT_IINTERFACE;
  24145. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24146. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24147. {
  24148. id = x.getLibraryGraphId();
  24149. if (!id)
  24150. id = _id;
  24151. loopCounter = 0;
  24152. graphSlaveContext.setCodeContext(&graphCodeContext);
  24153. graphCodeContext.setContainer(&graphSlaveContext, this);
  24154. }
  24155. ~CActivityGraph()
  24156. {
  24157. if (probeManager)
  24158. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24159. }
  24160. virtual const char *queryName() const
  24161. {
  24162. return graphName.get();
  24163. }
  24164. virtual IRoxieServerActivity *queryActivity(unsigned _activityId)
  24165. {
  24166. unsigned idx = graphDefinition.recursiveFindActivityIndex(_activityId);
  24167. if (idx==NotFound)
  24168. return nullptr;
  24169. assertex(activities.isItem(idx));
  24170. IRoxieServerActivity *activity = &activities.item(idx);
  24171. if (activity->queryId() == _activityId)
  24172. return activity;
  24173. return activity->queryChildActivity(_activityId);
  24174. }
  24175. void createGraph(IRoxieSlaveContext *_ctx)
  24176. {
  24177. if (graphDefinition.isMultiInstance())
  24178. {
  24179. graphCodeContext.set(_ctx->queryCodeContext());
  24180. _ctx = &graphSlaveContext;
  24181. }
  24182. ForEachItemIn(idx, graphDefinition)
  24183. {
  24184. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24185. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24186. activities.append(activity);
  24187. if (donor.isSink())
  24188. {
  24189. sinks.append(activity);
  24190. if (probeManager)
  24191. probeManager->noteSink(&activity);
  24192. }
  24193. }
  24194. ForEachItemIn(idx1, graphDefinition)
  24195. {
  24196. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24197. IRoxieServerActivity &activity = activities.item(idx1);
  24198. unsigned inputidx = 0;
  24199. loop
  24200. {
  24201. unsigned outputidx;
  24202. unsigned source = donor.getInput(inputidx, outputidx);
  24203. if (source==(unsigned) -1)
  24204. break;
  24205. connectInput(idx1, inputidx, source, outputidx, 0);
  24206. inputidx++;
  24207. }
  24208. IntArray &dependencies = donor.queryDependencies();
  24209. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24210. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24211. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24212. ForEachItemIn(idx2, dependencies)
  24213. {
  24214. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24215. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24216. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24217. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24218. if (probeManager)
  24219. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24220. }
  24221. }
  24222. ForEachItemIn(idx2, sinks)
  24223. {
  24224. IRoxieServerActivity &sink = sinks.item(idx2);
  24225. sink.connectInputStreams(true);
  24226. }
  24227. }
  24228. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24229. {
  24230. IRoxieServerActivity &targetActivity = activities.item(target);
  24231. IRoxieServerActivity &sourceActivity = activities.item(source);
  24232. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24233. if (probeManager)
  24234. {
  24235. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24236. probes.append(*LINK(inputProbe));
  24237. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24238. }
  24239. targetActivity.setInput(targetIdx, sourceIdx, output);
  24240. }
  24241. virtual void onCreate(IHThorArg *_colocalParent)
  24242. {
  24243. ForEachItemIn(idx, activities)
  24244. {
  24245. IRoxieServerActivity *activity = &activities.item(idx);
  24246. if (activity)
  24247. activity->onCreate(_colocalParent);
  24248. }
  24249. }
  24250. virtual void abort()
  24251. {
  24252. ForEachItemIn(idx, sinks)
  24253. {
  24254. IRoxieServerActivity &sink = sinks.item(idx);
  24255. sink.abort();
  24256. }
  24257. }
  24258. virtual void reset()
  24259. {
  24260. ForEachItemIn(idx, sinks)
  24261. {
  24262. IRoxieServerActivity &sink = sinks.item(idx);
  24263. sink.reset();
  24264. }
  24265. }
  24266. Linked<IException> exception;
  24267. CriticalSection eCrit;
  24268. virtual void noteException(IException *E)
  24269. {
  24270. CriticalBlock b(eCrit);
  24271. if (!exception)
  24272. {
  24273. if (graphSlaveContext.queryDebugContext())
  24274. {
  24275. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24276. }
  24277. exception.set(E);
  24278. }
  24279. }
  24280. virtual void checkAbort()
  24281. {
  24282. CriticalBlock b(eCrit);
  24283. if (exception)
  24284. throw exception.getLink();
  24285. }
  24286. virtual void execute()
  24287. {
  24288. results.setown(new CGraphResults);
  24289. doExecute(0, NULL);
  24290. }
  24291. //New child query code...
  24292. virtual IThorChildGraph * queryChildGraph()
  24293. {
  24294. return this;
  24295. }
  24296. virtual IEclGraphResults * queryLocalGraph()
  24297. {
  24298. return this;
  24299. }
  24300. virtual IRoxieServerChildGraph * queryLoopGraph()
  24301. {
  24302. return this;
  24303. }
  24304. inline unsigned queryId() const
  24305. {
  24306. return id;
  24307. }
  24308. inline unsigned queryLoopCounter() const
  24309. {
  24310. return loopCounter;
  24311. }
  24312. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24313. {
  24314. if (sinks.ordinality()==1)
  24315. sinks.item(0).execute(parentExtractSize, parentExtract);
  24316. #ifdef PARALLEL_EXECUTE
  24317. else if (!probeManager && !graphDefinition.isSequential())
  24318. {
  24319. class casyncfor: public CAsyncFor
  24320. {
  24321. public:
  24322. IActivityGraph &parent;
  24323. unsigned parentExtractSize;
  24324. const byte * parentExtract;
  24325. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24326. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24327. void Do(unsigned i)
  24328. {
  24329. try
  24330. {
  24331. sinks.item(i).execute(parentExtractSize, parentExtract);
  24332. }
  24333. catch (IException *E)
  24334. {
  24335. parent.noteException(E);
  24336. throw;
  24337. }
  24338. }
  24339. private:
  24340. IRoxieServerActivityCopyArray &sinks;
  24341. } afor(sinks, *this, parentExtractSize, parentExtract);
  24342. afor.For(sinks.ordinality(), sinks.ordinality());
  24343. }
  24344. #endif
  24345. else
  24346. {
  24347. ForEachItemIn(idx, sinks)
  24348. {
  24349. IRoxieServerActivity &sink = sinks.item(idx);
  24350. sink.execute(parentExtractSize, parentExtract);
  24351. }
  24352. }
  24353. }
  24354. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24355. {
  24356. CriticalBlock block(evaluateCrit);
  24357. results.setown(new CGraphResults);
  24358. try
  24359. {
  24360. doExecute(parentExtractSize, parentExtract);
  24361. }
  24362. catch (...)
  24363. {
  24364. DBGLOG("Exception thrown in child query - cleaning up");
  24365. reset();
  24366. throw;
  24367. }
  24368. reset();
  24369. return results.getClear();
  24370. }
  24371. //interface IRoxieServerChildGraph
  24372. virtual void beforeExecute()
  24373. {
  24374. results.setown(new CGraphResults);
  24375. }
  24376. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24377. {
  24378. IFinalRoxieInput * ret = selectOutput(id);
  24379. ret->start(parentExtractSize, parentExtract, paused);
  24380. return ret;
  24381. }
  24382. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24383. {
  24384. ForEachItemIn(i, sinks)
  24385. {
  24386. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24387. if (ret)
  24388. return ret;
  24389. }
  24390. throwUnexpected();
  24391. return NULL;
  24392. }
  24393. virtual void setInputResult(unsigned id, IGraphResult * result)
  24394. {
  24395. results->setResult(id, result);
  24396. }
  24397. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24398. {
  24399. ForEachItemIn(i, activities)
  24400. {
  24401. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24402. return true;
  24403. }
  24404. return false;
  24405. }
  24406. virtual void stopUnusedOutputs()
  24407. {
  24408. //Hmm not sure how to do this...
  24409. }
  24410. virtual void afterExecute()
  24411. {
  24412. ForEachItemIn(i, sinks)
  24413. {
  24414. sinks.item(i).stop();
  24415. }
  24416. if (graphSlaveContext.queryDebugContext())
  24417. {
  24418. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24419. }
  24420. reset();
  24421. }
  24422. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24423. {
  24424. doExecute(parentExtractSize, parentExtract);
  24425. return LINK(results);
  24426. }
  24427. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  24428. {
  24429. results->getLinkedResult(count, ret, id);
  24430. }
  24431. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  24432. {
  24433. results->getLinkedResult(count, ret, id);
  24434. }
  24435. virtual const void * getLinkedRowResult(unsigned id)
  24436. {
  24437. return results->getLinkedRowResult(id);
  24438. }
  24439. virtual void setResult(unsigned id, IGraphResult * result)
  24440. {
  24441. results->setResult(id, result);
  24442. }
  24443. virtual IEngineRowStream * createResultIterator(unsigned id)
  24444. {
  24445. return results->createIterator(id);
  24446. }
  24447. virtual void setGraphLoopResult(IGraphResult * result)
  24448. {
  24449. graphLoopResults.appendResult(result);
  24450. }
  24451. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24452. {
  24453. try
  24454. {
  24455. return graphLoopResults.createIterator(id);
  24456. }
  24457. catch (IException * e)
  24458. {
  24459. e->Release();
  24460. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24461. }
  24462. }
  24463. virtual void clearGraphLoopResults()
  24464. {
  24465. graphLoopResults.clear();
  24466. }
  24467. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24468. {
  24469. doExecute(parentExtractSize, parentExtract);
  24470. }
  24471. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24472. {
  24473. graphLoopResults.setResult(id, result);
  24474. }
  24475. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24476. {
  24477. return graphLoopResults.createIterator(id);
  24478. }
  24479. virtual void getProbeResponse(IPropertyTree *query)
  24480. {
  24481. if (probeManager)
  24482. probeManager->getProbeResponse(query);
  24483. }
  24484. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24485. {
  24486. throwUnexpected();
  24487. }
  24488. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24489. {
  24490. return NULL;
  24491. }
  24492. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24493. {
  24494. throwUnexpected();
  24495. }
  24496. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24497. {
  24498. throwUnexpected();
  24499. }
  24500. };
  24501. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24502. {
  24503. public:
  24504. IMPLEMENT_IINTERFACE;
  24505. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24506. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  24507. {
  24508. }
  24509. virtual void abort() { throwUnexpected(); }
  24510. virtual void reset() { throwUnexpected(); }
  24511. virtual void execute() { throwUnexpected(); }
  24512. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24513. virtual void onCreate(IHThorArg *_colocalArg)
  24514. {
  24515. colocalArg = _colocalArg;
  24516. }
  24517. virtual void noteException(IException *E) { throwUnexpected(); }
  24518. virtual void checkAbort() { throwUnexpected(); }
  24519. virtual IThorChildGraph * queryChildGraph() { return this; }
  24520. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24521. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24522. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
  24523. virtual const char *queryName() const { throwUnexpected(); }
  24524. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24525. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24526. {
  24527. Owned<CActivityGraph> realGraph;
  24528. {
  24529. CriticalBlock b(graphCrit);
  24530. if (stack.length())
  24531. realGraph.setown(&stack.popGet());
  24532. }
  24533. if (!realGraph)
  24534. {
  24535. realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
  24536. realGraph->createGraph(ctx);
  24537. realGraph->onCreate(colocalArg);
  24538. }
  24539. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24540. {
  24541. CriticalBlock b(graphCrit);
  24542. stack.append(*realGraph.getClear());
  24543. }
  24544. return results.getClear();
  24545. }
  24546. protected:
  24547. IRoxieSlaveContext *ctx;
  24548. StringAttr graphName;
  24549. unsigned id;
  24550. ActivityArray &graphDefinition;
  24551. const IRoxieContextLogger &logctx;
  24552. unsigned numParallel;
  24553. IHThorArg *colocalArg = nullptr;
  24554. CriticalSection graphCrit;
  24555. CIArrayOf<CActivityGraph> stack;
  24556. };
  24557. class CIterationActivityGraph : public CActivityGraph
  24558. {
  24559. IHThorArg * colocalParent;
  24560. unsigned fixedParentExtractSize;
  24561. const byte * fixedParentExtract;
  24562. unsigned graphOutputActivityIndex;
  24563. public:
  24564. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  24565. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  24566. : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
  24567. {
  24568. graphOutputActivityIndex = 0;
  24569. loopCounter = _loopCounter;
  24570. colocalParent = _colocalParent;
  24571. graphSlaveContext.setLoopCounter(loopCounter);
  24572. graphCodeContext.set(_ctx->queryCodeContext());
  24573. fixedParentExtractSize = parentExtractSize;
  24574. fixedParentExtract = parentExtract;
  24575. }
  24576. void createIterationGraph(IRoxieSlaveContext *_ctx)
  24577. {
  24578. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  24579. ForEachItemIn(idx1, graphDefinition)
  24580. activities.append(*LINK(pseudoActivity));
  24581. graphOutputActivityIndex = queryGraphOutputIndex();
  24582. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  24583. }
  24584. unsigned queryGraphOutputIndex() const
  24585. {
  24586. ForEachItemIn(i, graphDefinition)
  24587. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  24588. return i;
  24589. throwUnexpected();
  24590. }
  24591. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  24592. {
  24593. //Check to see if already created
  24594. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  24595. if (prevActivity.queryId() != 0)
  24596. {
  24597. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  24598. return;
  24599. }
  24600. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  24601. IRoxieServerActivity * activity = NULL;
  24602. if (donor.isGraphInvariant())
  24603. {
  24604. ThorActivityKind kind = donor.getKind();
  24605. switch (kind)
  24606. {
  24607. case TAKif:
  24608. case TAKchildif:
  24609. case TAKcase:
  24610. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  24611. {
  24612. Owned<IHThorArg> helper = &donor.getHelper();
  24613. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  24614. helper->onStart(fixedParentExtract, NULL);
  24615. unsigned branch;
  24616. switch (kind)
  24617. {
  24618. case TAKif: case TAKchildif:
  24619. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  24620. break;
  24621. case TAKcase: case TAKchildcase:
  24622. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  24623. if (branch >= donor.numInputs())
  24624. branch = donor.numInputs() - 1;
  24625. break;
  24626. default:
  24627. throwUnexpected();
  24628. }
  24629. helper.clear();
  24630. unsigned outputidx;
  24631. unsigned source = donor.getInput(branch, outputidx);
  24632. if (source ==(unsigned) -1)
  24633. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  24634. else
  24635. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  24636. activities.replace(*activity, whichActivity);
  24637. activity->onCreate(colocalParent);
  24638. if (source ==(unsigned) -1)
  24639. return;
  24640. recursiveCreateGraph(_ctx, source);
  24641. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  24642. break;
  24643. }
  24644. }
  24645. }
  24646. if (!activity)
  24647. {
  24648. activity = donor.createActivity(&graphSlaveContext, probeManager);
  24649. activities.replace(*activity, whichActivity);
  24650. activity->onCreate(colocalParent);
  24651. activity->resetOutputsUsed();
  24652. unsigned inputidx = 0;
  24653. loop
  24654. {
  24655. unsigned outputidx;
  24656. unsigned source = donor.getInput(inputidx, outputidx);
  24657. if (source==(unsigned) -1)
  24658. break;
  24659. recursiveCreateGraph(_ctx, source);
  24660. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  24661. inputidx++;
  24662. }
  24663. }
  24664. IntArray &dependencies = donor.queryDependencies();
  24665. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24666. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24667. ForEachItemIn(idx2, dependencies)
  24668. {
  24669. unsigned input = dependencies.item(idx2);
  24670. recursiveCreateGraph(_ctx, input);
  24671. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  24672. }
  24673. }
  24674. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24675. {
  24676. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  24677. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  24678. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  24679. }
  24680. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24681. {
  24682. ForEachItemIn(i, activities)
  24683. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  24684. }
  24685. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24686. {
  24687. ForEachItemIn(i, activities)
  24688. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  24689. }
  24690. };
  24691. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  24692. {
  24693. StringAttr graphName;
  24694. ActivityArray & graphDefinition;
  24695. IProbeManager *probeManager;
  24696. unsigned id;
  24697. IRoxieSlaveContext * ctx;
  24698. IHThorArg * colocalParent;
  24699. public:
  24700. IMPLEMENT_IINTERFACE;
  24701. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  24702. : probeManager(_probeManager), graphDefinition(x)
  24703. {
  24704. graphName.set(_graphName);
  24705. id = _id;
  24706. ctx = NULL;
  24707. colocalParent = NULL;
  24708. }
  24709. virtual const char *queryName() const { return graphName.get(); }
  24710. virtual void abort() { throwUnexpected(); }
  24711. virtual void reset() { }
  24712. virtual void execute() { throwUnexpected(); }
  24713. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  24714. virtual void noteException(IException *E) { throwUnexpected(); }
  24715. virtual void checkAbort() { throwUnexpected(); }
  24716. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  24717. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  24718. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  24719. virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
  24720. virtual void onCreate(IHThorArg *_colocalParent)
  24721. {
  24722. colocalParent = _colocalParent;
  24723. }
  24724. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24725. {
  24726. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  24727. ret->createIterationGraph(ctx);
  24728. return ret.getClear();
  24729. }
  24730. };
  24731. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  24732. {
  24733. if (childFactories.isDelayed())
  24734. {
  24735. assertex(numParallel==1);
  24736. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  24737. }
  24738. else
  24739. {
  24740. if (numParallel==1 || _probeManager != nullptr)
  24741. {
  24742. Owned<IProbeManager> childProbe;
  24743. if (_probeManager)
  24744. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  24745. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
  24746. ret->createGraph(ctx);
  24747. if (_probeManager)
  24748. _probeManager->endChildGraph(childProbe, parentActivity);
  24749. return ret.getClear();
  24750. }
  24751. else
  24752. return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
  24753. }
  24754. }
  24755. //================================================================================================================
  24756. #ifdef _USE_CPPUNIT
  24757. #include "unittests.hpp"
  24758. // 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...
  24759. #if _MSC_VER==1200
  24760. #undef protected
  24761. #endif
  24762. static const char *sortAlgorithm;
  24763. class TestMetaData : public CInterface, implements IOutputMetaData
  24764. {
  24765. public:
  24766. IMPLEMENT_IINTERFACE;
  24767. virtual size32_t getRecordSize(const void *) { return 10; }
  24768. virtual size32_t getMinRecordSize() const { return 10; }
  24769. virtual size32_t getFixedSize() const { return 10; }
  24770. virtual void toXML(const byte * self, IXmlWriter & out) {}
  24771. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  24772. virtual unsigned getMetaFlags() { return 0; }
  24773. virtual void destruct(byte * self) {}
  24774. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24775. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24776. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24777. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  24778. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24779. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  24780. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  24781. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  24782. } testMeta;
  24783. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  24784. {
  24785. char const * const *input;
  24786. IRoxieSlaveContext *ctx;
  24787. unsigned endSeen;
  24788. bool eof;
  24789. unsigned count;
  24790. ActivityTimeAccumulator totalCycles;
  24791. size32_t recordSize;
  24792. unsigned activityId;
  24793. public:
  24794. enum { STATEreset, STATEstarted, STATEstopped } state;
  24795. bool allRead;
  24796. unsigned repeat;
  24797. IMPLEMENT_IINTERFACE;
  24798. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  24799. {
  24800. ctx = _ctx;
  24801. input = _input;
  24802. count = 0;
  24803. eof = false;
  24804. allRead = false;
  24805. endSeen = 0;
  24806. recordSize = testMeta.getFixedSize();
  24807. state = STATEreset;
  24808. activityId = 1;
  24809. repeat = 0;
  24810. }
  24811. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  24812. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  24813. {
  24814. ASSERT(state == STATEreset);
  24815. }
  24816. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24817. {
  24818. ASSERT(state == STATEreset);
  24819. state = STATEstarted;
  24820. }
  24821. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  24822. {
  24823. streams.append(this);
  24824. return NULL;
  24825. }
  24826. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  24827. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  24828. virtual IRoxieServerActivity *queryActivity()
  24829. {
  24830. throwUnexpected();
  24831. }
  24832. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  24833. {
  24834. throwUnexpected();
  24835. }
  24836. virtual void stop()
  24837. {
  24838. state = STATEstopped;
  24839. }
  24840. virtual void reset()
  24841. {
  24842. ASSERT(state == STATEstopped);
  24843. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  24844. }
  24845. virtual void resetEOF()
  24846. {
  24847. throwUnexpected();
  24848. }
  24849. virtual void checkAbort() {}
  24850. virtual unsigned queryId() const { return activityId; };
  24851. virtual const void *nextRow()
  24852. {
  24853. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  24854. ASSERT(state == STATEstarted);
  24855. ASSERT(allRead || !eof);
  24856. if (eof)
  24857. return NULL;
  24858. again:
  24859. const char *nextSource = input[count++];
  24860. if (nextSource)
  24861. {
  24862. endSeen = 0;
  24863. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  24864. memset(ret, 0, recordSize);
  24865. strncpy((char *) ret, nextSource, recordSize);
  24866. return ret;
  24867. }
  24868. else if (repeat)
  24869. {
  24870. repeat--;
  24871. count = 0;
  24872. goto again;
  24873. }
  24874. else
  24875. {
  24876. endSeen++;
  24877. if (endSeen==2)
  24878. eof = true;
  24879. return NULL;
  24880. }
  24881. }
  24882. virtual bool nextGroup(ConstPointerArray & group)
  24883. {
  24884. const void * next;
  24885. while ((next = nextRow()) != NULL)
  24886. group.append(next);
  24887. if (group.ordinality())
  24888. return true;
  24889. return false;
  24890. }
  24891. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  24892. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  24893. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  24894. {
  24895. return NULL;
  24896. }
  24897. };
  24898. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  24899. public:
  24900. struct CompareClass : public ICompare {
  24901. virtual int docompare(const void * _left, const void * _right) const {
  24902. return memcmp(_left, _right, 5);
  24903. }
  24904. } compare;
  24905. virtual ICompare * queryCompare() { return &compare; }
  24906. virtual IOutputMetaData * queryOutputMeta()
  24907. {
  24908. return &testMeta;
  24909. }
  24910. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  24911. virtual const char * getAlgorithm() { return sortAlgorithm; }
  24912. };
  24913. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  24914. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  24915. static bool isDedup;
  24916. public:
  24917. struct CompareClass : public ICompare {
  24918. virtual int docompare(const void * _left, const void * _right) const {
  24919. return memcmp(_left, _right, 5);
  24920. }
  24921. } compare;
  24922. virtual ICompare * queryCompare() { return &compare; }
  24923. virtual IOutputMetaData * queryOutputMeta()
  24924. {
  24925. return &testMeta;
  24926. }
  24927. virtual bool dedup() { return isDedup; }
  24928. };
  24929. bool MergeActivityTest::isDedup = false;
  24930. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  24931. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  24932. public:
  24933. virtual unsigned numBranches() { return 2; }
  24934. virtual IOutputMetaData * queryOutputMeta()
  24935. {
  24936. return &testMeta;
  24937. }
  24938. };
  24939. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  24940. class CcdServerTest : public CppUnit::TestFixture
  24941. {
  24942. CPPUNIT_TEST_SUITE(CcdServerTest);
  24943. CPPUNIT_TEST(testSetup);
  24944. CPPUNIT_TEST(testHeapSort);
  24945. CPPUNIT_TEST(testQuickSort);
  24946. CPPUNIT_TEST(testMerge);
  24947. CPPUNIT_TEST(testMergeDedup);
  24948. CPPUNIT_TEST(testMiscellaneous);
  24949. CPPUNIT_TEST(testSplitter);
  24950. CPPUNIT_TEST(testCleanup);
  24951. CPPUNIT_TEST_SUITE_END();
  24952. protected:
  24953. SlaveContextLogger logctx;
  24954. Owned<const IQueryDll> queryDll;
  24955. Owned<IRoxiePackage> package;
  24956. Owned<IPropertyTree> stateInfo;
  24957. Owned<IQueryFactory> queryFactory;
  24958. Owned<IRoxieSlaveContext> ctx;
  24959. void testSetup()
  24960. {
  24961. selfTestMode = true;
  24962. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  24963. }
  24964. void testCleanup()
  24965. {
  24966. roxiemem::releaseRoxieHeap();
  24967. }
  24968. void init()
  24969. {
  24970. package.setown(createRoxiePackage(NULL, NULL));
  24971. queryDll.setown(createExeQueryDll("roxie"));
  24972. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  24973. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  24974. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  24975. queryActiveTimer()->reset();
  24976. }
  24977. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  24978. {
  24979. testActivity(activity, input, NULL, output);
  24980. }
  24981. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  24982. {
  24983. TestInput in(ctx, input);
  24984. TestInput in2(ctx, input2);
  24985. activity->setInput(0, 0, &in);
  24986. if (input2)
  24987. activity->setInput(1, 0, &in2);
  24988. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  24989. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  24990. IOutputMetaData *meta = out->queryOutputMeta();
  24991. void *buf = alloca(meta->getFixedSize());
  24992. for (unsigned iteration = 0; iteration < 8; iteration++)
  24993. {
  24994. // 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)
  24995. // This should be true whether we read all, some, or none of the data.
  24996. // Should not matter if an activity is not started
  24997. if (iteration % 4 == 0)
  24998. activity->onCreate(NULL);
  24999. unsigned count = 0;
  25000. if (iteration % 4 != 3)
  25001. {
  25002. activity->start(0, NULL, false);
  25003. ASSERT(in.state == TestInput::STATEstarted);
  25004. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25005. loop
  25006. {
  25007. const void *next = outStream->nextRow();
  25008. if (!next)
  25009. {
  25010. ASSERT(output[count++] == NULL);
  25011. next = outStream->nextRow();
  25012. if (!next)
  25013. {
  25014. ASSERT(output[count++] == NULL);
  25015. break;
  25016. }
  25017. }
  25018. ASSERT(output[count] != NULL);
  25019. unsigned outsize = meta->getRecordSize(next);
  25020. memset(buf, 0, outsize);
  25021. strncpy((char *) buf, output[count++], outsize);
  25022. ASSERT(memcmp(next, buf, outsize) == 0);
  25023. ReleaseRoxieRow(next);
  25024. if (iteration % 4 == 2)
  25025. break;
  25026. }
  25027. if (iteration % 4 != 2)
  25028. {
  25029. // Check that reading after end is harmless
  25030. in.allRead = true;
  25031. const void *next = outStream->nextRow();
  25032. ASSERT(next == NULL);
  25033. }
  25034. }
  25035. activity->stop();
  25036. ASSERT(in.state == TestInput::STATEstopped);
  25037. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25038. activity->reset();
  25039. ASSERT(in.state == TestInput::STATEreset);
  25040. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25041. ctx->queryRowManager().reportLeaks();
  25042. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25043. }
  25044. }
  25045. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25046. {
  25047. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25048. TestInput in(ctx, input);
  25049. in.repeat = repeat;
  25050. activity->setInput(0, 0, &in);
  25051. ArrayOf<IFinalRoxieInput *> out;
  25052. for (unsigned i = 0; i < numOutputs; i++)
  25053. {
  25054. out.append(activity->queryOutput(i));
  25055. }
  25056. activity->onCreate(NULL);
  25057. class casyncfor: public CAsyncFor
  25058. {
  25059. public:
  25060. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25061. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25062. {}
  25063. void Do(unsigned i)
  25064. {
  25065. IFinalRoxieInput *out = outputs.item(i);
  25066. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25067. out->start(0, NULL, false);
  25068. IOutputMetaData *meta = out->queryOutputMeta();
  25069. void *buf = alloca(meta->getFixedSize());
  25070. unsigned count = 0;
  25071. unsigned repeats = repeat;
  25072. loop
  25073. {
  25074. const void *next = outStream->nextRow();
  25075. if (!next)
  25076. {
  25077. ASSERT(repeats==0);
  25078. ASSERT(output[count] == NULL);
  25079. count++;
  25080. next = outStream->nextRow();
  25081. if (!next)
  25082. {
  25083. ASSERT(output[count] == NULL);
  25084. count++;
  25085. break;
  25086. }
  25087. }
  25088. if (output[count] == NULL && repeats)
  25089. {
  25090. repeats--;
  25091. count = 0;
  25092. }
  25093. ASSERT(output[count] != NULL);
  25094. unsigned outsize = meta->getRecordSize(next);
  25095. memset(buf, 0, outsize);
  25096. strncpy((char *) buf, output[count++], outsize);
  25097. ASSERT(memcmp(next, buf, outsize) == 0);
  25098. ReleaseRoxieRow(next);
  25099. }
  25100. outStream->stop();
  25101. }
  25102. private:
  25103. IRoxieServerActivity *activity;
  25104. ArrayOf<IFinalRoxieInput *> &outputs;
  25105. char const * const *input;
  25106. char const * const *output;
  25107. unsigned repeat;
  25108. CcdServerTest *parent;
  25109. } afor(this, activity, out, input, output, repeat);
  25110. afor.For(numOutputs, numOutputs);
  25111. ASSERT(in.state == TestInput::STATEstopped);
  25112. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25113. {
  25114. out.item(i2)->reset();
  25115. }
  25116. ASSERT(in.state == TestInput::STATEreset);
  25117. ctx->queryRowManager().reportLeaks();
  25118. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25119. }
  25120. static int compareFunc(const void *l, const void *r)
  25121. {
  25122. return strcmp(*(char **) l, *(char **) r);
  25123. }
  25124. void testSort(unsigned type)
  25125. {
  25126. init();
  25127. sortAlgorithm = NULL;
  25128. if (type==2)
  25129. sortAlgorithm = "heapSort";
  25130. else
  25131. sortAlgorithm = "quickSort";
  25132. DBGLOG("Testing %s activity", sortAlgorithm);
  25133. Owned<IPropertyTree> dummyNode = createPTree("node");
  25134. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25135. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25136. const char * test[] = { NULL, NULL };
  25137. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25138. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25139. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25140. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25141. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25142. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25143. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25144. testActivity(activity, test, test);
  25145. testActivity(activity, test12345, test12345);
  25146. testActivity(activity, test54321, test12345);
  25147. testActivity(activity, test11111, test11111);
  25148. testActivity(activity, test11111_12345, test11111_12345);
  25149. testActivity(activity, test11111_54321, test11111_12345);
  25150. testActivity(activity, test54321_54321, test12345_12345);
  25151. // A few larger tests
  25152. char *input[2002];
  25153. char *output[2002];
  25154. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25155. unsigned i;
  25156. // identical
  25157. for (i=0; i<2000; i++)
  25158. {
  25159. input[i] = new char[11];
  25160. output[i] = new char[11];
  25161. sprintf(input[i], "1");
  25162. sprintf(output[i], "1");
  25163. }
  25164. testActivity(activity, input, output);
  25165. // Ascending
  25166. for (i=0; i<2000; i++)
  25167. {
  25168. sprintf(input[i], "%04d", i);
  25169. sprintf(output[i], "%04d", i);
  25170. }
  25171. testActivity(activity, input, output);
  25172. // Almost sorted
  25173. for (i=0; i<20; i++)
  25174. {
  25175. unsigned h = i*100;
  25176. sprintf(input[h], "%04d", 1900-h);
  25177. }
  25178. testActivity(activity, input, output);
  25179. // Descending
  25180. for (i=0; i<2000; i++)
  25181. {
  25182. sprintf(input[i], "%04d", 1999-i);
  25183. sprintf(output[i], "%04d", i);
  25184. }
  25185. testActivity(activity, input, output);
  25186. // Random
  25187. for (i=0; i<2000; i++)
  25188. {
  25189. unsigned r = rand() % 1500;
  25190. sprintf(input[i], "%04d", r);
  25191. sprintf(output[i], "%04d", r);
  25192. }
  25193. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25194. testActivity(activity, input, output);
  25195. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  25196. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25197. factory->resetNodeProgressInfo();
  25198. if (type)
  25199. {
  25200. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25201. // All sort identical
  25202. for (i=0; i<2000; i++)
  25203. {
  25204. sprintf(input[i], "1 %d", i);
  25205. sprintf(output[i], "1 %d", i);
  25206. }
  25207. testActivity(activity, input, output);
  25208. // Already sorted
  25209. for (i=0; i<2000; i++)
  25210. {
  25211. sprintf(input[i], "%04d %d", i / 10, i);
  25212. sprintf(output[i], "%04d %d", i / 10, i);
  25213. }
  25214. testActivity(activity, input, output);
  25215. // Reverse order
  25216. for (i=0; i<2000; i++)
  25217. {
  25218. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25219. sprintf(output[i], "%04d %d", i / 10, i%10);
  25220. }
  25221. testActivity(activity, input, output);
  25222. }
  25223. for (i=0; i<2000; i++)
  25224. {
  25225. delete [] input[i];
  25226. delete [] output[i];
  25227. }
  25228. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25229. }
  25230. void testQuickSort()
  25231. {
  25232. testSort(0);
  25233. }
  25234. void testHeapSort()
  25235. {
  25236. testSort(2);
  25237. }
  25238. void testMerge()
  25239. {
  25240. DBGLOG("testMerge");
  25241. init();
  25242. Owned<IPropertyTree> splitterNode = createPTree();
  25243. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25244. factory->setInput(0,0,0);
  25245. factory->setInput(1,0,0);
  25246. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25247. const char * test[] = { NULL, NULL };
  25248. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25249. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25250. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25251. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25252. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25253. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25254. 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 };
  25255. testActivity(activity, test, test, test);
  25256. testActivity(activity, test12345, test, test12345);
  25257. testActivity(activity, test, test12345, test12345);
  25258. testActivity(activity, test12345, test12345, test1122334455);
  25259. testActivity(activity, test11111, test, test11111);
  25260. testActivity(activity, test, test11111, test11111);
  25261. testActivity(activity, test11111, test11111, test1111111111);
  25262. testActivity(activity, test11111_12345, test, test1111112345);
  25263. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25264. // Should really test WHICH side gets kept...
  25265. // Should test with more than 2 inputs...
  25266. DBGLOG("testMerge done");
  25267. }
  25268. void testMergeDedup()
  25269. {
  25270. DBGLOG("testMergeDedup");
  25271. init();
  25272. MergeActivityTest::isDedup = true;
  25273. Owned<IPropertyTree> splitterNode = createPTree();
  25274. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25275. factory->setInput(0,0,0);
  25276. factory->setInput(1,0,0);
  25277. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25278. const char * test[] = { NULL, NULL };
  25279. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25280. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25281. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25282. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25283. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25284. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25285. testActivity(activity, test, test11111, test11111);
  25286. testActivity(activity, test, test, test);
  25287. testActivity(activity, test12345, test, test12345);
  25288. testActivity(activity, test, test12345, test12345);
  25289. testActivity(activity, test12345, test12345, test12345);
  25290. testActivity(activity, test11111_12345, test, test1111112345);
  25291. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25292. // Should really test WHICH side gets kept...
  25293. // Should test with more than 2 inputs...
  25294. DBGLOG("testMergeDedup done");
  25295. }
  25296. void doTestSplitter(unsigned numOutputs)
  25297. {
  25298. DBGLOG("testSplit %d", numOutputs);
  25299. init();
  25300. Owned<IPropertyTree> splitterNode = createPTree();
  25301. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25302. factory->setInput(0,0,0);
  25303. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25304. const char * test[] = { NULL, NULL };
  25305. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25306. unsigned start = msTick();
  25307. testSplitActivity(factory, test, test, numOutputs, 0);
  25308. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25309. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25310. unsigned elapsed = msTick() - start;
  25311. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25312. }
  25313. void testSplitter()
  25314. {
  25315. doTestSplitter(1);
  25316. doTestSplitter(2);
  25317. doTestSplitter(3);
  25318. doTestSplitter(10);
  25319. }
  25320. void testMiscellaneous()
  25321. {
  25322. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25323. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25324. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25325. ASSERT(sizeof(CJoinGroup) <= 120);
  25326. }
  25327. };
  25328. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25329. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25330. #endif