ccdserver.cpp 911 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118
  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 "jlzw.hpp"
  27. #include "javahash.hpp"
  28. #include "javahash.tpp"
  29. #include "thorstep.ipp"
  30. #include "thorpipe.hpp"
  31. #include "thorfile.hpp"
  32. #include "eclhelper.hpp"
  33. #include "eclrtl_imp.hpp"
  34. #include "rtlfield_imp.hpp"
  35. #include "rtlds_imp.hpp"
  36. #include "rtlread_imp.hpp"
  37. #include "dafdesc.hpp"
  38. #include "dautils.hpp"
  39. #include "ftbase.ipp"
  40. namespace ccdserver_hqlhelper
  41. {
  42. #include "eclhelper_base.hpp"
  43. }
  44. #include "ccd.hpp"
  45. #include "ccdserver.hpp"
  46. #include "ccdcontext.hpp"
  47. #include "ccdactivities.hpp"
  48. #include "ccdquery.hpp"
  49. #include "ccdstate.hpp"
  50. #include "ccdqueue.ipp"
  51. #include "ccdsnmp.hpp"
  52. #include "ccddali.hpp"
  53. #include "jsmartsock.hpp"
  54. #include "dllserver.hpp"
  55. #include "workflow.hpp"
  56. #include "roxiemem.hpp"
  57. #include "roxierowbuff.hpp"
  58. #include "roxiehelper.hpp"
  59. #include "roxielmj.hpp"
  60. #include "roxierow.hpp"
  61. #include "thorplugin.hpp"
  62. #include "keybuild.hpp"
  63. #define MAX_HTTP_HEADERSIZE 8000
  64. #define MIN_PAYLOAD_SIZE 800
  65. #pragma warning(disable : 4355)
  66. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  67. #define PROBE
  68. #ifdef _DEBUG
  69. //#define FAKE_EXCEPTIONS
  70. //#define TRACE_JOINGROUPS
  71. //#define TRACE_SPLIT
  72. //#define _CHECK_HEAPSORT
  73. //#undef PARALLEL_EXECUTE
  74. //#define TRACE_SEEK_REQUESTS
  75. #endif
  76. using roxiemem::OwnedRoxieRow;
  77. using roxiemem::OwnedRoxieString;
  78. using roxiemem::OwnedConstRoxieRow;
  79. using roxiemem::IRowManager;
  80. // 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...
  81. #if _MSC_VER==1200
  82. #define protected public
  83. #endif
  84. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  85. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  86. inline void ReleaseRoxieRowSet(ConstPointerArray &data)
  87. {
  88. ForEachItemIn(idx, data)
  89. ReleaseRoxieRow(data.item(idx));
  90. data.kill();
  91. }
  92. //=================================================================================
  93. class RestartableThread : public CInterface
  94. {
  95. class MyThread : public Thread
  96. {
  97. Linked<RestartableThread> owner;
  98. public:
  99. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  100. {
  101. }
  102. virtual int run()
  103. {
  104. owner->started.signal();
  105. return owner->run();
  106. }
  107. };
  108. friend class MyThread;
  109. Semaphore started;
  110. Owned<MyThread> thread;
  111. CriticalSection crit;
  112. StringAttr name;
  113. public:
  114. RestartableThread(const char *_name) : name(_name)
  115. {
  116. }
  117. virtual void start(const char *namePrefix)
  118. {
  119. StringBuffer s(namePrefix);
  120. s.append(name);
  121. {
  122. CriticalBlock b(crit);
  123. assertex(!thread);
  124. thread.setown(new MyThread(this, s));
  125. thread->start();
  126. }
  127. started.wait();
  128. }
  129. virtual void join()
  130. {
  131. {
  132. Owned<Thread> tthread;
  133. {
  134. CriticalBlock b(crit);
  135. tthread.setown(thread.getClear());
  136. }
  137. if (tthread)
  138. tthread->join();
  139. }
  140. }
  141. virtual int run() = 0;
  142. };
  143. //================================================================================
  144. // default implementation - can be overridden for efficiency...
  145. bool IRoxieInput::nextGroup(ConstPointerArray & group)
  146. {
  147. // MORE - this should be replaced with a version that reads to a builder
  148. const void * next;
  149. while ((next = nextInGroup()) != NULL)
  150. group.append(next);
  151. if (group.ordinality())
  152. return true;
  153. return false;
  154. }
  155. void IRoxieInput::readAll(RtlLinkedDatasetBuilder &builder)
  156. {
  157. loop
  158. {
  159. const void *nextrec = nextInGroup();
  160. if (!nextrec)
  161. {
  162. nextrec = nextInGroup();
  163. if (!nextrec)
  164. break;
  165. builder.appendEOG();
  166. }
  167. builder.appendOwn(nextrec);
  168. }
  169. }
  170. inline const void * nextUngrouped(IRoxieInput * input)
  171. {
  172. const void * ret = input->nextInGroup();
  173. if (!ret)
  174. ret = input->nextInGroup();
  175. return ret;
  176. };
  177. //=================================================================================
  178. //The following don't link their arguments because that creates a circular reference
  179. //But I wish there was a better way
  180. class IndirectSlaveContext : public CInterface, implements IRoxieSlaveContext
  181. {
  182. public:
  183. IndirectSlaveContext(IRoxieSlaveContext * _ctx = NULL) : ctx(_ctx) {}
  184. IMPLEMENT_IINTERFACE
  185. void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  186. virtual ICodeContext *queryCodeContext()
  187. {
  188. return ctx->queryCodeContext();
  189. }
  190. virtual void checkAbort()
  191. {
  192. ctx->checkAbort();
  193. }
  194. virtual void notifyAbort(IException *E)
  195. {
  196. ctx->notifyAbort(E);
  197. }
  198. virtual IActivityGraph * queryChildGraph(unsigned id)
  199. {
  200. return ctx->queryChildGraph(id);
  201. }
  202. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  203. {
  204. ctx->noteChildGraph(id, childGraph) ;
  205. }
  206. virtual IRowManager &queryRowManager()
  207. {
  208. return ctx->queryRowManager();
  209. }
  210. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  211. {
  212. ctx->noteStatistic(kind, value);
  213. }
  214. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  215. {
  216. ctx->mergeStats(from);
  217. }
  218. virtual const CRuntimeStatisticCollection &queryStats() const
  219. {
  220. return ctx->queryStats();
  221. }
  222. virtual void CTXLOGva(const char *format, va_list args) const
  223. {
  224. ctx->CTXLOGva(format, args);
  225. }
  226. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  227. {
  228. ctx->CTXLOGa(category, prefix, text);
  229. }
  230. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  231. {
  232. ctx->logOperatorExceptionVA(E, file, line, format, args);
  233. }
  234. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  235. {
  236. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  237. }
  238. virtual void CTXLOGl(LogItem *log) const
  239. {
  240. ctx->CTXLOGl(log);
  241. }
  242. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  243. {
  244. return ctx->getLogPrefix(ret);
  245. }
  246. virtual unsigned queryTraceLevel() const
  247. {
  248. return ctx->queryTraceLevel();
  249. }
  250. virtual bool isIntercepted() const
  251. {
  252. return ctx->isIntercepted();
  253. }
  254. virtual bool isBlind() const
  255. {
  256. return ctx->isBlind();
  257. }
  258. virtual const QueryOptions &queryOptions() const
  259. {
  260. return ctx->queryOptions();
  261. }
  262. virtual void addSlavesReplyLen(unsigned len)
  263. {
  264. ctx->addSlavesReplyLen(len);
  265. }
  266. virtual const char *queryAuthToken()
  267. {
  268. return ctx->queryAuthToken();
  269. }
  270. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  271. {
  272. return ctx->resolveLFN(filename, isOpt);
  273. }
  274. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  275. {
  276. return ctx->createLFN(filename, overwrite, extend, clusters);
  277. }
  278. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  279. {
  280. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  281. }
  282. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  283. {
  284. return ctx->getLibraryGraph(extra, parentActivity);
  285. }
  286. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed) const
  287. {
  288. ctx->noteProcessed(subgraphId, activityId, _idx, _processed);
  289. }
  290. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  291. {
  292. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  293. }
  294. virtual IProbeManager *queryProbeManager() const
  295. {
  296. return ctx->queryProbeManager();
  297. }
  298. virtual IDebuggableContext *queryDebugContext() const
  299. {
  300. return ctx->queryDebugContext();
  301. }
  302. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  303. {
  304. ctx->printResults(output, name, sequence);
  305. }
  306. virtual void setWUState(WUState state)
  307. {
  308. ctx->setWUState(state);
  309. }
  310. virtual bool checkWuAborted()
  311. {
  312. return ctx->checkWuAborted();
  313. }
  314. virtual IWorkUnit *updateWorkUnit() const
  315. {
  316. return ctx->updateWorkUnit();
  317. }
  318. virtual IConstWorkUnit *queryWorkUnit() const
  319. {
  320. return ctx->queryWorkUnit();
  321. }
  322. virtual IRoxieServerContext *queryServerContext()
  323. {
  324. return ctx->queryServerContext();
  325. }
  326. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  327. {
  328. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  329. }
  330. protected:
  331. IRoxieSlaveContext * ctx;
  332. };
  333. //=================================================================================
  334. #define RESULT_FLUSH_THRESHOLD 10000u
  335. #ifdef _DEBUG
  336. #define SOAP_SPLIT_THRESHOLD 100u
  337. #define SOAP_SPLIT_RESERVE 200u
  338. #else
  339. #define SOAP_SPLIT_THRESHOLD 64000u
  340. #define SOAP_SPLIT_RESERVE 65535u
  341. #endif
  342. //=================================================================================
  343. // General activity statistics
  344. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  345. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StKindNone);
  346. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  347. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  348. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  349. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  350. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  351. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  352. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  353. StNumDiskRejected, StKindNone);
  354. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  355. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  356. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  357. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  358. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  359. StNumIndexRowsRead, StKindNone);
  360. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  361. StNumDiskRejected, StKindNone);
  362. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  363. //=================================================================================
  364. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  365. {
  366. protected:
  367. IntArray dependencies; // things I am dependent on
  368. IntArray dependencyIndexes; // things I am dependent on
  369. IntArray dependencyControlIds; // things I am dependent on
  370. StringArray dependencyEdgeIds; // How to describe them to the debugger
  371. unsigned dependentCount; // things dependent on me
  372. mutable CriticalSection statsCrit;
  373. mutable __int64 processed;
  374. mutable __int64 started;
  375. mutable __int64 totalCycles;
  376. mutable __int64 localCycles;
  377. public:
  378. IMPLEMENT_IINTERFACE;
  379. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  380. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  381. {
  382. processed = 0;
  383. started = 0;
  384. totalCycles = 0;
  385. localCycles = 0;
  386. dependentCount = 0;
  387. }
  388. ~CRoxieServerActivityFactoryBase()
  389. {
  390. }
  391. StringBuffer &toString(StringBuffer &ret) const
  392. {
  393. return ret.appendf("%p", this);
  394. }
  395. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  396. {
  397. dependencies.append(_source);
  398. dependencyIndexes.append(_sourceIdx);
  399. dependencyControlIds.append(controlId);
  400. dependencyEdgeIds.append(edgeId);
  401. }
  402. virtual void noteDependent(unsigned target)
  403. {
  404. dependentCount++;
  405. }
  406. virtual IntArray &queryDependencies() { return dependencies; }
  407. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  408. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  409. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  410. virtual unsigned queryId() const { return id; }
  411. virtual unsigned querySubgraphId() const { return subgraphId; }
  412. virtual ThorActivityKind getKind() const { return kind; }
  413. virtual IOutputMetaData * queryOutputMeta() const
  414. {
  415. return meta;
  416. }
  417. virtual bool isSink() const
  418. {
  419. return false;
  420. }
  421. virtual bool isFunction() const
  422. {
  423. return false;
  424. }
  425. virtual bool isGraphInvariant() const
  426. {
  427. return false;
  428. }
  429. virtual IHThorArg &getHelper() const
  430. {
  431. return *helperFactory();
  432. }
  433. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  434. {
  435. arg.Release();
  436. throwUnexpected();
  437. }
  438. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  439. {
  440. CActivityFactory::mergeStats(from);
  441. }
  442. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  443. {
  444. dbgassertex(!_idx);
  445. if (_processed)
  446. {
  447. CriticalBlock b(statsCrit);
  448. processed += processed;
  449. }
  450. }
  451. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  452. {
  453. if (_totalCycles.totalCycles || _localCycles)
  454. {
  455. CriticalBlock b(statsCrit);
  456. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  457. totalCycles += _totalCycles.totalCycles;
  458. localCycles += _localCycles;
  459. }
  460. CActivityFactory::mergeStats(fromStats);
  461. }
  462. virtual void noteStarted() const
  463. {
  464. CriticalBlock b(statsCrit);
  465. started ++;
  466. }
  467. virtual void noteStarted(unsigned idx) const
  468. {
  469. throwUnexpected(); // should be implemented/required by multiOutput cases only
  470. }
  471. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  472. {
  473. CriticalBlock b(statsCrit);
  474. if (output == 0)
  475. {
  476. putStatsValue(&edge, "count", "sum", processed);
  477. if (started)
  478. putStatsValue(&edge, "started", "sum", started);
  479. }
  480. else
  481. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  482. }
  483. virtual void getNodeProgressInfo(IPropertyTree &node) const
  484. {
  485. CActivityFactory::getNodeProgressInfo(node);
  486. CriticalBlock b(statsCrit);
  487. if (started)
  488. putStatsValue(&node, "_roxieStarted", "sum", started);
  489. if (totalCycles)
  490. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  491. if (localCycles)
  492. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  493. }
  494. virtual void resetNodeProgressInfo()
  495. {
  496. CActivityFactory::resetNodeProgressInfo();
  497. CriticalBlock b(statsCrit);
  498. processed = 0;
  499. started = 0;
  500. totalCycles = 0;
  501. localCycles = 0;
  502. }
  503. virtual void getActivityMetrics(StringBuffer &reply) const
  504. {
  505. CActivityFactory::getActivityMetrics(reply);
  506. CriticalBlock b(statsCrit);
  507. putStatsValue(reply, "_roxieStarted", "sum", started);
  508. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  509. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  510. }
  511. virtual unsigned __int64 queryLocalCycles() const
  512. {
  513. return localCycles;
  514. }
  515. virtual IQueryFactory &queryQueryFactory() const
  516. {
  517. return CActivityFactory::queryQueryFactory();
  518. }
  519. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  520. {
  521. return CActivityFactory::queryChildQuery(idx, id);
  522. }
  523. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  524. {
  525. CActivityFactory::addChildQuery(id, childQuery);
  526. }
  527. virtual void createChildQueries(IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx) const
  528. {
  529. ForEachItemIn(idx, childQueries)
  530. {
  531. childGraphs.append(*createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx));
  532. }
  533. }
  534. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs) const
  535. {
  536. ForEachItemIn(idx, childGraphs)
  537. {
  538. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  539. childGraphs.item(idx).onCreate(ctx, colocalArg);
  540. }
  541. }
  542. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  543. {
  544. unsigned match = childQueryIndexes.find(childId);
  545. assertex(match != NotFound);
  546. Owned<IActivityGraph> graph = createActivityGraph(NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx);
  547. graph->onCreate(ctx, colocalArg);
  548. return graph.getClear();
  549. }
  550. virtual IRoxieServerSideCache *queryServerSideCache() const
  551. {
  552. return NULL; // Activities that wish to support server-side caching will need to do better....
  553. }
  554. virtual bool getEnableFieldTranslation() const
  555. {
  556. throwUnexpected(); // only implemented by index-related subclasses
  557. }
  558. virtual IDefRecordMeta *queryActivityMeta() const
  559. {
  560. throwUnexpected(); // only implemented by index-related subclasses
  561. }
  562. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  563. {
  564. // Most activities have nothing to say...
  565. }
  566. virtual const StatisticsMapping &queryStatsMapping() const
  567. {
  568. return actStatistics; // Overridden by anyone that needs more
  569. }
  570. };
  571. class CRoxieServerMultiInputInfo
  572. {
  573. private:
  574. UnsignedArray inputs;
  575. UnsignedArray inputIndexes;
  576. public:
  577. void set(unsigned idx, unsigned source, unsigned sourceidx)
  578. {
  579. if (idx==inputs.length())
  580. {
  581. inputs.append(source);
  582. inputIndexes.append(sourceidx);
  583. }
  584. else
  585. {
  586. while (!inputs.isItem(idx))
  587. {
  588. inputs.append(0);
  589. inputIndexes.append(0);
  590. }
  591. inputs.replace(source, idx);
  592. inputIndexes.replace(sourceidx, idx);
  593. }
  594. }
  595. unsigned get(unsigned idx, unsigned &sourceidx) const
  596. {
  597. if (inputs.isItem(idx))
  598. {
  599. sourceidx = inputIndexes.item(idx);
  600. return inputs.item(idx);
  601. }
  602. else
  603. return (unsigned) -1;
  604. }
  605. inline unsigned ordinality() const { return inputs.ordinality(); }
  606. };
  607. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  608. {
  609. private:
  610. CRoxieServerMultiInputInfo inputs;
  611. public:
  612. IMPLEMENT_IINTERFACE;
  613. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  614. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  615. {
  616. }
  617. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  618. {
  619. inputs.set(idx, source, sourceidx);
  620. }
  621. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  622. {
  623. return inputs.get(idx, sourceidx);
  624. }
  625. virtual unsigned numInputs() const { return inputs.ordinality(); }
  626. };
  627. class CWrappedException : public CInterface, implements IException
  628. {
  629. Owned<IException> wrapped;
  630. ThorActivityKind kind;
  631. unsigned queryId;
  632. public:
  633. IMPLEMENT_IINTERFACE;
  634. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  635. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  636. {
  637. }
  638. virtual int errorCode() const { return wrapped->errorCode(); }
  639. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  640. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  641. };
  642. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  643. {
  644. protected:
  645. unsigned input;
  646. unsigned inputidx;
  647. public:
  648. IMPLEMENT_IINTERFACE;
  649. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  650. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  651. {
  652. input = (unsigned) -1;
  653. inputidx = 0;
  654. }
  655. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  656. {
  657. if (idx != 0)
  658. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  659. if (input != -1)
  660. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, __FILE__, __LINE__);
  661. input = source;
  662. inputidx = sourceidx;
  663. }
  664. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  665. {
  666. if (!idx)
  667. {
  668. sourceidx = inputidx;
  669. return input;
  670. }
  671. return (unsigned) -1;
  672. }
  673. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  674. };
  675. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  676. {
  677. protected:
  678. unsigned numOutputs;
  679. unsigned __int64 *processedArray;
  680. bool *startedArray;
  681. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  682. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  683. {
  684. numOutputs = 0;
  685. processedArray = NULL;
  686. startedArray = NULL;
  687. }
  688. ~CRoxieServerMultiOutputFactory()
  689. {
  690. delete [] processedArray;
  691. delete [] startedArray;
  692. }
  693. void setNumOutputs(unsigned num)
  694. {
  695. numOutputs = num;
  696. if (!num)
  697. num = 1; // Even sink activities like to track how many records they process
  698. processedArray = new unsigned __int64[num];
  699. startedArray = new bool[num];
  700. for (unsigned i = 0; i < num; i++)
  701. {
  702. processedArray[i] = 0;
  703. startedArray[i] = 0;
  704. }
  705. }
  706. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  707. {
  708. assertex(numOutputs ? idx < numOutputs : idx==0);
  709. CriticalBlock b(statsCrit);
  710. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  711. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  712. }
  713. virtual void resetNodeProgressInfo()
  714. {
  715. CRoxieServerActivityFactory::resetNodeProgressInfo();
  716. CriticalBlock b(statsCrit);
  717. for (unsigned i = 0; i < numOutputs; i++)
  718. {
  719. processedArray[i] = 0;
  720. startedArray[i] = 0;
  721. }
  722. }
  723. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  724. {
  725. assertex(numOutputs ? idx < numOutputs : idx==0);
  726. CriticalBlock b(statsCrit);
  727. processedArray[idx] += _processed;
  728. }
  729. virtual void noteStarted(unsigned idx) const
  730. {
  731. assertex(numOutputs ? idx < numOutputs : idx==0);
  732. CriticalBlock b(statsCrit);
  733. startedArray[idx] = true;
  734. }
  735. };
  736. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  737. {
  738. protected:
  739. bool isInternal;
  740. bool isRoot;
  741. unsigned usageCount;
  742. public:
  743. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  744. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  745. {
  746. usageCount = _usageCount;
  747. isRoot = _isRoot;
  748. isInternal = false; // filled in by derived class constructor
  749. }
  750. virtual bool isSink() const
  751. {
  752. //only a sink if a root activity
  753. 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?
  754. }
  755. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  756. {
  757. // 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
  758. // Just leave it blank is safest.
  759. }
  760. };
  761. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  762. const char *queryStateText(activityState state)
  763. {
  764. switch (state)
  765. {
  766. case STATEreset: return "reset";
  767. case STATEstarted: return "started";
  768. case STATEstopped: return "stopped";
  769. case STATEstarting: return "starting";
  770. default: return "unknown";
  771. }
  772. }
  773. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  774. class CParallelActivityExecutor : public CAsyncFor
  775. {
  776. public:
  777. unsigned parentExtractSize;
  778. const byte * parentExtract;
  779. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  780. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  781. void Do(unsigned i)
  782. {
  783. activities.item(i).execute(parentExtractSize, parentExtract);
  784. }
  785. private:
  786. IRoxieServerActivityCopyArray & activities;
  787. };
  788. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  789. {
  790. protected:
  791. IRoxieInput *input;
  792. IHThorArg &basehelper;
  793. IRoxieSlaveContext *ctx;
  794. const IRoxieServerActivityFactory *factory;
  795. IRoxieServerActivityCopyArray dependencies;
  796. IntArray dependencyIndexes;
  797. IntArray dependencyControlIds;
  798. IArrayOf<IActivityGraph> childGraphs;
  799. CachedOutputMetaData meta;
  800. IHThorArg *colocalParent;
  801. IEngineRowAllocator *rowAllocator;
  802. CriticalSection statecrit;
  803. mutable CRuntimeStatisticCollection stats;
  804. unsigned processed;
  805. ActivityTimeAccumulator totalCycles;
  806. cycle_t localCycles;
  807. unsigned activityId;
  808. activityState state;
  809. bool createPending;
  810. bool debugging;
  811. bool timeActivities;
  812. public:
  813. IMPLEMENT_IINTERFACE;
  814. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  815. : factory(_factory),
  816. basehelper(_factory->getHelper()),
  817. activityId(_factory->queryId()),
  818. stats(_factory ? factory->queryStatsMapping() : actStatistics)
  819. {
  820. input = NULL;
  821. ctx = NULL;
  822. meta.set(basehelper.queryOutputMeta());
  823. processed = 0;
  824. localCycles = 0;
  825. if (factory)
  826. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  827. state=STATEreset;
  828. rowAllocator = NULL;
  829. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  830. colocalParent = NULL;
  831. createPending = true;
  832. timeActivities = defaultTimeActivities;
  833. }
  834. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper), stats(allStatistics)
  835. {
  836. activityId = 0;
  837. input = NULL;
  838. ctx = NULL;
  839. meta.set(basehelper.queryOutputMeta());
  840. processed = 0;
  841. localCycles = 0;
  842. state=STATEreset;
  843. rowAllocator = NULL;
  844. debugging = false;
  845. colocalParent = NULL;
  846. createPending = true;
  847. timeActivities = defaultTimeActivities;
  848. }
  849. ~CRoxieServerActivity()
  850. {
  851. if (traceStartStop)
  852. {
  853. // There was an old comment here stating // Note- CTXLOG may not be safe
  854. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  855. // was released while activities still referenced it.
  856. // However these should now all be fixed
  857. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  858. if (watchActivityId && watchActivityId==activityId)
  859. {
  860. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  861. }
  862. }
  863. if (state!=STATEreset)
  864. {
  865. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  866. state = STATEreset; // bit pointless but there you go...
  867. }
  868. if (factory && !debugging)
  869. {
  870. if (processed)
  871. factory->noteProcessed(0, processed);
  872. factory->mergeActivityStats(stats, totalCycles, localCycles);
  873. }
  874. if (ctx)
  875. {
  876. if (processed)
  877. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed);
  878. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  879. }
  880. basehelper.Release();
  881. ::Release(rowAllocator);
  882. }
  883. virtual const IRoxieContextLogger &queryLogCtx()const
  884. {
  885. return *this;
  886. }
  887. virtual void mergeStats(MemoryBuffer &buf)
  888. {
  889. stats.deserializeMerge(buf);
  890. }
  891. inline void createRowAllocator()
  892. {
  893. if (!rowAllocator)
  894. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  895. }
  896. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  897. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  898. {
  899. if (ctx)
  900. ctx->CTXLOGa(category, prefix, text);
  901. else
  902. DBGLOG("[%s] %s", prefix, text);
  903. }
  904. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  905. {
  906. if (ctx)
  907. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  908. else
  909. {
  910. StringBuffer ss;
  911. ss.appendf("[%s] ERROR", prefix);
  912. if (E)
  913. ss.append(": ").append(E->errorCode());
  914. if (file)
  915. ss.appendf(": %s(%d) ", file, line);
  916. if (E)
  917. E->errorMessage(ss.append(": "));
  918. if (format)
  919. {
  920. ss.append(": ").valist_appendf(format, args);
  921. }
  922. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  923. }
  924. }
  925. virtual void CTXLOGl(LogItem *log) const
  926. {
  927. if (ctx)
  928. ctx->CTXLOGl(log);
  929. else
  930. {
  931. assert(ctx);
  932. log->Release(); // Should never happen
  933. }
  934. }
  935. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  936. {
  937. stats.addStatistic(kind, value);
  938. }
  939. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  940. {
  941. stats.merge(from);
  942. }
  943. virtual const CRuntimeStatisticCollection &queryStats() const
  944. {
  945. return stats;
  946. }
  947. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  948. {
  949. if (ctx)
  950. ctx->getLogPrefix(ret);
  951. return ret.append('@').append(activityId);
  952. }
  953. virtual bool isIntercepted() const
  954. {
  955. return ctx ? ctx->isIntercepted() : false;
  956. }
  957. virtual bool isBlind() const
  958. {
  959. return ctx ? ctx->isBlind() : blindLogging;
  960. }
  961. virtual unsigned queryTraceLevel() const
  962. {
  963. if (ctx)
  964. return ctx->queryTraceLevel();
  965. else
  966. return traceLevel;
  967. }
  968. virtual bool isPassThrough()
  969. {
  970. return false;
  971. }
  972. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  973. {
  974. return ctx->resolveLFN(filename, isOpt);
  975. }
  976. virtual const IResolvedFile *queryVarFileInfo() const
  977. {
  978. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  979. return NULL;
  980. }
  981. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  982. {
  983. throwUnexpected(); // should be implemented in more derived class wherever needed
  984. }
  985. virtual IRoxieSlaveContext *queryContext()
  986. {
  987. return ctx;
  988. }
  989. virtual IRoxieServerActivity *queryActivity() { return this; }
  990. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  991. virtual bool needsAllocator() const { return false; }
  992. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  993. {
  994. ctx = _ctx;
  995. colocalParent = _colocalParent;
  996. createPending = true;
  997. if (needsAllocator())
  998. createRowAllocator();
  999. processed = 0;
  1000. if (factory)
  1001. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  1002. if (ctx)
  1003. timeActivities = ctx->queryOptions().timeActivities;
  1004. }
  1005. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1006. {
  1007. //This should only be called after onStart has been called on the helper
  1008. assertex(!createPending);
  1009. assertex(state==STATEstarted);
  1010. unsigned startlen = out.length();
  1011. basehelper.serializeCreateContext(out);
  1012. basehelper.serializeStartContext(out);
  1013. if (queryTraceLevel() > 10)
  1014. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1015. }
  1016. virtual void serializeExtra(MemoryBuffer &out) {}
  1017. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1018. {
  1019. CriticalBlock cb(statecrit);
  1020. if (state != STATEreset && state != STATEstarting)
  1021. {
  1022. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1023. }
  1024. state=STATEstarted;
  1025. #ifdef TRACE_STARTSTOP
  1026. if (traceStartStop)
  1027. {
  1028. CTXLOG("start %p %d", this, activityId);
  1029. if (watchActivityId && watchActivityId==activityId)
  1030. {
  1031. CTXLOG("WATCH: start %p %d", this, activityId);
  1032. }
  1033. }
  1034. #endif
  1035. executeDependencies(parentExtractSize, parentExtract, 0);
  1036. if (input)
  1037. input->start(parentExtractSize, parentExtract, paused);
  1038. ensureCreated();
  1039. basehelper.onStart(parentExtract, NULL);
  1040. if (factory)
  1041. factory->noteStarted();
  1042. }
  1043. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1044. {
  1045. //MORE: Create a filtered list and then use asyncfor
  1046. ForEachItemIn(idx, dependencies)
  1047. {
  1048. if (dependencyControlIds.item(idx) == controlId)
  1049. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1050. }
  1051. }
  1052. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1053. {
  1054. ForEachItemIn(idx, dependencies)
  1055. {
  1056. if (dependencyControlIds.item(idx) == controlId)
  1057. dependencies.item(idx).stop(false);
  1058. }
  1059. }
  1060. virtual unsigned __int64 queryTotalCycles() const
  1061. {
  1062. return totalCycles.totalCycles;
  1063. }
  1064. virtual unsigned __int64 queryLocalCycles() const
  1065. {
  1066. __int64 ret = totalCycles.totalCycles;
  1067. if (input) ret -= input->queryTotalCycles();
  1068. if (ret < 0)
  1069. ret = 0;
  1070. return ret;
  1071. }
  1072. virtual IRoxieInput *queryInput(unsigned idx) const
  1073. {
  1074. if (idx==0)
  1075. return input;
  1076. else
  1077. return NULL;
  1078. }
  1079. inline void ensureCreated()
  1080. {
  1081. if (createPending)
  1082. {
  1083. createPending = false;
  1084. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1085. }
  1086. }
  1087. inline void stop(bool aborting)
  1088. {
  1089. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1090. if (state != STATEstopped)
  1091. {
  1092. CriticalBlock cb(statecrit);
  1093. if (state != STATEstopped)
  1094. {
  1095. #ifdef TRACE_STARTSTOP
  1096. if (traceStartStop)
  1097. {
  1098. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1099. if (watchActivityId && watchActivityId==activityId)
  1100. {
  1101. CTXLOG("WATCH: stop %p %d", this, activityId);
  1102. }
  1103. }
  1104. #endif
  1105. state=STATEstopped;
  1106. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1107. ForEachItemIn(idx, dependencies)
  1108. {
  1109. if (dependencyControlIds.item(idx) == 0)
  1110. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1111. }
  1112. if (input)
  1113. input->stop(aborting);
  1114. }
  1115. }
  1116. }
  1117. inline void reset()
  1118. {
  1119. if (state != STATEreset)
  1120. {
  1121. CriticalBlock cb(statecrit);
  1122. if (state != STATEreset)
  1123. {
  1124. if (state==STATEstarted || state==STATEstarting)
  1125. {
  1126. if (traceStartStop || traceLevel > 2)
  1127. CTXLOG("STATE: activity %d reset without stop", activityId);
  1128. stop(false);
  1129. }
  1130. state = STATEreset;
  1131. #ifdef TRACE_STARTSTOP
  1132. if (traceStartStop)
  1133. {
  1134. CTXLOG("reset %p %d", this, activityId);
  1135. if (watchActivityId && watchActivityId==activityId)
  1136. {
  1137. CTXLOG("WATCH: reset %p %d", this, activityId);
  1138. }
  1139. }
  1140. #endif
  1141. ForEachItemIn(idx, dependencies)
  1142. dependencies.item(idx).reset();
  1143. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1144. if (input)
  1145. input->reset();
  1146. }
  1147. }
  1148. }
  1149. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1150. {
  1151. dependencies.append(source);
  1152. dependencyIndexes.append(sourceIdx);
  1153. dependencyControlIds.append(controlId);
  1154. }
  1155. virtual void resetEOF()
  1156. {
  1157. //would make more sense if the default implementation (and eof member) were in the base class
  1158. }
  1159. // Sink activities should override this....
  1160. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1161. {
  1162. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1163. }
  1164. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1165. {
  1166. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1167. }
  1168. virtual void stopSink(unsigned idx)
  1169. {
  1170. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1171. }
  1172. virtual __int64 evaluate()
  1173. {
  1174. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1175. }
  1176. virtual IRoxieInput * querySelectOutput(unsigned id)
  1177. {
  1178. return NULL;
  1179. }
  1180. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1181. {
  1182. return false;
  1183. }
  1184. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1185. {
  1186. assertex(!idx);
  1187. input = _in;
  1188. }
  1189. virtual IRoxieInput *queryOutput(unsigned idx)
  1190. {
  1191. if (idx == (unsigned) -1)
  1192. idx = 0;
  1193. return idx ? NULL : this;
  1194. }
  1195. virtual IOutputMetaData *queryOutputMeta() const
  1196. {
  1197. return meta.queryOriginal();
  1198. }
  1199. virtual unsigned queryId() const
  1200. {
  1201. return activityId;
  1202. }
  1203. virtual unsigned querySubgraphId() const
  1204. {
  1205. return factory->querySubgraphId();
  1206. }
  1207. virtual void checkAbort()
  1208. {
  1209. ctx->checkAbort();
  1210. }
  1211. IException *makeWrappedException(IException *e)
  1212. {
  1213. StringBuffer msg;
  1214. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1215. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1216. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1217. return e;
  1218. else
  1219. return new CWrappedException(e, activityKind, activityId);
  1220. }
  1221. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1222. {
  1223. }
  1224. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1225. {
  1226. }
  1227. virtual void resetOutputsUsed()
  1228. {
  1229. }
  1230. virtual void noteOutputUsed()
  1231. {
  1232. }
  1233. virtual IRoxieServerSideCache *queryServerSideCache() const
  1234. {
  1235. return factory->queryServerSideCache();
  1236. }
  1237. virtual const IRoxieServerActivityFactory *queryFactory() const
  1238. {
  1239. return factory;
  1240. }
  1241. inline ThorActivityKind getKind() const
  1242. {
  1243. return factory->getKind();
  1244. }
  1245. inline bool isSink() const
  1246. {
  1247. return (factory != NULL) && factory->isSink();
  1248. }
  1249. };
  1250. //=====================================================================================================
  1251. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1252. {
  1253. protected:
  1254. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1255. bool prefiltered;
  1256. bool eof;
  1257. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1258. {
  1259. prefiltered = !any;
  1260. eof = prefiltered;
  1261. if (!prefiltered)
  1262. input->start(parentExtractSize, parentExtract, false);
  1263. else
  1264. {
  1265. if (traceStartStop)
  1266. CTXLOG("lateStart activity stopping input early as prefiltered");
  1267. input->stop(false);
  1268. }
  1269. }
  1270. public:
  1271. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1272. : CRoxieServerActivity(_factory, _probeManager)
  1273. {
  1274. input = NULL;
  1275. prefiltered = false;
  1276. eof = false;
  1277. }
  1278. virtual void stop(bool aborting)
  1279. {
  1280. if (!prefiltered)
  1281. {
  1282. input->stop(aborting);
  1283. }
  1284. else if (traceStartStop)
  1285. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1286. CRoxieServerActivity::stop(aborting);
  1287. }
  1288. virtual IRoxieInput *queryInput(unsigned idx) const
  1289. {
  1290. if (idx==0)
  1291. return input;
  1292. else
  1293. return NULL;
  1294. }
  1295. virtual void reset()
  1296. {
  1297. CRoxieServerActivity::reset();
  1298. input->reset();
  1299. prefiltered = false;
  1300. }
  1301. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1302. {
  1303. assertex(!idx);
  1304. input = _in;
  1305. }
  1306. };
  1307. //=====================================================================================================
  1308. atomic_t nextInstanceId;
  1309. extern unsigned getNextInstanceId()
  1310. {
  1311. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1312. }
  1313. atomic_t nextRuid;
  1314. ruid_t getNextRuid()
  1315. {
  1316. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1317. while (ret < RUID_FIRST)
  1318. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1319. return ret;
  1320. }
  1321. void setStartRuid(unsigned restarts)
  1322. {
  1323. atomic_set(&nextRuid, restarts * 0x10000);
  1324. atomic_set(&nextInstanceId, restarts * 10000);
  1325. }
  1326. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1327. class LimitSkipException : public CInterface, public IException
  1328. {
  1329. int code;
  1330. public:
  1331. LimitSkipException(int _code) { code = _code; }
  1332. IMPLEMENT_IINTERFACE;
  1333. virtual int errorCode() const { return code; }
  1334. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1335. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1336. };
  1337. IException *makeLimitSkipException(bool isKeyed)
  1338. {
  1339. // We need to make sure what we throw is IException not something derived from it....
  1340. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1341. }
  1342. //=================================================================================
  1343. interface IRecordPullerCallback : extends IExceptionHandler
  1344. {
  1345. virtual void processRow(const void *row) = 0;
  1346. virtual void processEOG() = 0;
  1347. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1348. virtual void processDone() = 0;
  1349. };
  1350. class RecordPullerThread : public RestartableThread
  1351. {
  1352. protected:
  1353. IRoxieInput *input;
  1354. IRecordPullerCallback *helper;
  1355. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1356. bool groupAtOnce, eof, eog;
  1357. CriticalSection crit;
  1358. public:
  1359. RecordPullerThread(bool _groupAtOnce)
  1360. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1361. {
  1362. input = NULL;
  1363. helper = NULL;
  1364. eof = eog = FALSE;
  1365. }
  1366. inline unsigned __int64 queryTotalCycles() const
  1367. {
  1368. return input->queryTotalCycles();
  1369. }
  1370. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1371. {
  1372. helper = _helper;
  1373. input = _input;
  1374. }
  1375. IRoxieInput *queryInput() const
  1376. {
  1377. return input;
  1378. }
  1379. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1380. {
  1381. eof = false;
  1382. eog = false;
  1383. input->start(parentExtractSize, parentExtract, paused);
  1384. try
  1385. {
  1386. if (preload && !paused)
  1387. {
  1388. if (traceLevel > 4)
  1389. DBGLOG("Preload fetching first %d records", preload);
  1390. if (groupAtOnce)
  1391. pullGroups(preload);
  1392. else
  1393. pullRecords(preload);
  1394. }
  1395. if (eof)
  1396. {
  1397. if (traceLevel > 4)
  1398. DBGLOG("No need to start puller after preload");
  1399. helper->processDone();
  1400. }
  1401. else
  1402. {
  1403. if (!noThread)
  1404. {
  1405. StringBuffer logPrefix("[");
  1406. if (ctx) ctx->getLogPrefix(logPrefix);
  1407. logPrefix.append("] ");
  1408. RestartableThread::start(logPrefix);
  1409. started.wait();
  1410. }
  1411. }
  1412. }
  1413. catch (IException *e)
  1414. {
  1415. helper->fireException(e);
  1416. }
  1417. catch (...)
  1418. {
  1419. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1420. }
  1421. }
  1422. void stop(bool aborting)
  1423. {
  1424. if (traceStartStop)
  1425. DBGLOG("RecordPullerThread::stop");
  1426. {
  1427. 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-nextInGroup etc etc.
  1428. input->stop(aborting);
  1429. }
  1430. RestartableThread::join();
  1431. }
  1432. void reset()
  1433. {
  1434. input->reset();
  1435. }
  1436. virtual int run()
  1437. {
  1438. started.signal();
  1439. try
  1440. {
  1441. if (groupAtOnce)
  1442. pullGroups((unsigned) -1);
  1443. else
  1444. pullRecords((unsigned) -1);
  1445. helper->processDone();
  1446. }
  1447. catch (IException *e)
  1448. {
  1449. helper->fireException(e);
  1450. }
  1451. catch (...)
  1452. {
  1453. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1454. }
  1455. return 0;
  1456. }
  1457. void done()
  1458. {
  1459. helper->processDone();
  1460. }
  1461. bool pullRecords(unsigned preload)
  1462. {
  1463. if (eof)
  1464. return false;
  1465. while (preload)
  1466. {
  1467. const void * row;
  1468. {
  1469. CriticalBlock c(crit); // See comments in stop for why this is needed
  1470. row = input->nextInGroup();
  1471. }
  1472. if (row)
  1473. {
  1474. eog = false;
  1475. helper->processRow(row);
  1476. }
  1477. else if (!eog)
  1478. {
  1479. helper->processEOG();
  1480. eog = true;
  1481. }
  1482. else
  1483. {
  1484. eof = true;
  1485. return false;
  1486. }
  1487. if (preload != (unsigned) -1)
  1488. preload--;
  1489. }
  1490. return true;
  1491. }
  1492. void pullGroups(unsigned preload)
  1493. {
  1494. ConstPointerArray thisGroup;
  1495. unsigned rowsDone = 0;
  1496. while (preload && !eof)
  1497. {
  1498. const void *row;
  1499. {
  1500. CriticalBlock c(crit);
  1501. row = input->nextInGroup();
  1502. }
  1503. if (row)
  1504. {
  1505. thisGroup.append(row);
  1506. rowsDone++;
  1507. }
  1508. else if (thisGroup.length())
  1509. {
  1510. helper->processGroup(thisGroup);
  1511. thisGroup.kill();
  1512. if (preload != (unsigned) -1)
  1513. {
  1514. if (preload > rowsDone)
  1515. preload -= rowsDone;
  1516. else
  1517. break;
  1518. }
  1519. rowsDone = 0;
  1520. }
  1521. else
  1522. {
  1523. eof = true;
  1524. break;
  1525. }
  1526. }
  1527. }
  1528. };
  1529. //=================================================================================
  1530. #define READAHEAD_SIZE 1000
  1531. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1532. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1533. {
  1534. QueueOf<const void, true> buffer;
  1535. InterruptableSemaphore ready;
  1536. InterruptableSemaphore space;
  1537. CriticalSection crit;
  1538. bool eof;
  1539. bool disabled;
  1540. RecordPullerThread puller;
  1541. unsigned preload;
  1542. cycle_t totalCycles;
  1543. IRoxieSlaveContext *ctx;
  1544. bool timeActivities;
  1545. public:
  1546. IMPLEMENT_IINTERFACE;
  1547. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1548. {
  1549. eof = false;
  1550. disabled = false;
  1551. ctx = NULL;
  1552. totalCycles = 0;
  1553. timeActivities = defaultTimeActivities;
  1554. }
  1555. void onCreate(IRoxieSlaveContext *_ctx)
  1556. {
  1557. ctx = _ctx;
  1558. disabled = (ctx->queryDebugContext() != NULL);
  1559. if (ctx)
  1560. timeActivities = ctx->queryOptions().timeActivities;
  1561. }
  1562. virtual IRoxieServerActivity *queryActivity()
  1563. {
  1564. return puller.queryInput()->queryActivity();
  1565. }
  1566. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1567. {
  1568. return puller.queryInput()->queryIndexReadActivity();
  1569. }
  1570. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1571. {
  1572. eof = false;
  1573. if (disabled)
  1574. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1575. else
  1576. {
  1577. space.reinit(READAHEAD_SIZE);
  1578. ready.reinit();
  1579. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1580. }
  1581. }
  1582. virtual void stop(bool aborting)
  1583. {
  1584. if (disabled)
  1585. puller.queryInput()->stop(aborting);
  1586. else
  1587. {
  1588. space.interrupt();
  1589. ready.interrupt();
  1590. puller.stop(aborting);
  1591. }
  1592. }
  1593. virtual void reset()
  1594. {
  1595. if (disabled)
  1596. puller.queryInput()->reset();
  1597. else
  1598. {
  1599. puller.reset();
  1600. ForEachItemIn(idx1, buffer)
  1601. ReleaseRoxieRow(buffer.item(idx1));
  1602. buffer.clear();
  1603. }
  1604. }
  1605. virtual void resetEOF()
  1606. {
  1607. throwUnexpected();
  1608. }
  1609. virtual IOutputMetaData * queryOutputMeta() const
  1610. {
  1611. return puller.queryInput()->queryOutputMeta();
  1612. }
  1613. virtual void checkAbort()
  1614. {
  1615. puller.queryInput()->checkAbort();
  1616. }
  1617. void setInput(unsigned idx, IRoxieInput *_in)
  1618. {
  1619. assertex(!idx);
  1620. puller.setInput(this, _in);
  1621. }
  1622. virtual unsigned __int64 queryTotalCycles() const
  1623. {
  1624. return totalCycles;
  1625. }
  1626. virtual unsigned __int64 queryLocalCycles() const
  1627. {
  1628. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1629. if (ret < 0) ret = 0;
  1630. return ret;
  1631. }
  1632. virtual IRoxieInput *queryInput(unsigned idx) const
  1633. {
  1634. return puller.queryInput()->queryInput(idx);
  1635. }
  1636. virtual const void * nextInGroup()
  1637. {
  1638. SimpleActivityTimer t(totalCycles, timeActivities);
  1639. if (disabled)
  1640. return puller.queryInput()->nextInGroup();
  1641. else
  1642. {
  1643. loop
  1644. {
  1645. {
  1646. CriticalBlock b(crit);
  1647. if (eof && !buffer.ordinality())
  1648. return NULL; // eof
  1649. }
  1650. ready.wait();
  1651. const void *ret;
  1652. {
  1653. CriticalBlock b(crit);
  1654. ret = buffer.dequeue();
  1655. }
  1656. space.signal();
  1657. return ret;
  1658. }
  1659. }
  1660. }
  1661. virtual unsigned queryId() const { throwUnexpected(); }
  1662. virtual bool fireException(IException *e)
  1663. {
  1664. // called from puller thread on failure
  1665. ready.interrupt(LINK(e));
  1666. space.interrupt(e);
  1667. return true;
  1668. }
  1669. virtual void processRow(const void *row)
  1670. {
  1671. {
  1672. CriticalBlock b(crit);
  1673. buffer.enqueue(row);
  1674. }
  1675. ready.signal();
  1676. space.wait();
  1677. }
  1678. virtual void processGroup(const ConstPointerArray &rows)
  1679. {
  1680. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1681. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1682. // if group was larger than max(space)
  1683. {
  1684. CriticalBlock b(crit);
  1685. ForEachItemIn(idx, rows)
  1686. buffer.enqueue(rows.item(idx));
  1687. buffer.enqueue(NULL);
  1688. }
  1689. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1690. {
  1691. ready.signal();
  1692. space.wait();
  1693. }
  1694. }
  1695. virtual void processEOG()
  1696. {
  1697. // Used when output is not grouped - just ignore
  1698. }
  1699. virtual void processDone()
  1700. {
  1701. CriticalBlock b(crit);
  1702. eof = true;
  1703. ready.signal();
  1704. }
  1705. };
  1706. //=================================================================================
  1707. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1708. {
  1709. protected:
  1710. IRoxieInput *input1;
  1711. Owned<CRoxieServerReadAheadInput> puller;
  1712. public:
  1713. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1714. : CRoxieServerActivity(_factory, _probeManager)
  1715. {
  1716. input1 = NULL;
  1717. }
  1718. ~CRoxieServerTwoInputActivity()
  1719. {
  1720. }
  1721. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1722. {
  1723. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1724. input1->start(parentExtractSize, parentExtract, paused);
  1725. }
  1726. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1727. {
  1728. if (puller)
  1729. puller->onCreate(_ctx);
  1730. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1731. }
  1732. virtual void stop(bool aborting)
  1733. {
  1734. input1->stop(aborting);
  1735. CRoxieServerActivity::stop(aborting);
  1736. }
  1737. virtual unsigned __int64 queryLocalCycles() const
  1738. {
  1739. __int64 ret;
  1740. __int64 inputCycles = input->queryTotalCycles();
  1741. __int64 input1Cycles = input1->queryTotalCycles();
  1742. if (puller)
  1743. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1744. else
  1745. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  1746. if (ret < 0)
  1747. ret = 0;
  1748. return ret;
  1749. }
  1750. virtual IRoxieInput *queryInput(unsigned idx) const
  1751. {
  1752. switch (idx)
  1753. {
  1754. case 0:
  1755. return input;
  1756. case 1:
  1757. return input1;
  1758. default:
  1759. return NULL;
  1760. }
  1761. }
  1762. virtual void reset()
  1763. {
  1764. CRoxieServerActivity::reset();
  1765. if (input1)
  1766. input1->reset();
  1767. }
  1768. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1769. {
  1770. switch(idx)
  1771. {
  1772. case 0:
  1773. input = _in;
  1774. break;
  1775. case 1:
  1776. input1 = _in;
  1777. break;
  1778. default:
  1779. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1780. }
  1781. }
  1782. };
  1783. //=================================================================================
  1784. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1785. {
  1786. protected:
  1787. unsigned numInputs;
  1788. IRoxieInput **inputArray;
  1789. public:
  1790. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1791. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1792. {
  1793. inputArray = new IRoxieInput*[numInputs];
  1794. for (unsigned i = 0; i < numInputs; i++)
  1795. inputArray[i] = NULL;
  1796. }
  1797. ~CRoxieServerMultiInputBaseActivity()
  1798. {
  1799. delete [] inputArray;
  1800. }
  1801. virtual unsigned __int64 queryLocalCycles() const
  1802. {
  1803. __int64 localCycles = totalCycles.totalCycles;
  1804. for (unsigned i = 0; i < numInputs; i++)
  1805. localCycles -= inputArray[i]->queryTotalCycles();
  1806. if (localCycles < 0)
  1807. localCycles = 0;
  1808. return localCycles;
  1809. }
  1810. virtual IRoxieInput *queryInput(unsigned idx) const
  1811. {
  1812. if (idx < numInputs)
  1813. return inputArray[idx];
  1814. else
  1815. return NULL;
  1816. }
  1817. virtual void reset()
  1818. {
  1819. for (unsigned i = 0; i < numInputs; i++)
  1820. inputArray[i]->reset();
  1821. CRoxieServerActivity::reset();
  1822. }
  1823. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1824. {
  1825. inputArray[idx] = _in;
  1826. }
  1827. };
  1828. //=================================================================================
  1829. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1830. {
  1831. public:
  1832. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1833. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1834. {
  1835. }
  1836. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1837. {
  1838. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1839. for (unsigned i = 0; i < numInputs; i++)
  1840. {
  1841. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1842. }
  1843. }
  1844. virtual void stop(bool aborting)
  1845. {
  1846. for (unsigned i = 0; i < numInputs; i++)
  1847. {
  1848. inputArray[i]->stop(aborting);
  1849. }
  1850. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1851. }
  1852. };
  1853. //=====================================================================================================
  1854. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1855. {
  1856. protected:
  1857. unsigned numOutputs;
  1858. bool executed;
  1859. bool *stopped;
  1860. CriticalSection ecrit;
  1861. Owned<IException> exception;
  1862. public:
  1863. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  1864. : CRoxieServerActivity(_factory, _probeManager), numOutputs(_numOutputs)
  1865. {
  1866. executed = false;
  1867. stopped = new bool[numOutputs];
  1868. for (unsigned s = 0; s < numOutputs; s++)
  1869. stopped[s] = false;
  1870. }
  1871. ~CRoxieServerInternalSinkActivity()
  1872. {
  1873. delete [] stopped;
  1874. }
  1875. virtual void reset()
  1876. {
  1877. for (unsigned s = 0; s < numOutputs; s++)
  1878. stopped[s] = false;
  1879. executed = false;
  1880. exception.clear();
  1881. CRoxieServerActivity::reset();
  1882. }
  1883. virtual IRoxieInput *queryOutput(unsigned idx)
  1884. {
  1885. return NULL;
  1886. }
  1887. virtual void stopSink(unsigned outputIdx)
  1888. {
  1889. if (!stopped[outputIdx])
  1890. {
  1891. stopped[outputIdx] = true;
  1892. for (unsigned s = 0; s < numOutputs; s++)
  1893. if (!stopped[s])
  1894. return;
  1895. stop(false); // all outputs stopped - stop parent.
  1896. }
  1897. }
  1898. virtual const void *nextInGroup()
  1899. {
  1900. throwUnexpected(); // I am nobody's input
  1901. }
  1902. virtual void onExecute() = 0;
  1903. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1904. {
  1905. CriticalBlock b(ecrit);
  1906. if (exception)
  1907. throw exception.getLink();
  1908. if (!executed)
  1909. {
  1910. try
  1911. {
  1912. start(parentExtractSize, parentExtract, false);
  1913. {
  1914. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  1915. onExecute();
  1916. }
  1917. stop(false);
  1918. executed = true;
  1919. }
  1920. catch (IException *E)
  1921. {
  1922. exception.set(E); // (or maybe makeWrappedException?)
  1923. stop(true);
  1924. throw;
  1925. }
  1926. catch (...)
  1927. {
  1928. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1929. stop(true);
  1930. throw;
  1931. }
  1932. }
  1933. }
  1934. };
  1935. //=================================================================================
  1936. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1937. {
  1938. protected:
  1939. Owned<IMessageResult> result;
  1940. Owned<IRoxieQueryPacket> packet;
  1941. Linked<IRoxieServerQueryPacket> continuation;
  1942. unsigned hash;
  1943. unsigned seq;
  1944. unsigned lastDebugSequence;
  1945. Owned<IRoxieQueryPacket> lastDebugResponse;
  1946. ILRUChain *prev;
  1947. ILRUChain *next;
  1948. bool delayed;
  1949. public:
  1950. IMPLEMENT_IINTERFACE;
  1951. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1952. {
  1953. hash = 0;
  1954. seq = 0;
  1955. prev = NULL;
  1956. next = NULL;
  1957. delayed = false;
  1958. lastDebugSequence = 0;
  1959. }
  1960. virtual IRoxieQueryPacket *queryPacket() const
  1961. {
  1962. return packet;
  1963. }
  1964. virtual bool isContinuation() const
  1965. {
  1966. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1967. }
  1968. virtual bool isDelayed() const
  1969. {
  1970. return delayed;
  1971. }
  1972. virtual bool isEnd() const
  1973. {
  1974. return false;
  1975. }
  1976. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1977. {
  1978. return false;
  1979. }
  1980. virtual bool hasResult() const
  1981. {
  1982. return result != NULL;
  1983. }
  1984. virtual bool hasContinuation() const
  1985. {
  1986. return continuation != NULL;
  1987. }
  1988. virtual void setDelayed(bool _delayed)
  1989. {
  1990. delayed = _delayed;
  1991. }
  1992. virtual void setPacket(IRoxieQueryPacket *_packet)
  1993. {
  1994. packet.setown(_packet);
  1995. }
  1996. virtual void setSequence(unsigned _seq)
  1997. {
  1998. assertex(!IsShared());
  1999. seq = _seq;
  2000. }
  2001. virtual unsigned getSequence() const
  2002. {
  2003. return seq;
  2004. }
  2005. IMessageResult *getResult()
  2006. {
  2007. return result.getLink();
  2008. }
  2009. IMessageResult *queryResult()
  2010. {
  2011. return result;
  2012. }
  2013. void setResult(IMessageResult *r)
  2014. {
  2015. result.setown(r);
  2016. }
  2017. IRoxieServerQueryPacket *queryContinuation()
  2018. {
  2019. return continuation;
  2020. }
  2021. void setContinuation(IRoxieServerQueryPacket *c)
  2022. {
  2023. continuation.setown(c);
  2024. }
  2025. virtual unsigned queryHash() const
  2026. {
  2027. return hash;
  2028. }
  2029. virtual void setHash(unsigned _hash)
  2030. {
  2031. hash = _hash;
  2032. }
  2033. virtual ILRUChain *queryPrev() const { return prev; }
  2034. virtual ILRUChain *queryNext() const { return next; }
  2035. virtual void setPrev(ILRUChain *p) { prev = p; }
  2036. virtual void setNext(ILRUChain *n) { next = n; }
  2037. virtual void unchain()
  2038. {
  2039. if (prev && next)
  2040. {
  2041. prev->setNext(next);
  2042. next->setPrev(prev);
  2043. }
  2044. next = NULL;
  2045. prev = NULL;
  2046. }
  2047. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2048. {
  2049. if (sequence == lastDebugSequence)
  2050. return lastDebugResponse.getLink();
  2051. else if (sequence > lastDebugSequence)
  2052. {
  2053. lastDebugResponse.clear();
  2054. return NULL;
  2055. }
  2056. else
  2057. throwUnexpected();
  2058. }
  2059. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2060. {
  2061. lastDebugSequence = sequence;
  2062. lastDebugResponse.set(response);
  2063. }
  2064. };
  2065. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2066. {
  2067. public:
  2068. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2069. {
  2070. }
  2071. virtual bool isEnd() const
  2072. {
  2073. return true;
  2074. }
  2075. };
  2076. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2077. {
  2078. unsigned __int64 rowLimit;
  2079. unsigned __int64 keyedLimit;
  2080. unsigned __int64 stopAfter;
  2081. public:
  2082. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2083. {
  2084. rowLimit = _rowLimit;
  2085. keyedLimit = _keyedLimit;
  2086. stopAfter = _stopAfter;
  2087. }
  2088. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2089. {
  2090. _rowLimit = rowLimit;
  2091. _keyedLimit = keyedLimit;
  2092. _stopAfter = stopAfter;
  2093. return true;
  2094. }
  2095. };
  2096. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2097. {
  2098. protected:
  2099. unsigned cacheTableSize;
  2100. unsigned cacheTableSpace;
  2101. IRoxieServerQueryPacket **cacheTable;
  2102. mutable ILRUChain *prev;
  2103. mutable ILRUChain *next;
  2104. mutable CriticalSection crit;
  2105. virtual ILRUChain *queryPrev() const { return prev; }
  2106. virtual ILRUChain *queryNext() const { return next; }
  2107. virtual void setPrev(ILRUChain *p) { prev = p; }
  2108. virtual void setNext(ILRUChain *n) { next = n; }
  2109. virtual void unchain()
  2110. {
  2111. prev->setNext(next);
  2112. next->setPrev(prev);
  2113. next = NULL;
  2114. prev = NULL;
  2115. }
  2116. void moveToHead(IRoxieServerQueryPacket *mru)
  2117. {
  2118. mru->unchain();
  2119. mru->setNext(next);
  2120. next->setPrev(mru);
  2121. mru->setPrev(this);
  2122. next = mru;
  2123. }
  2124. IRoxieServerQueryPacket *removeLRU()
  2125. {
  2126. if (next==this)
  2127. assertex(next != this);
  2128. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2129. goer->unchain(); // NOTE - this will modify the value of next
  2130. return goer;
  2131. }
  2132. void removeEntry(IRoxieServerQueryPacket *goer)
  2133. {
  2134. unsigned v = goer->queryHash() % cacheTableSize;
  2135. loop
  2136. {
  2137. IRoxieServerQueryPacket *found = cacheTable[v];
  2138. assertex(found);
  2139. if (found == goer)
  2140. {
  2141. cacheTable[v] = NULL;
  2142. unsigned vn = v;
  2143. loop
  2144. {
  2145. vn++;
  2146. if (vn==cacheTableSize) vn = 0;
  2147. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2148. if (!found2)
  2149. break;
  2150. unsigned vm = found2->queryHash() % cacheTableSize;
  2151. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2152. {
  2153. cacheTable[v] = found2;
  2154. v = vn;
  2155. cacheTable[v] = NULL;
  2156. }
  2157. }
  2158. cacheTableSpace++;
  2159. break;
  2160. }
  2161. v++;
  2162. if (v==cacheTableSize)
  2163. v = 0;
  2164. }
  2165. goer->Release();
  2166. }
  2167. public:
  2168. CRoxieServerSideCache(unsigned _cacheSize)
  2169. {
  2170. cacheTableSize = (_cacheSize*4)/3;
  2171. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2172. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2173. cacheTableSpace = _cacheSize;
  2174. prev = this;
  2175. next = this;
  2176. }
  2177. ~CRoxieServerSideCache()
  2178. {
  2179. for (unsigned i = 0; i < cacheTableSize; i++)
  2180. {
  2181. ::Release(cacheTable[i]);
  2182. }
  2183. delete [] cacheTable;
  2184. }
  2185. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2186. {
  2187. unsigned hash = p->hash();
  2188. unsigned et = hash % cacheTableSize;
  2189. if (traceServerSideCache)
  2190. {
  2191. StringBuffer s;
  2192. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2193. }
  2194. CriticalBlock b(crit);
  2195. loop
  2196. {
  2197. IRoxieServerQueryPacket *found = cacheTable[et];
  2198. if (!found)
  2199. return NULL;
  2200. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2201. {
  2202. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2203. if (traceServerSideCache)
  2204. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2205. logctx.noteStatistic(StNumServerCacheHits, 1);
  2206. return NULL;
  2207. // 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....
  2208. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2209. //ret->setResult(found->getResult());
  2210. //return ret;
  2211. }
  2212. et++;
  2213. if (et == cacheTableSize)
  2214. et = 0;
  2215. }
  2216. }
  2217. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2218. {
  2219. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2220. {
  2221. unsigned hash = out->queryPacket()->hash();
  2222. out->setHash(hash);
  2223. unsigned et = hash % cacheTableSize;
  2224. if (traceServerSideCache)
  2225. {
  2226. StringBuffer s;
  2227. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2228. }
  2229. CriticalBlock b(crit);
  2230. loop
  2231. {
  2232. IRoxieServerQueryPacket *found = cacheTable[et];
  2233. if (!found)
  2234. {
  2235. if (cacheTableSpace)
  2236. {
  2237. out->setResult(LINK(in));
  2238. cacheTable[et] = LINK(out);
  2239. cacheTableSpace--;
  2240. moveToHead(out);
  2241. break;
  2242. }
  2243. else
  2244. {
  2245. IRoxieServerQueryPacket *goer = removeLRU();
  2246. removeEntry(goer);
  2247. et = hash % cacheTableSize;
  2248. continue;
  2249. }
  2250. }
  2251. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2252. {
  2253. moveToHead(found);
  2254. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2255. // multiple copies of a slave query are in-flight at once.
  2256. }
  2257. et++;
  2258. if (et == cacheTableSize)
  2259. et = 0;
  2260. }
  2261. }
  2262. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2263. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2264. }
  2265. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2266. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2267. // more than make up for it
  2268. };
  2269. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2270. {
  2271. ConstPointerArray &data;
  2272. Linked<IMessageResult> result;
  2273. public:
  2274. IMPLEMENT_IINTERFACE;
  2275. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2276. : data(_data), result(_result)
  2277. {
  2278. }
  2279. virtual bool atEOF() const
  2280. {
  2281. return data.length()==0;
  2282. }
  2283. virtual bool isSerialized() const
  2284. {
  2285. return false;
  2286. }
  2287. virtual const void * getNext(int length)
  2288. {
  2289. if (!data.length())
  2290. return NULL;
  2291. const void *ret = data.item(0);
  2292. data.remove(0);
  2293. return ret;
  2294. }
  2295. };
  2296. // MORE - should possibly move more over to the lazy version used in indexread?
  2297. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2298. {
  2299. ConstPointerArray data;
  2300. IRowManager &rowManager;
  2301. bool variableSize;
  2302. public:
  2303. IMPLEMENT_IINTERFACE;
  2304. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2305. {
  2306. }
  2307. ~CRowArrayMessageResult()
  2308. {
  2309. ReleaseRoxieRowSet(data);
  2310. }
  2311. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2312. {
  2313. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2314. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2315. }
  2316. virtual const void *getMessageHeader(unsigned &length) const
  2317. {
  2318. throwUnexpected(); // should never get called - I don't have a header available
  2319. length = 0;
  2320. return NULL;
  2321. }
  2322. virtual const void *getMessageMetadata(unsigned &length) const
  2323. {
  2324. length = 0;
  2325. return NULL;
  2326. }
  2327. virtual void discard() const
  2328. {
  2329. throwUnexpected();
  2330. }
  2331. void append(const void *row)
  2332. {
  2333. data.append(row);
  2334. }
  2335. };
  2336. void throwRemoteException(IMessageUnpackCursor *extra)
  2337. {
  2338. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2339. if (rowlen)
  2340. {
  2341. char *xml = (char *) extra->getNext(*rowlen);
  2342. ReleaseRoxieRow(rowlen);
  2343. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2344. ReleaseRoxieRow(xml);
  2345. unsigned code = p->getPropInt("Code", 0);
  2346. const char *msg = p->queryProp("Message");
  2347. if (!msg)
  2348. msg = xml;
  2349. throw MakeStringException(code, "%s", msg);
  2350. }
  2351. throwUnexpected();
  2352. }
  2353. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2354. {
  2355. friend class CRemoteResultMerger;
  2356. class CRemoteResultMerger
  2357. {
  2358. class HeapEntry : public CInterface
  2359. {
  2360. private:
  2361. CRemoteResultAdaptor &adaptor;
  2362. IMessageUnpackCursor *cursor;
  2363. public:
  2364. const void *current;
  2365. bool isLast;
  2366. bool lastIsComplete;
  2367. IRoxieServerQueryPacket *packet;
  2368. unsigned seq;
  2369. public:
  2370. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2371. {
  2372. cursor = _cursor;
  2373. lastIsComplete = _lastIsComplete;
  2374. return next();
  2375. }
  2376. public:
  2377. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2378. {
  2379. cursor = NULL;
  2380. current = NULL;
  2381. isLast = false;
  2382. lastIsComplete = true;
  2383. }
  2384. ~HeapEntry()
  2385. {
  2386. ::Release(packet);
  2387. ::Release(cursor);
  2388. ReleaseRoxieRow(current);
  2389. }
  2390. bool isCompleteMatch() const
  2391. {
  2392. if (!isLast || lastIsComplete)
  2393. return true;
  2394. else
  2395. return false;
  2396. }
  2397. const void *next()
  2398. {
  2399. if (cursor)
  2400. {
  2401. ReleaseClearRoxieRow(current);
  2402. current = adaptor.getRow(cursor);
  2403. isLast = cursor->atEOF();
  2404. if (!current)
  2405. {
  2406. cursor->Release();
  2407. cursor = NULL;
  2408. }
  2409. }
  2410. return current;
  2411. }
  2412. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2413. {
  2414. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2415. unsigned skipped = 0;
  2416. loop
  2417. {
  2418. int c = compare->docompare(current, seek, numFields);
  2419. //If larger than the seek values, then we may be allowed to return an inexact match,
  2420. //if equal then it is required to be an exact match,
  2421. if (c > 0)
  2422. {
  2423. if (!requireExactMatch || isCompleteMatch())
  2424. break;
  2425. }
  2426. else if ((c == 0) && isCompleteMatch())
  2427. break;
  2428. skipped++;
  2429. if (!next())
  2430. break;
  2431. }
  2432. return skipped;
  2433. }
  2434. };
  2435. CRemoteResultAdaptor &adaptor;
  2436. CIArrayOf<HeapEntry> heapEntries;
  2437. UnsignedArray heap;
  2438. IRowManager *rowManager;
  2439. unsigned numPending;
  2440. unsigned numFields;
  2441. bool endSeen;
  2442. bool remakePending;
  2443. IRangeCompare *compare;
  2444. bool deferredContinuation;
  2445. inline int doCompare(unsigned l, unsigned r)
  2446. {
  2447. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2448. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2449. return ret;
  2450. }
  2451. void makeHeap()
  2452. {
  2453. /* Permute blocks to establish the heap property
  2454. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2455. The children of p must both be greater than or equal to p
  2456. The parent of a child c is given by p = (c-1)/2
  2457. */
  2458. unsigned i;
  2459. unsigned n = heap.length();
  2460. unsigned *s = heap.getArray();
  2461. for (i=1; i<n; i++)
  2462. {
  2463. unsigned r = s[i];
  2464. int c = i; /* child */
  2465. while (c > 0)
  2466. {
  2467. int p = (c-1)/2; /* parent */
  2468. if ( doCompare( s[c], s[p] ) >= 0 )
  2469. break;
  2470. s[c] = s[p];
  2471. s[p] = r;
  2472. c = p;
  2473. }
  2474. }
  2475. remakePending = false;
  2476. }
  2477. void remakeHeap()
  2478. {
  2479. /* The row associated with block[0] will have changed
  2480. This code restores the heap property
  2481. */
  2482. unsigned p = 0; /* parent */
  2483. unsigned n = heap.length();
  2484. unsigned *s = heap.getArray();
  2485. while (1)
  2486. {
  2487. unsigned c = p*2 + 1; /* child */
  2488. if ( c >= n )
  2489. break;
  2490. /* Select smaller child */
  2491. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2492. /* If child is greater or equal than parent then we are done */
  2493. if ( doCompare( s[c], s[p] ) >= 0 )
  2494. break;
  2495. /* Swap parent and child */
  2496. unsigned r = s[c];
  2497. s[c] = s[p];
  2498. s[p] = r;
  2499. /* child becomes parent */
  2500. p = c;
  2501. }
  2502. remakePending = false;
  2503. }
  2504. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2505. {
  2506. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2507. IMessageResult *result = p->queryResult();
  2508. assertex(result);
  2509. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2510. {
  2511. heapEntries.append(h);
  2512. heap.append(heap.ordinality());
  2513. }
  2514. else
  2515. h.Release();
  2516. }
  2517. void removeHeap(unsigned idx)
  2518. {
  2519. heapEntries.remove(idx);
  2520. ForEachItemIn(i, heap)
  2521. {
  2522. unsigned v = heap.item(i);
  2523. assertex(v != idx);
  2524. if (v > idx)
  2525. heap.replace(v-1, i);
  2526. }
  2527. }
  2528. bool isCompleteMatchFlag(IMessageResult *result)
  2529. {
  2530. unsigned metaLen;
  2531. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2532. if (metaLen)
  2533. {
  2534. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2535. if (continuationLen >= sizeof(bool))
  2536. {
  2537. metaInfo += sizeof(unsigned short);
  2538. return *(bool *) metaInfo;
  2539. }
  2540. }
  2541. return true; // if no continuation info, last row was complete.
  2542. }
  2543. public:
  2544. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2545. {
  2546. init(NULL, NULL);
  2547. }
  2548. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2549. {
  2550. if (meta)
  2551. {
  2552. numFields = meta->getNumFields();
  2553. compare = meta->queryCompare();
  2554. }
  2555. else
  2556. {
  2557. numFields = 0;
  2558. compare = NULL;
  2559. }
  2560. rowManager = _rowManager;
  2561. numPending = 0;
  2562. endSeen = false;
  2563. remakePending = false;
  2564. deferredContinuation = false;
  2565. }
  2566. void reset()
  2567. {
  2568. heapEntries.kill();
  2569. heap.kill();
  2570. numPending = 0;
  2571. endSeen = false;
  2572. remakePending = false;
  2573. deferredContinuation = false;
  2574. }
  2575. inline bool noteEndSeen()
  2576. {
  2577. bool hadSeen = endSeen;
  2578. if (!endSeen)
  2579. makeHeap();
  2580. endSeen = true;
  2581. return !hadSeen;
  2582. }
  2583. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2584. {
  2585. if (!p->isContinuation())
  2586. append(p, seq);
  2587. else
  2588. {
  2589. ForEachItemIn(idx, heapEntries)
  2590. {
  2591. HeapEntry &h = heapEntries.item(idx);
  2592. if (h.packet == p)
  2593. {
  2594. IMessageResult *result = p->queryResult();
  2595. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2596. {
  2597. heap.zap(idx);
  2598. removeHeap(idx);
  2599. }
  2600. numPending--;
  2601. if (!numPending)
  2602. makeHeap();
  2603. return;
  2604. }
  2605. }
  2606. }
  2607. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2608. return;
  2609. }
  2610. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2611. {
  2612. HeapEntry &entry = heapEntries.item(idx);
  2613. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2614. if (!entry.current)
  2615. {
  2616. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2617. if (continuation)
  2618. {
  2619. continuation->Link();
  2620. entry.packet->Release();
  2621. entry.packet = continuation;
  2622. if (continuation->hasResult())
  2623. {
  2624. IMessageResult *result = continuation->queryResult();
  2625. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2626. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2627. }
  2628. else
  2629. {
  2630. if (continuation->isDelayed())
  2631. {
  2632. continuation->setDelayed(false);
  2633. MemoryBuffer serializedSkip;
  2634. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2635. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2636. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2637. adaptor.sentsome.signal();
  2638. }
  2639. numPending++;
  2640. }
  2641. }
  2642. else
  2643. {
  2644. heap.zap(idx);
  2645. removeHeap(idx);
  2646. idx--;
  2647. }
  2648. }
  2649. return skipped;
  2650. }
  2651. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2652. {
  2653. // We discard all rows < seekval from all entries in heap
  2654. // If this results in additional slave requests, we return NULL so that we can wait for them
  2655. // If not, we rebuild the heap (if any were skipped) and return the first row
  2656. deferredContinuation = false;
  2657. if (heap.length())
  2658. {
  2659. unsigned skipped = 0;
  2660. unsigned idx = 0;
  2661. while(heapEntries.isItem(idx))
  2662. {
  2663. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2664. idx++;
  2665. }
  2666. if (numPending)
  2667. return NULL; // can't answer yet, need more results from slaves
  2668. else
  2669. {
  2670. if (skipped)
  2671. makeHeap();
  2672. return next(wasCompleteMatch, stepExtra);
  2673. }
  2674. }
  2675. else
  2676. return NULL;
  2677. }
  2678. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2679. {
  2680. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2681. if (continuation)
  2682. {
  2683. if (continuation->isDelayed() && canDefer)
  2684. {
  2685. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2686. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2687. deferredContinuation = true;
  2688. }
  2689. else
  2690. {
  2691. deferredContinuation = false;
  2692. continuation->Link();
  2693. topEntry.packet->Release();
  2694. topEntry.packet = continuation;
  2695. if (continuation->hasResult())
  2696. {
  2697. IMessageResult *result = continuation->queryResult();
  2698. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2699. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2700. }
  2701. else
  2702. {
  2703. if (continuation->isDelayed()) // has the continuation been requested yet?
  2704. {
  2705. continuation->Link();
  2706. topEntry.packet->Release();
  2707. topEntry.packet = continuation;
  2708. continuation->setDelayed(false);
  2709. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2710. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2711. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2712. adaptor.sentsome.signal();
  2713. }
  2714. numPending++; // we are waiting for one that is already in flight
  2715. }
  2716. }
  2717. return true; // next not known yet
  2718. }
  2719. else
  2720. return false;
  2721. }
  2722. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2723. {
  2724. OwnedConstRoxieRow ret;
  2725. if (heap.length())
  2726. {
  2727. if (deferredContinuation)
  2728. {
  2729. unsigned top = heap.item(0);
  2730. HeapEntry &topEntry = heapEntries.item(top);
  2731. doContinuation(topEntry, false);
  2732. return NULL;
  2733. }
  2734. if (remakePending)
  2735. remakeHeap();
  2736. unsigned top = heap.item(0);
  2737. HeapEntry &topEntry = heapEntries.item(top);
  2738. ret.set(topEntry.current);
  2739. wasCompleteMatch = topEntry.isCompleteMatch();
  2740. const void *next = topEntry.next();
  2741. if (!next)
  2742. {
  2743. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2744. {
  2745. unsigned last = heap.popGet();
  2746. if (heap.length())
  2747. heap.replace(last, 0);
  2748. removeHeap(top);
  2749. }
  2750. }
  2751. remakePending = true;
  2752. }
  2753. return ret.getClear();
  2754. }
  2755. bool ready()
  2756. {
  2757. return endSeen && numPending == 0;
  2758. }
  2759. };
  2760. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2761. {
  2762. if (serverSideCache && !debugContext)
  2763. {
  2764. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2765. if (ret)
  2766. {
  2767. p->Release();
  2768. cached = true;
  2769. return ret;
  2770. }
  2771. }
  2772. cached = false;
  2773. return new CRoxieServerQueryPacket(p);
  2774. }
  2775. #ifdef _DEBUG
  2776. void dumpPending()
  2777. {
  2778. CriticalBlock b(pendingCrit);
  2779. ForEachItemIn(idx, pending)
  2780. {
  2781. IRoxieServerQueryPacket &p = pending.item(idx);
  2782. StringBuffer s;
  2783. unsigned __int64 dummy;
  2784. if (p.isEnd())
  2785. s.append("END");
  2786. else if (p.isLimit(dummy, dummy, dummy))
  2787. s.append("LIMIT");
  2788. else
  2789. {
  2790. IRoxieQueryPacket *i = p.queryPacket();
  2791. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2792. if (i)
  2793. {
  2794. RoxiePacketHeader &header = i->queryHeader();
  2795. header.toString(s);
  2796. }
  2797. }
  2798. DBGLOG("Pending %d %s", idx, s.str());
  2799. }
  2800. }
  2801. #endif
  2802. void abortPending()
  2803. {
  2804. CriticalBlock b(pendingCrit);
  2805. ForEachItemIn(idx, pending)
  2806. {
  2807. IRoxieServerQueryPacket &p = pending.item(idx);
  2808. if (!p.hasResult())
  2809. {
  2810. IRoxieQueryPacket *i = p.queryPacket();
  2811. if (i)
  2812. {
  2813. RoxiePacketHeader &header = i->queryHeader();
  2814. ROQ->sendAbort(header, activity.queryLogCtx());
  2815. }
  2816. }
  2817. }
  2818. pending.kill();
  2819. }
  2820. void checkDelayed()
  2821. {
  2822. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2823. {
  2824. bool allDelayed = true;
  2825. CriticalBlock b(pendingCrit);
  2826. unsigned sendIdx = (unsigned) -1;
  2827. ForEachItemIn(idx, pending)
  2828. {
  2829. IRoxieServerQueryPacket &p = pending.item(idx);
  2830. if (p.queryPacket())
  2831. {
  2832. if (p.isDelayed())
  2833. {
  2834. if (sendIdx == (unsigned) -1)
  2835. sendIdx = idx;
  2836. }
  2837. else if (!p.hasResult())
  2838. {
  2839. allDelayed = false;
  2840. break;
  2841. }
  2842. }
  2843. }
  2844. if (allDelayed && sendIdx != (unsigned) -1)
  2845. {
  2846. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2847. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2848. pending.item(sendIdx).setDelayed(false);
  2849. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2850. sentsome.signal();
  2851. }
  2852. }
  2853. else if (deferredStart)
  2854. {
  2855. CriticalBlock b(pendingCrit);
  2856. ForEachItemIn(idx, pending)
  2857. {
  2858. IRoxieServerQueryPacket &p = pending.item(idx);
  2859. if (p.isDelayed())
  2860. {
  2861. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2862. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2863. p.setDelayed(false);
  2864. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2865. sentsome.signal();
  2866. }
  2867. }
  2868. deferredStart = false;
  2869. }
  2870. }
  2871. void retryPending()
  2872. {
  2873. CriticalBlock b(pendingCrit);
  2874. checkDelayed();
  2875. ForEachItemIn(idx, pending)
  2876. {
  2877. IRoxieServerQueryPacket &p = pending.item(idx);
  2878. if (!p.hasResult() && !p.isDelayed())
  2879. {
  2880. IRoxieQueryPacket *i = p.queryPacket();
  2881. if (i)
  2882. {
  2883. if (!i->queryHeader().retry())
  2884. {
  2885. StringBuffer s;
  2886. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2887. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2888. throw E;
  2889. }
  2890. if (!localSlave)
  2891. {
  2892. ROQ->sendPacket(i, activity.queryLogCtx());
  2893. atomic_inc(&retriesSent);
  2894. }
  2895. }
  2896. }
  2897. }
  2898. }
  2899. class ChannelBuffer
  2900. {
  2901. protected:
  2902. unsigned bufferLeft;
  2903. MemoryBuffer buffer;
  2904. char *nextBuf;
  2905. unsigned overflowSequence;
  2906. unsigned channel; // == bonded channel
  2907. bool needsFlush;
  2908. InterruptableSemaphore flowController;
  2909. const CRemoteResultAdaptor &owner;
  2910. CriticalSection crit;
  2911. public:
  2912. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2913. {
  2914. overflowSequence = 0;
  2915. needsFlush = false;
  2916. bufferLeft = 0;
  2917. nextBuf = NULL;
  2918. }
  2919. void init(unsigned minSize)
  2920. {
  2921. assertex(!buffer.length());
  2922. if (minSize < MIN_PAYLOAD_SIZE)
  2923. minSize = MIN_PAYLOAD_SIZE;
  2924. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2925. unsigned bufferSize = headerSize+minSize;
  2926. if (bufferSize < mtu_size)
  2927. bufferSize = mtu_size;
  2928. buffer.reserveTruncate(bufferSize);
  2929. bufferLeft = bufferSize - headerSize;
  2930. assertex(buffer.toByteArray());
  2931. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2932. needsFlush = false;
  2933. }
  2934. inline IRoxieQueryPacket *flush()
  2935. {
  2936. CriticalBlock cb(crit);
  2937. Owned<IRoxieQueryPacket> ret;
  2938. if (needsFlush)
  2939. {
  2940. buffer.setLength(nextBuf - buffer.toByteArray());
  2941. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2942. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2943. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2944. byte * tgt = (byte*)(h+1);
  2945. owner.copyHeader(tgt, channel);
  2946. ret.setown(createRoxiePacket(buffer));
  2947. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2948. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2949. else
  2950. overflowSequence++;
  2951. needsFlush = false;
  2952. bufferLeft = 0;
  2953. if (owner.flowControlled)
  2954. {
  2955. CriticalUnblock cub(crit);
  2956. while (!flowController.wait(1000))
  2957. {
  2958. StringBuffer s;
  2959. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2960. }
  2961. }
  2962. }
  2963. return ret.getClear();
  2964. }
  2965. inline void signal()
  2966. {
  2967. if (owner.flowControlled)
  2968. flowController.signal();
  2969. }
  2970. inline void interrupt(IException *e)
  2971. {
  2972. flowController.interrupt(e);
  2973. }
  2974. inline void *getBuffer(unsigned size)
  2975. {
  2976. CriticalBlock cb(crit);
  2977. if (bufferLeft >= size)
  2978. {
  2979. needsFlush = true;
  2980. void * ret = nextBuf;
  2981. nextBuf += size;
  2982. bufferLeft -= size;
  2983. return ret;
  2984. }
  2985. else if (!needsFlush)
  2986. {
  2987. init(size);
  2988. return getBuffer(size);
  2989. }
  2990. else if (owner.mergeOrder)
  2991. {
  2992. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2993. }
  2994. else
  2995. return NULL; // will force it to flush and start a new packet
  2996. }
  2997. };
  2998. private:
  2999. friend class CRemoteResultMerger;
  3000. bool allread;
  3001. bool contextCached;
  3002. bool preserveOrder;
  3003. InterruptableSemaphore sentsome;
  3004. Owned <IMessageCollator> mc;
  3005. Owned<IMessageUnpackCursor> mu;
  3006. Owned<IMessageResult> mr;
  3007. ChannelBuffer **buffers;
  3008. IHThorArg &helper;
  3009. unsigned __int64 stopAfter;
  3010. unsigned resendSequence;
  3011. IHThorArg *colocalArg;
  3012. IArrayOf<IRoxieServerQueryPacket> pending;
  3013. CriticalSection pendingCrit;
  3014. IRoxieServerSideCache *serverSideCache;
  3015. unsigned sentSequence;
  3016. Owned<IOutputRowDeserializer> deserializer;
  3017. Owned<IEngineRowAllocator> rowAllocator;
  3018. CRemoteResultMerger merger;
  3019. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3020. MemoryBuffer tempRowBuffer;
  3021. Owned<ISerialStream> bufferStream;
  3022. CThorStreamDeserializerSource rowSource;
  3023. protected:
  3024. IRowManager *rowManager;
  3025. IRoxieInput *owner;
  3026. unsigned __int64 rowLimit;
  3027. unsigned __int64 keyedLimit;
  3028. IRoxieServerErrorHandler *errorHandler;
  3029. CachedOutputMetaData meta;
  3030. public:
  3031. ISteppingMeta *mergeOrder;
  3032. IRoxieSlaveContext *ctx;
  3033. IDebuggableContext *debugContext;
  3034. IRoxieServerActivity &activity;
  3035. unsigned parentExtractSize;
  3036. const byte * parentExtract;
  3037. bool flowControlled;
  3038. bool deferredStart;
  3039. MemoryBuffer logInfo;
  3040. MemoryBuffer cachedContext;
  3041. const RemoteActivityId &remoteId;
  3042. ruid_t ruid;
  3043. mutable CriticalSection buffersCrit;
  3044. unsigned processed;
  3045. cycle_t totalCycles;
  3046. bool timeActivities;
  3047. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3048. const void *getRow(IMessageUnpackCursor *mu)
  3049. {
  3050. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3051. return mu->getNext(meta.getFixedSize());
  3052. else
  3053. {
  3054. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3055. if (rowlen)
  3056. {
  3057. RecordLengthType len = *rowlen;
  3058. ReleaseRoxieRow(rowlen);
  3059. const void *slaveRec = mu->getNext(len);
  3060. if (deserializer && mu->isSerialized())
  3061. {
  3062. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3063. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3064. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3065. ReleaseRoxieRow(slaveRec);
  3066. return rowBuilder.finalizeRowClear(outsize);
  3067. }
  3068. else
  3069. return slaveRec;
  3070. }
  3071. else
  3072. return NULL;
  3073. }
  3074. }
  3075. private:
  3076. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3077. {
  3078. CriticalBlock cb(buffersCrit);
  3079. ChannelBuffer *b = buffers[channel];
  3080. if (!b && force)
  3081. {
  3082. if (!contextCached)
  3083. {
  3084. logInfo.clear();
  3085. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3086. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3087. const QueryOptions &options = ctx->queryOptions();
  3088. if (activity.queryLogCtx().isIntercepted())
  3089. loggingFlags |= LOGGING_INTERCEPTED;
  3090. if (options.timeActivities)
  3091. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3092. if (activity.queryLogCtx().isBlind())
  3093. loggingFlags |= LOGGING_BLIND;
  3094. if (options.checkingHeap)
  3095. loggingFlags |= LOGGING_CHECKINGHEAP;
  3096. if (ctx->queryWorkUnit())
  3097. loggingFlags |= LOGGING_WUID;
  3098. if (debugContext)
  3099. {
  3100. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3101. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3102. MemoryBuffer bpInfo;
  3103. debugContext->serialize(bpInfo);
  3104. bpInfo.append((__uint64)(memsize_t) &activity);
  3105. logInfo.append((unsigned short) bpInfo.length());
  3106. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3107. }
  3108. else
  3109. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3110. StringBuffer logPrefix;
  3111. activity.queryLogCtx().getLogPrefix(logPrefix);
  3112. logInfo.append(logPrefix);
  3113. activity.serializeCreateStartContext(cachedContext.clear());
  3114. activity.serializeExtra(cachedContext);
  3115. if (activity.queryVarFileInfo())
  3116. {
  3117. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3118. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3119. }
  3120. contextCached = true;
  3121. }
  3122. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3123. }
  3124. return b;
  3125. }
  3126. void processRow(const void *got)
  3127. {
  3128. processed++;
  3129. if (processed > rowLimit)
  3130. {
  3131. ReleaseRoxieRow(got);
  3132. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3133. throwUnexpected();
  3134. }
  3135. else if (processed > keyedLimit)
  3136. {
  3137. ReleaseRoxieRow(got);
  3138. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3139. throwUnexpected();
  3140. }
  3141. }
  3142. public:
  3143. IMPLEMENT_IINTERFACE;
  3144. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3145. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3146. {
  3147. rowLimit = (unsigned __int64) -1;
  3148. keyedLimit = (unsigned __int64) -1;
  3149. contextCached = false;
  3150. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3151. buffers = new ChannelBuffer*[numChannels+1];
  3152. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3153. parentExtractSize = 0;
  3154. parentExtract = NULL;
  3155. debugContext = NULL;
  3156. owner = NULL;
  3157. mergeOrder = NULL;
  3158. deferredStart = false;
  3159. processed = 0;
  3160. sentSequence = 0;
  3161. resendSequence = 0;
  3162. totalCycles = 0;
  3163. serverSideCache = activity.queryServerSideCache();
  3164. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3165. rowSource.setStream(bufferStream);
  3166. timeActivities = defaultTimeActivities;
  3167. }
  3168. ~CRemoteResultAdaptor()
  3169. {
  3170. if (mc)
  3171. {
  3172. ROQ->queryReceiveManager()->detachCollator(mc);
  3173. mc.clear();
  3174. }
  3175. for (unsigned channel = 0; channel <= numChannels; channel++)
  3176. {
  3177. delete(buffers[channel]);
  3178. }
  3179. delete [] buffers;
  3180. }
  3181. void setMeta(IOutputMetaData *newmeta)
  3182. {
  3183. meta.set(newmeta);
  3184. }
  3185. virtual IRoxieServerActivity *queryActivity()
  3186. {
  3187. return &activity;
  3188. }
  3189. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3190. {
  3191. return NULL;
  3192. }
  3193. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3194. {
  3195. mergeOrder = _mergeOrder;
  3196. deferredStart = true;
  3197. }
  3198. void send(IRoxieQueryPacket *p)
  3199. {
  3200. if (p)
  3201. {
  3202. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3203. assertex(p->queryHeader().uid==ruid);
  3204. // MORE: Maybe we should base the fastlane flag on some other
  3205. // criteria !! (i.e A Roxie server prediction based on the
  3206. // activity type/activity behaviour/expected reply size .. etc).
  3207. //
  3208. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3209. // But this could still cause too many reply packets on the fatlane
  3210. // (higher priority output Q), which may cause the activities on the
  3211. // low priority output Q to not get service on time.
  3212. if ((colocalArg == 0) && // not a child query activity??
  3213. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3214. (p->queryHeader().overflowSequence == 0) &&
  3215. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3216. p->queryHeader().retries |= ROXIE_FASTLANE;
  3217. if (p->queryHeader().channel)
  3218. {
  3219. bool cached = false;
  3220. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3221. if (deferredStart)
  3222. rsqp->setDelayed(true);
  3223. rsqp->setSequence(sentSequence++);
  3224. {
  3225. CriticalBlock b(pendingCrit);
  3226. pending.append(*rsqp);
  3227. }
  3228. if (!deferredStart)
  3229. {
  3230. if (!cached)
  3231. ROQ->sendPacket(p, activity.queryLogCtx());
  3232. sentsome.signal();
  3233. }
  3234. }
  3235. else
  3236. {
  3237. // 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
  3238. // Need to add first, then send
  3239. unsigned i;
  3240. bool allCached = true;
  3241. for (i = 1; i <= numChannels; i++)
  3242. {
  3243. IRoxieQueryPacket *q = p->clonePacket(i);
  3244. bool thisChannelCached;
  3245. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3246. if (!thisChannelCached)
  3247. allCached = false;
  3248. rsqp->setSequence(sentSequence++);
  3249. if (deferredStart)
  3250. {
  3251. rsqp->setDelayed(true);
  3252. }
  3253. {
  3254. CriticalBlock b(pendingCrit);
  3255. pending.append(*rsqp);
  3256. }
  3257. if (!deferredStart)
  3258. sentsome.signal();
  3259. }
  3260. if (!allCached && !deferredStart)
  3261. ROQ->sendPacket(p, activity.queryLogCtx());
  3262. buffers[0]->signal(); // since replies won't come back on that channel...
  3263. p->Release();
  3264. }
  3265. }
  3266. }
  3267. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3268. {
  3269. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3270. size += sizeof(PartNoType);
  3271. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3272. char *buffer = (char *) b->getBuffer(size);
  3273. if (!buffer)
  3274. {
  3275. send(b->flush());
  3276. buffer = (char *) b->getBuffer(size);
  3277. }
  3278. PartNoType sp;
  3279. sp.partNo = partNo;
  3280. sp.fileNo = fileNo;
  3281. memcpy(buffer, &sp, sizeof(sp));
  3282. buffer += sizeof(sp);
  3283. return buffer;
  3284. }
  3285. void injectResult(IMessageResult *result)
  3286. {
  3287. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3288. f->setSequence(sentSequence++);
  3289. f->setResult(result);
  3290. CriticalBlock b(pendingCrit);
  3291. pending.append(*f);
  3292. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3293. }
  3294. void flush()
  3295. {
  3296. for (unsigned channel = 0; channel <= numChannels; channel++)
  3297. {
  3298. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3299. if (b)
  3300. send(b->flush());
  3301. }
  3302. }
  3303. void interruptBuffers(IException *e)
  3304. {
  3305. for (unsigned channel = 0; channel <= numChannels; channel++)
  3306. {
  3307. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3308. if (b)
  3309. b->interrupt(LINK(e));
  3310. }
  3311. }
  3312. void senddone()
  3313. {
  3314. CriticalBlock b(pendingCrit);
  3315. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3316. sentsome.signal();
  3317. }
  3318. bool fireException(IException *e)
  3319. {
  3320. {
  3321. CriticalBlock b(pendingCrit);
  3322. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3323. }
  3324. interruptBuffers(e);
  3325. if (mc)
  3326. mc->interrupt(LINK(e));
  3327. sentsome.interrupt(e);
  3328. return true;
  3329. }
  3330. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3331. {
  3332. owner = _owner;
  3333. errorHandler = _errorHandler;
  3334. ctx = _ctx;
  3335. debugContext = ctx->queryDebugContext();
  3336. colocalArg = _colocalArg;
  3337. if (meta.needsSerializeDisk())
  3338. {
  3339. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3340. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3341. }
  3342. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3343. deferredStart = true;
  3344. if (ctx)
  3345. timeActivities = ctx->queryOptions().timeActivities;
  3346. }
  3347. virtual unsigned queryId() const
  3348. {
  3349. return owner->queryId();
  3350. }
  3351. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3352. {
  3353. #ifdef TRACE_STARTSTOP
  3354. if (traceStartStop)
  3355. activity.queryLogCtx().CTXLOG("RRAonstart");
  3356. #endif
  3357. sentsome.reinit();
  3358. ruid = getNextRuid();
  3359. rowManager = &ctx->queryRowManager();
  3360. if (mergeOrder)
  3361. merger.init(mergeOrder, rowManager);
  3362. if (mc)
  3363. {
  3364. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3365. }
  3366. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3367. allread = false;
  3368. mu.clear();
  3369. contextCached = false;
  3370. processed = 0;
  3371. resendSequence = 0;
  3372. sentSequence = 0;
  3373. for (unsigned channel = 0; channel <= numChannels; channel++)
  3374. {
  3375. delete(buffers[channel]);
  3376. buffers[channel] = NULL;
  3377. }
  3378. flush();
  3379. parentExtractSize = _parentExtractSize;
  3380. parentExtract = _parentExtract;
  3381. }
  3382. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3383. {
  3384. #ifdef TRACE_STARTSTOP
  3385. if (traceStartStop)
  3386. activity.queryLogCtx().CTXLOG("RRAstart");
  3387. #endif
  3388. owner->start(parentExtractSize, parentExtract, paused);
  3389. }
  3390. void checkAbort()
  3391. {
  3392. owner->checkAbort();
  3393. }
  3394. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3395. {
  3396. if (ctx->queryProbeManager())
  3397. {
  3398. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3399. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3400. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3401. }
  3402. {
  3403. CriticalBlock b(pendingCrit);
  3404. if (pending.length())
  3405. {
  3406. #ifdef _DEBUG
  3407. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3408. #endif
  3409. assertex(pending.length()==0);
  3410. }
  3411. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3412. }
  3413. sentsome.signal();
  3414. rowLimit = _rowLimit;
  3415. keyedLimit = _keyedLimit;
  3416. stopAfter = _stopAfter;
  3417. }
  3418. virtual void stop(bool aborting)
  3419. {
  3420. #ifdef TRACE_STARTSTOP
  3421. if (traceStartStop)
  3422. activity.queryLogCtx().CTXLOG("RRAstop");
  3423. #endif
  3424. onStop(aborting);
  3425. owner->stop(aborting);
  3426. }
  3427. void onStop(bool aborting)
  3428. {
  3429. #ifdef TRACE_STARTSTOP
  3430. if (traceStartStop)
  3431. activity.queryLogCtx().CTXLOG("RRAonstop");
  3432. #endif
  3433. abortPending();
  3434. interruptBuffers(NULL);
  3435. sentsome.interrupt();
  3436. if (mc) // May not be set if start() chain threw exception
  3437. mc->interrupt();
  3438. }
  3439. virtual void reset()
  3440. {
  3441. #ifdef TRACE_STARTSTOP
  3442. if (traceStartStop)
  3443. activity.queryLogCtx().CTXLOG("RRAreset");
  3444. #endif
  3445. owner->reset();
  3446. onReset();
  3447. }
  3448. virtual void resetEOF()
  3449. {
  3450. throwUnexpected();
  3451. }
  3452. virtual void onReset()
  3453. {
  3454. #ifdef TRACE_STARTSTOP
  3455. if (traceStartStop)
  3456. activity.queryLogCtx().CTXLOG("RRAonreset");
  3457. #endif
  3458. if (mc)
  3459. ROQ->queryReceiveManager()->detachCollator(mc);
  3460. merger.reset();
  3461. pending.kill();
  3462. if (mc && ctx)
  3463. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3464. mc.clear(); // Or we won't free memory for graphs that get recreated
  3465. mu.clear(); //ditto
  3466. deferredStart = false;
  3467. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3468. }
  3469. virtual IOutputMetaData * queryOutputMeta() const
  3470. {
  3471. return helper.queryOutputMeta();
  3472. }
  3473. virtual unsigned __int64 queryTotalCycles() const
  3474. {
  3475. return totalCycles;
  3476. }
  3477. virtual unsigned __int64 queryLocalCycles() const
  3478. {
  3479. return owner->queryLocalCycles();
  3480. }
  3481. virtual IRoxieInput *queryInput(unsigned idx) const
  3482. {
  3483. return owner->queryInput(idx);
  3484. }
  3485. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3486. {
  3487. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3488. {
  3489. StringBuffer recstr;
  3490. unsigned i;
  3491. for (i = 0; i < seekLen; i++)
  3492. {
  3493. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3494. }
  3495. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3496. }
  3497. assertex(mergeOrder);
  3498. if (deferredStart)
  3499. {
  3500. CriticalBlock b(pendingCrit);
  3501. ForEachItemIn(idx, pending)
  3502. {
  3503. IRoxieServerQueryPacket &p = pending.item(idx);
  3504. if (p.isDelayed())
  3505. {
  3506. p.setDelayed(false);
  3507. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3508. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3509. MemoryBuffer serializedSkip;
  3510. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3511. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3512. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3513. sentsome.signal();
  3514. }
  3515. }
  3516. deferredStart = false;
  3517. }
  3518. SimpleActivityTimer t(totalCycles, timeActivities);
  3519. if (processed==stopAfter)
  3520. return NULL;
  3521. if (allread)
  3522. return NULL;
  3523. loop
  3524. {
  3525. if (merger.ready())
  3526. {
  3527. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3528. if (got)
  3529. {
  3530. processRow(got);
  3531. return got;
  3532. }
  3533. }
  3534. if (!reload()) // MORE - should pass the seek info here...
  3535. return NULL;
  3536. }
  3537. }
  3538. virtual const void *nextInGroup()
  3539. {
  3540. // If we are merging then we need to do a heapsort on all
  3541. SimpleActivityTimer t(totalCycles, timeActivities);
  3542. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3543. {
  3544. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3545. }
  3546. loop
  3547. {
  3548. checkDelayed();
  3549. if (processed==stopAfter)
  3550. return NULL;
  3551. if (allread)
  3552. return NULL;
  3553. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3554. const void *got = NULL;
  3555. if (mergeOrder && merger.ready())
  3556. {
  3557. bool matched = true;
  3558. got = merger.next(matched, dummySmartStepExtra);
  3559. }
  3560. else if (mu)
  3561. got = getRow(mu);
  3562. if (got)
  3563. {
  3564. processRow(got);
  3565. return got;
  3566. }
  3567. if (!reload())
  3568. return NULL;
  3569. }
  3570. }
  3571. bool reload()
  3572. {
  3573. // Wait for something to be returned from a slave....
  3574. mu.clear();
  3575. sentsome.wait();
  3576. // must be at least an endMarker on the queue since sentsome was signalled
  3577. {
  3578. CriticalBlock b(pendingCrit);
  3579. IRoxieServerQueryPacket &top = pending.item(0);
  3580. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3581. {
  3582. pending.remove(0);
  3583. return true;
  3584. }
  3585. else if (top.isEnd())
  3586. {
  3587. pending.remove(0);
  3588. allread = true;
  3589. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3590. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3591. return false;
  3592. }
  3593. else if (mergeOrder)
  3594. {
  3595. unsigned idx = 0;
  3596. bool added = false;
  3597. while (pending.isItem(idx))
  3598. {
  3599. IRoxieServerQueryPacket &item = pending.item(idx);
  3600. if (item.isEnd())
  3601. {
  3602. if (merger.noteEndSeen())
  3603. {
  3604. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3605. added = true;
  3606. }
  3607. break;
  3608. }
  3609. else if (item.hasResult())
  3610. {
  3611. merger.noteResult(&item, item.getSequence());
  3612. pending.remove(idx);
  3613. added = true;
  3614. }
  3615. else if (item.isContinuation())
  3616. idx++;
  3617. else
  3618. break;
  3619. }
  3620. if (added)
  3621. return true;
  3622. }
  3623. else if (top.hasResult())
  3624. {
  3625. mr.setown(pending.item(0).getResult());
  3626. mu.setown(mr->getCursor(rowManager));
  3627. pending.remove(0);
  3628. return true;
  3629. }
  3630. }
  3631. getNextUnpacker();
  3632. return true;
  3633. }
  3634. void getNextUnpacker()
  3635. {
  3636. mu.clear();
  3637. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3638. loop
  3639. {
  3640. checkDelayed();
  3641. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3642. owner->checkAbort();
  3643. bool anyActivity;
  3644. if (ctxTraceLevel > 5)
  3645. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3646. mr.setown(mc->getNextResult(timeout, anyActivity));
  3647. if (ctxTraceLevel > 6)
  3648. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3649. owner->checkAbort();
  3650. if (mr)
  3651. {
  3652. unsigned roxieHeaderLen;
  3653. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3654. #ifdef _DEBUG
  3655. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3656. #endif
  3657. if (ctxTraceLevel > 5)
  3658. {
  3659. StringBuffer s;
  3660. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3661. }
  3662. CriticalBlock b(pendingCrit);
  3663. unsigned idx = 0;
  3664. IRoxieServerQueryPacket *original = NULL;
  3665. IRoxieQueryPacket *op;
  3666. while (pending.isItem(idx))
  3667. {
  3668. original = &pending.item(idx);
  3669. op = original->queryPacket();
  3670. if (op && header.matchPacket(op->queryHeader()))
  3671. break;
  3672. original = NULL;
  3673. idx++;
  3674. }
  3675. if (!original || original->hasResult())
  3676. {
  3677. switch (header.activityId)
  3678. {
  3679. case ROXIE_FILECALLBACK:
  3680. {
  3681. // tell slave to abort
  3682. //if (ctxTraceLevel > 5)
  3683. {
  3684. StringBuffer s;
  3685. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3686. }
  3687. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3688. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3689. if (len)
  3690. {
  3691. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3692. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3693. const char *rowdata = (const char *) row.get();
  3694. // bool isOpt = * (bool *) rowdata;
  3695. // bool isLocal = * (bool *) (rowdata+1);
  3696. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3697. }
  3698. else
  3699. throwUnexpected();
  3700. break;
  3701. }
  3702. // MORE - ROXIE_ALIVE perhaps should go here too
  3703. default:
  3704. if (ctxTraceLevel > 3)
  3705. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3706. mr->discard();
  3707. break;
  3708. }
  3709. mr.clear();
  3710. }
  3711. else
  3712. {
  3713. atomic_inc(&resultsReceived);
  3714. switch (header.activityId)
  3715. {
  3716. case ROXIE_DEBUGCALLBACK:
  3717. {
  3718. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3719. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3720. if (len)
  3721. {
  3722. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3723. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3724. char *rowdata = (char *) row.get();
  3725. if (ctxTraceLevel > 5)
  3726. {
  3727. StringBuffer s;
  3728. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3729. }
  3730. MemoryBuffer slaveInfo;
  3731. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3732. unsigned debugSequence;
  3733. slaveInfo.read(debugSequence);
  3734. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3735. if (!reply)
  3736. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3737. if (reply)
  3738. {
  3739. original->setDebugResponse(debugSequence, reply);
  3740. ROQ->sendPacket(reply, activity.queryLogCtx());
  3741. }
  3742. }
  3743. else
  3744. throwUnexpected();
  3745. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3746. // Leave original message on pending queue in original location - this is not a reply to it.
  3747. break;
  3748. }
  3749. case ROXIE_FILECALLBACK:
  3750. {
  3751. // we need to send back to the slave a message containing the file info requested.
  3752. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3753. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3754. if (len)
  3755. {
  3756. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3757. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3758. const char *rowdata = (const char *) row.get();
  3759. bool isOpt = * (bool *) rowdata;
  3760. bool isLocal = * (bool *) (rowdata+1);
  3761. const char *lfn = rowdata+2;
  3762. if (ctxTraceLevel > 5)
  3763. {
  3764. StringBuffer s;
  3765. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3766. }
  3767. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3768. }
  3769. else
  3770. throwUnexpected();
  3771. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3772. // Leave original message on pending queue in original location - this is not a reply to it.
  3773. break;
  3774. }
  3775. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3776. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3777. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3778. throwUnexpected();
  3779. case ROXIE_LIMIT_EXCEEDED:
  3780. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3781. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3782. throwUnexpected();
  3783. case ROXIE_TRACEINFO:
  3784. {
  3785. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3786. loop
  3787. {
  3788. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3789. if (rowlen)
  3790. {
  3791. char *logInfo = (char *) extra->getNext(*rowlen);
  3792. MemoryBuffer buf;
  3793. buf.setBuffer(*rowlen, logInfo, false);
  3794. switch ((TracingCategory) *logInfo)
  3795. {
  3796. case LOG_TRACING:
  3797. case LOG_ERROR:
  3798. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3799. break;
  3800. case LOG_STATVALUES:
  3801. buf.skip(1);
  3802. activity.mergeStats(buf);
  3803. break;
  3804. case LOG_CHILDCOUNT:
  3805. case LOG_CHILDSTATS:
  3806. unsigned graphId, childId;
  3807. buf.skip(1);
  3808. buf.read(graphId);
  3809. buf.read(childId);
  3810. if (*logInfo == LOG_CHILDCOUNT)
  3811. {
  3812. unsigned childProcessed;
  3813. unsigned idx;
  3814. buf.read(childProcessed);
  3815. buf.read(idx);
  3816. if (traceLevel > 5)
  3817. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d for child %d subgraph %d", childProcessed, idx, childId, graphId);
  3818. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed);
  3819. }
  3820. else
  3821. {
  3822. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  3823. CRuntimeStatisticCollection childStats(allStatistics);
  3824. childStats.deserialize(buf);
  3825. if (traceLevel > 5)
  3826. {
  3827. StringBuffer s;
  3828. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  3829. }
  3830. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  3831. }
  3832. }
  3833. ReleaseRoxieRow(rowlen);
  3834. ReleaseRoxieRow(logInfo);
  3835. }
  3836. else
  3837. break;
  3838. }
  3839. break;
  3840. }
  3841. case ROXIE_EXCEPTION:
  3842. if (ctxTraceLevel > 1)
  3843. {
  3844. StringBuffer s;
  3845. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3846. }
  3847. op->queryHeader().noteException(header.retries);
  3848. if (op->queryHeader().allChannelsFailed())
  3849. {
  3850. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3851. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3852. throwRemoteException(exceptionData);
  3853. }
  3854. // Leave it on pending queue in original location
  3855. break;
  3856. case ROXIE_ALIVE:
  3857. if (ctxTraceLevel > 4)
  3858. {
  3859. StringBuffer s;
  3860. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3861. }
  3862. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3863. // Leave it on pending queue in original location
  3864. break;
  3865. default:
  3866. if (header.retries & ROXIE_RETRIES_MASK)
  3867. atomic_inc(&retriesNeeded);
  3868. unsigned metaLen;
  3869. const void *metaData = mr->getMessageMetadata(metaLen);
  3870. if (metaLen)
  3871. {
  3872. // We got back first chunk but there is more.
  3873. // resend the packet, with the cursor info provided.
  3874. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3875. if (ctxTraceLevel > 1)
  3876. {
  3877. StringBuffer s;
  3878. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3879. }
  3880. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3881. {
  3882. StringBuffer s;
  3883. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3884. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3885. throwUnexpected();
  3886. }
  3887. MemoryBuffer nextQuery;
  3888. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3889. nextQuery.append(metaLen, metaData);
  3890. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3891. nextQuery.append(op->getContextLength(), op->queryContextData());
  3892. if (resendSequence == CONTINUESEQUENCE_MAX)
  3893. {
  3894. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3895. resendSequence = 1;
  3896. }
  3897. else
  3898. resendSequence++;
  3899. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3900. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3901. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3902. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3903. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3904. fqp->setSequence(original->getSequence());
  3905. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3906. original->setContinuation(LINK(fqp));
  3907. if (mergeOrder)
  3908. fqp->setDelayed(true);
  3909. else
  3910. {
  3911. ROQ->sendPacket(resend, activity.queryLogCtx());
  3912. sentsome.signal();
  3913. }
  3914. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3915. }
  3916. else
  3917. {
  3918. if (serverSideCache)
  3919. serverSideCache->noteCachedResult(original, mr);
  3920. }
  3921. unsigned channel = header.channel;
  3922. {
  3923. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3924. if (b)
  3925. b->signal();
  3926. }
  3927. original->setResult(mr.getClear());
  3928. sentsome.signal();
  3929. return;
  3930. }
  3931. }
  3932. }
  3933. else
  3934. {
  3935. if (!anyActivity && !localSlave)
  3936. {
  3937. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3938. retryPending();
  3939. }
  3940. }
  3941. }
  3942. }
  3943. inline unsigned headerLength() const
  3944. {
  3945. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3946. }
  3947. void copyHeader(byte *tgt, unsigned channel) const
  3948. {
  3949. unsigned len = logInfo.length();
  3950. memcpy(tgt, logInfo.toByteArray(), len);
  3951. tgt += len;
  3952. *(unsigned *) tgt = parentExtractSize;
  3953. tgt += sizeof(unsigned);
  3954. memcpy(tgt, parentExtract, parentExtractSize);
  3955. tgt += parentExtractSize;
  3956. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3957. tgt += cachedContext.length();
  3958. }
  3959. };
  3960. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3961. {
  3962. Owned <IException> exception;
  3963. bool skipping;
  3964. ConstPointerArray buff;
  3965. unsigned index;
  3966. bool pulled;
  3967. void pullInput()
  3968. {
  3969. try
  3970. {
  3971. if (exception)
  3972. throw exception.getClear();
  3973. unsigned __int64 count = 0;
  3974. loop
  3975. {
  3976. const void * next = CRemoteResultAdaptor::nextInGroup();
  3977. if (next == NULL)
  3978. {
  3979. next = CRemoteResultAdaptor::nextInGroup();
  3980. if(next == NULL)
  3981. break;
  3982. buff.append(NULL);
  3983. }
  3984. count++;
  3985. if (count > rowLimit)
  3986. {
  3987. ReleaseRoxieRow(next);
  3988. ReleaseRoxieRowSet(buff);
  3989. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3990. throwUnexpected();
  3991. }
  3992. else if (count > keyedLimit)
  3993. {
  3994. ReleaseRoxieRow(next);
  3995. ReleaseRoxieRowSet(buff);
  3996. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3997. throwUnexpected();
  3998. }
  3999. buff.append(next);
  4000. }
  4001. }
  4002. catch (IException *E)
  4003. {
  4004. if (QUERYINTERFACE(E, LimitSkipException))
  4005. {
  4006. Owned<IException> cleanup = E;
  4007. ReleaseRoxieRowSet(buff);
  4008. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4009. if (onfail)
  4010. buff.append(onfail);
  4011. }
  4012. else
  4013. throw;
  4014. }
  4015. pulled = true;
  4016. }
  4017. public:
  4018. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4019. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4020. {
  4021. skipping = _skipping;
  4022. index = 0;
  4023. pulled = false;
  4024. }
  4025. void setException(IException *E)
  4026. {
  4027. exception.setown(E);
  4028. }
  4029. virtual void onReset()
  4030. {
  4031. while (buff.isItem(index))
  4032. ReleaseRoxieRow(buff.item(index++));
  4033. buff.kill();
  4034. pulled = false;
  4035. exception.clear();
  4036. CRemoteResultAdaptor::onReset();
  4037. }
  4038. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4039. {
  4040. index = 0;
  4041. pulled = false;
  4042. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4043. }
  4044. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4045. {
  4046. // 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
  4047. if (exception)
  4048. throw exception.getClear();
  4049. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4050. }
  4051. virtual const void *nextInGroup()
  4052. {
  4053. if (skipping)
  4054. {
  4055. if(!pulled)
  4056. pullInput();
  4057. if(buff.isItem(index))
  4058. {
  4059. const void * next = buff.item(index++);
  4060. if(next)
  4061. processed++;
  4062. return next;
  4063. }
  4064. return NULL;
  4065. }
  4066. else
  4067. {
  4068. if (exception)
  4069. throw exception.getClear();
  4070. return CRemoteResultAdaptor::nextInGroup();
  4071. }
  4072. }
  4073. };
  4074. //=================================================================================
  4075. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4076. {
  4077. IHThorApplyArg &helper;
  4078. public:
  4079. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4080. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4081. {
  4082. }
  4083. virtual void onExecute()
  4084. {
  4085. helper.start();
  4086. loop
  4087. {
  4088. const void * next = input->nextInGroup();
  4089. if (!next)
  4090. {
  4091. next = input->nextInGroup();
  4092. if (!next)
  4093. break;
  4094. }
  4095. helper.apply(next);
  4096. ReleaseRoxieRow(next);
  4097. }
  4098. helper.end();
  4099. }
  4100. };
  4101. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4102. {
  4103. bool isRoot;
  4104. public:
  4105. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4106. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4107. {
  4108. }
  4109. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4110. {
  4111. return new CRoxieServerApplyActivity(this, _probeManager);
  4112. }
  4113. virtual bool isSink() const
  4114. {
  4115. return isRoot;
  4116. }
  4117. };
  4118. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4119. {
  4120. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4121. }
  4122. //=================================================================================
  4123. class CRoxieServerNullActivity : public CRoxieServerActivity
  4124. {
  4125. public:
  4126. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4127. : CRoxieServerActivity(_factory, _probeManager)
  4128. {
  4129. }
  4130. virtual const void *nextInGroup()
  4131. {
  4132. return NULL;
  4133. }
  4134. };
  4135. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4136. {
  4137. return new CRoxieServerNullActivity(_factory, _probeManager);
  4138. }
  4139. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4140. {
  4141. public:
  4142. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4143. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4144. {
  4145. }
  4146. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4147. {
  4148. return new CRoxieServerNullActivity(this, _probeManager);
  4149. }
  4150. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4151. {
  4152. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4153. }
  4154. };
  4155. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4156. {
  4157. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4158. }
  4159. //=================================================================================
  4160. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4161. {
  4162. public:
  4163. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4164. : CRoxieServerActivity(_factory, _probeManager)
  4165. {
  4166. }
  4167. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4168. {
  4169. return input->gatherConjunctions(collector);
  4170. }
  4171. virtual void resetEOF()
  4172. {
  4173. input->resetEOF();
  4174. }
  4175. virtual const void *nextInGroup()
  4176. {
  4177. const void * next = input->nextInGroup();
  4178. if (next)
  4179. processed++;
  4180. return next;
  4181. }
  4182. virtual bool isPassThrough()
  4183. {
  4184. return true;
  4185. }
  4186. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4187. {
  4188. ActivityTimer t(totalCycles, timeActivities);
  4189. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4190. if (next)
  4191. processed++;
  4192. return next;
  4193. }
  4194. IInputSteppingMeta * querySteppingMeta()
  4195. {
  4196. return input->querySteppingMeta();
  4197. }
  4198. };
  4199. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4200. {
  4201. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4202. }
  4203. //=================================================================================
  4204. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4205. {
  4206. protected:
  4207. bool eof;
  4208. bool first;
  4209. public:
  4210. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4211. : CRoxieServerActivity(_factory, _probeManager)
  4212. {
  4213. eof = false;
  4214. first = true;
  4215. }
  4216. ~CRoxieServerChildBaseActivity()
  4217. {
  4218. }
  4219. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4220. {
  4221. eof = false;
  4222. first = true;
  4223. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4224. }
  4225. };
  4226. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4227. {
  4228. public:
  4229. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4230. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4231. {
  4232. }
  4233. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4234. {
  4235. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4236. }
  4237. };
  4238. //=================================================================================
  4239. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4240. {
  4241. IHThorChildIteratorArg &helper;
  4242. public:
  4243. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4244. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4245. {
  4246. }
  4247. virtual bool needsAllocator() const { return true; }
  4248. virtual const void *nextInGroup()
  4249. {
  4250. ActivityTimer t(totalCycles, timeActivities);
  4251. if (eof)
  4252. return NULL;
  4253. bool ok;
  4254. if (first)
  4255. {
  4256. ok = helper.first();
  4257. first = false;
  4258. }
  4259. else
  4260. ok = helper.next();
  4261. try
  4262. {
  4263. while (ok)
  4264. {
  4265. processed++;
  4266. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4267. unsigned outSize = helper.transform(rowBuilder);
  4268. if (outSize)
  4269. return rowBuilder.finalizeRowClear(outSize);
  4270. ok = helper.next();
  4271. }
  4272. }
  4273. catch (IException *E)
  4274. {
  4275. throw makeWrappedException(E);
  4276. }
  4277. eof = true;
  4278. return NULL;
  4279. }
  4280. };
  4281. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4282. {
  4283. public:
  4284. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4285. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4286. {
  4287. }
  4288. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4289. {
  4290. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4291. }
  4292. };
  4293. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4294. {
  4295. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4296. }
  4297. //=================================================================================
  4298. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4299. {
  4300. IHThorChildNormalizeArg &helper;
  4301. public:
  4302. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4303. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4304. {
  4305. }
  4306. virtual bool needsAllocator() const { return true; }
  4307. virtual const void *nextInGroup()
  4308. {
  4309. ActivityTimer t(totalCycles, timeActivities);
  4310. if (eof)
  4311. return NULL;
  4312. bool ok;
  4313. if (first)
  4314. {
  4315. ok = helper.first();
  4316. first = false;
  4317. }
  4318. else
  4319. ok = helper.next();
  4320. if (ok)
  4321. {
  4322. try
  4323. {
  4324. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4325. do {
  4326. unsigned outSize = helper.transform(rowBuilder);
  4327. if (outSize)
  4328. {
  4329. processed++;
  4330. return rowBuilder.finalizeRowClear(outSize);
  4331. }
  4332. ok = helper.next();
  4333. }
  4334. while (ok);
  4335. }
  4336. catch (IException *E)
  4337. {
  4338. throw makeWrappedException(E);
  4339. }
  4340. }
  4341. eof = true;
  4342. return NULL;
  4343. }
  4344. };
  4345. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4346. {
  4347. public:
  4348. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4349. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4350. {
  4351. }
  4352. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4353. {
  4354. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4355. }
  4356. };
  4357. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4358. {
  4359. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4360. }
  4361. //=================================================================================
  4362. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4363. {
  4364. IHThorChildAggregateArg &helper;
  4365. public:
  4366. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4367. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4368. {
  4369. }
  4370. virtual bool needsAllocator() const { return true; }
  4371. virtual const void *nextInGroup()
  4372. {
  4373. ActivityTimer t(totalCycles, timeActivities);
  4374. if (eof)
  4375. return NULL;
  4376. eof = true;
  4377. processed++;
  4378. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4379. helper.clearAggregate(rowBuilder);
  4380. helper.processRows(rowBuilder);
  4381. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4382. return rowBuilder.finalizeRowClear(finalSize);
  4383. }
  4384. };
  4385. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4386. {
  4387. public:
  4388. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4389. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4390. {
  4391. }
  4392. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4393. {
  4394. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4395. }
  4396. };
  4397. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4398. {
  4399. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4400. }
  4401. //=================================================================================
  4402. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4403. {
  4404. IHThorChildGroupAggregateArg &helper;
  4405. RowAggregator aggregated;
  4406. public:
  4407. IMPLEMENT_IINTERFACE
  4408. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4409. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4410. aggregated(helper, helper)
  4411. {
  4412. }
  4413. void processRow(const void * next)
  4414. {
  4415. aggregated.addRow(next);
  4416. }
  4417. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4418. {
  4419. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4420. aggregated.start(rowAllocator);
  4421. }
  4422. virtual void reset()
  4423. {
  4424. aggregated.reset();
  4425. CRoxieServerChildBaseActivity::reset();
  4426. }
  4427. virtual bool needsAllocator() const { return true; }
  4428. virtual const void *nextInGroup()
  4429. {
  4430. ActivityTimer t(totalCycles, timeActivities);
  4431. if (eof)
  4432. return NULL;
  4433. if (first)
  4434. {
  4435. helper.processRows(this);
  4436. first = false;
  4437. }
  4438. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4439. if (next)
  4440. {
  4441. processed++;
  4442. return next->finalizeRowClear();
  4443. }
  4444. eof = true;
  4445. return NULL;
  4446. }
  4447. };
  4448. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4449. {
  4450. public:
  4451. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4452. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4453. {
  4454. }
  4455. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4456. {
  4457. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4458. }
  4459. };
  4460. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4461. {
  4462. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4463. }
  4464. //=================================================================================
  4465. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4466. {
  4467. IHThorChildThroughNormalizeArg &helper;
  4468. const void * lastInput;
  4469. unsigned numProcessedLastGroup;
  4470. bool ok;
  4471. public:
  4472. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4473. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4474. {
  4475. lastInput = NULL;
  4476. numProcessedLastGroup = 0;
  4477. ok = false;
  4478. }
  4479. virtual void stop(bool aborting)
  4480. {
  4481. CRoxieServerChildBaseActivity::stop(aborting);
  4482. ReleaseRoxieRow(lastInput);
  4483. lastInput = NULL;
  4484. }
  4485. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4486. {
  4487. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4488. numProcessedLastGroup = processed;
  4489. ok = false;
  4490. }
  4491. virtual bool needsAllocator() const { return true; }
  4492. virtual const void *nextInGroup()
  4493. {
  4494. ActivityTimer t(totalCycles, timeActivities);
  4495. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4496. loop
  4497. {
  4498. if (ok)
  4499. ok = helper.next();
  4500. while (!ok)
  4501. {
  4502. ReleaseRoxieRow(lastInput);
  4503. lastInput = input->nextInGroup();
  4504. if (!lastInput)
  4505. {
  4506. if (numProcessedLastGroup != processed)
  4507. {
  4508. numProcessedLastGroup = processed;
  4509. return NULL;
  4510. }
  4511. lastInput = input->nextInGroup();
  4512. if (!lastInput)
  4513. return NULL;
  4514. }
  4515. ok = helper.first(lastInput);
  4516. }
  4517. try
  4518. {
  4519. do
  4520. {
  4521. unsigned outSize = helper.transform(rowBuilder);
  4522. if (outSize)
  4523. {
  4524. processed++;
  4525. return rowBuilder.finalizeRowClear(outSize);
  4526. }
  4527. ok = helper.next();
  4528. } while (ok);
  4529. }
  4530. catch (IException *E)
  4531. {
  4532. throw makeWrappedException(E);
  4533. }
  4534. }
  4535. }
  4536. };
  4537. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4538. {
  4539. public:
  4540. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4541. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4542. {
  4543. }
  4544. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4545. {
  4546. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4547. }
  4548. };
  4549. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4550. {
  4551. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4552. }
  4553. //=================================================================================
  4554. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  4555. {
  4556. IHThorDistributionArg &helper;
  4557. public:
  4558. CRoxieServerDistributionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4559. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  4560. {
  4561. }
  4562. virtual void onExecute()
  4563. {
  4564. MemoryAttr ma;
  4565. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  4566. helper.clearAggregate(accumulator);
  4567. OwnedConstRoxieRow nextrec(input->nextInGroup());
  4568. loop
  4569. {
  4570. if (!nextrec)
  4571. {
  4572. nextrec.setown(input->nextInGroup());
  4573. if (!nextrec)
  4574. break;
  4575. }
  4576. helper.process(accumulator, nextrec);
  4577. nextrec.setown(input->nextInGroup());
  4578. }
  4579. StringBuffer result;
  4580. result.append("<XML>");
  4581. helper.gatherResult(accumulator, result);
  4582. result.append("</XML>");
  4583. helper.sendResult(result.length(), result.str());
  4584. helper.destruct(accumulator);
  4585. }
  4586. };
  4587. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  4588. {
  4589. bool isRoot;
  4590. public:
  4591. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4592. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4593. {
  4594. }
  4595. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4596. {
  4597. return new CRoxieServerDistributionActivity(this, _probeManager);
  4598. }
  4599. virtual bool isSink() const
  4600. {
  4601. return isRoot;
  4602. }
  4603. };
  4604. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4605. {
  4606. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4607. }
  4608. //=================================================================================
  4609. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4610. {
  4611. IHThorLinkedRawIteratorArg &helper;
  4612. public:
  4613. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4614. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4615. {
  4616. }
  4617. virtual const void *nextInGroup()
  4618. {
  4619. ActivityTimer t(totalCycles, timeActivities);
  4620. const void *ret =helper.next();
  4621. if (ret)
  4622. {
  4623. LinkRoxieRow(ret);
  4624. processed++;
  4625. }
  4626. return ret;
  4627. }
  4628. };
  4629. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4630. {
  4631. public:
  4632. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4633. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4634. {
  4635. }
  4636. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4637. {
  4638. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4639. }
  4640. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4641. {
  4642. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4643. }
  4644. };
  4645. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4646. {
  4647. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4648. }
  4649. //=================================================================================
  4650. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4651. {
  4652. public:
  4653. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4654. : CRoxieServerActivity(_factory, _probeManager)
  4655. {
  4656. }
  4657. virtual const void *nextInGroup()
  4658. {
  4659. throwUnexpected();
  4660. }
  4661. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4662. {
  4663. try
  4664. {
  4665. start(parentExtractSize, parentExtract, false);
  4666. {
  4667. ActivityTimer t(totalCycles, timeActivities);
  4668. MemoryBuffer result;
  4669. IRecordSize * inputMeta = input->queryOutputMeta();
  4670. loop
  4671. {
  4672. const void *nextrec = input->nextInGroup();
  4673. if (!nextrec)
  4674. {
  4675. nextrec = input->nextInGroup();
  4676. if (!nextrec)
  4677. break;
  4678. }
  4679. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4680. ReleaseRoxieRow(nextrec);
  4681. }
  4682. retSize = result.length();
  4683. ret = result.detach();
  4684. }
  4685. stop(false);
  4686. reset();
  4687. }
  4688. catch(IException *E)
  4689. {
  4690. ctx->notifyAbort(E);
  4691. stop(true);
  4692. reset();
  4693. throw;
  4694. }
  4695. catch(...)
  4696. {
  4697. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4698. ctx->notifyAbort(E);
  4699. stop(true);
  4700. reset();
  4701. throw;
  4702. }
  4703. }
  4704. };
  4705. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4706. {
  4707. bool isRoot;
  4708. public:
  4709. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4710. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4711. {
  4712. }
  4713. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4714. {
  4715. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4716. }
  4717. virtual bool isSink() const
  4718. {
  4719. return isRoot;
  4720. }
  4721. };
  4722. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4723. {
  4724. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4725. }
  4726. //=================================================================================
  4727. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4728. {
  4729. IHThorInlineTableArg &helper;
  4730. __uint64 curRow;
  4731. __uint64 numRows;
  4732. public:
  4733. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4734. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4735. {
  4736. curRow = 0;
  4737. numRows = 0;
  4738. }
  4739. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4740. {
  4741. curRow = 0;
  4742. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4743. numRows = helper.numRows();
  4744. }
  4745. virtual bool needsAllocator() const { return true; }
  4746. virtual const void *nextInGroup()
  4747. {
  4748. ActivityTimer t(totalCycles, timeActivities);
  4749. // Filtering empty rows, returns the next valid row
  4750. while (curRow < numRows)
  4751. {
  4752. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4753. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4754. if (outSize)
  4755. {
  4756. processed++;
  4757. return rowBuilder.finalizeRowClear(outSize);
  4758. }
  4759. }
  4760. return NULL;
  4761. }
  4762. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4763. {
  4764. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4765. }
  4766. };
  4767. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4768. {
  4769. public:
  4770. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4771. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4772. {
  4773. }
  4774. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4775. {
  4776. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4777. }
  4778. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4779. {
  4780. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4781. }
  4782. };
  4783. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4784. {
  4785. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4786. }
  4787. //=================================================================================
  4788. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4789. {
  4790. IHThorWorkunitReadArg &helper;
  4791. CriticalSection readerCrit;
  4792. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4793. public:
  4794. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4795. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4796. {
  4797. }
  4798. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4799. {
  4800. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4801. if (!ctx->queryServerContext())
  4802. {
  4803. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4804. }
  4805. }
  4806. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4807. {
  4808. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4809. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4810. OwnedRoxieString fromWuid(helper.getWUID());
  4811. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4812. // MORE _ should that be in onCreate?
  4813. }
  4814. virtual void reset()
  4815. {
  4816. {
  4817. CriticalBlock b(readerCrit);
  4818. wuReader.clear();
  4819. }
  4820. CRoxieServerActivity::reset();
  4821. };
  4822. virtual bool needsAllocator() const { return true; }
  4823. virtual const void *nextInGroup()
  4824. {
  4825. ActivityTimer t(totalCycles, timeActivities);
  4826. Linked<IWorkUnitRowReader> useReader;
  4827. {
  4828. CriticalBlock b(readerCrit);
  4829. if (!wuReader)
  4830. return NULL;
  4831. useReader.set(wuReader);
  4832. }
  4833. const void *ret = useReader->nextInGroup();
  4834. if (ret)
  4835. processed++;
  4836. return ret;
  4837. }
  4838. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4839. {
  4840. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4841. }
  4842. };
  4843. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4844. {
  4845. public:
  4846. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4847. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4848. {
  4849. }
  4850. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4851. {
  4852. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4853. }
  4854. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4855. {
  4856. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4857. }
  4858. };
  4859. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4860. {
  4861. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4862. }
  4863. //=================================================================================
  4864. interface ILocalGraphEx : public IEclGraphResults
  4865. {
  4866. public:
  4867. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4868. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4869. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4870. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4871. };
  4872. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4873. {
  4874. public:
  4875. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4876. IMPLEMENT_IINTERFACE
  4877. virtual IOutputMetaData * queryOutputMeta() const
  4878. {
  4879. return input->queryOutputMeta();
  4880. }
  4881. virtual unsigned queryId() const
  4882. {
  4883. return input->queryId();
  4884. }
  4885. virtual unsigned __int64 queryTotalCycles() const
  4886. {
  4887. return input->queryTotalCycles();
  4888. }
  4889. virtual unsigned __int64 queryLocalCycles() const
  4890. {
  4891. return input->queryLocalCycles();
  4892. }
  4893. virtual IRoxieInput *queryInput(unsigned idx) const
  4894. {
  4895. return input->queryInput(idx);
  4896. }
  4897. virtual IRoxieServerActivity *queryActivity()
  4898. {
  4899. return input->queryActivity();
  4900. }
  4901. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4902. {
  4903. return input->queryIndexReadActivity();
  4904. }
  4905. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4906. {
  4907. CriticalBlock procedure(cs);
  4908. input->start(parentExtractSize, parentExtract, paused);
  4909. }
  4910. virtual void stop(bool aborting)
  4911. {
  4912. CriticalBlock procedure(cs);
  4913. input->stop(aborting);
  4914. }
  4915. virtual void reset()
  4916. {
  4917. CriticalBlock procedure(cs);
  4918. input->reset();
  4919. }
  4920. virtual void resetEOF()
  4921. {
  4922. CriticalBlock procedure(cs);
  4923. input->resetEOF();
  4924. }
  4925. virtual void checkAbort()
  4926. {
  4927. CriticalBlock procedure(cs);
  4928. input->checkAbort();
  4929. }
  4930. virtual const void *nextInGroup()
  4931. {
  4932. CriticalBlock procedure(cs);
  4933. return input->nextInGroup();
  4934. }
  4935. virtual bool nextGroup(ConstPointerArray & group)
  4936. {
  4937. CriticalBlock procedure(cs);
  4938. return input->nextGroup(group);
  4939. }
  4940. private:
  4941. CriticalSection cs;
  4942. Linked<IRoxieInput> input;
  4943. };
  4944. //=================================================================================
  4945. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4946. {
  4947. public:
  4948. IMPLEMENT_IINTERFACE;
  4949. CPseudoRoxieInput()
  4950. {
  4951. }
  4952. virtual unsigned __int64 queryTotalCycles() const
  4953. {
  4954. return 0;
  4955. }
  4956. virtual unsigned __int64 queryLocalCycles() const
  4957. {
  4958. return 0;
  4959. }
  4960. virtual IRoxieInput *queryInput(unsigned idx) const
  4961. {
  4962. return NULL;
  4963. }
  4964. virtual IRoxieServerActivity *queryActivity()
  4965. {
  4966. throwUnexpected();
  4967. }
  4968. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4969. {
  4970. throwUnexpected();
  4971. }
  4972. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4973. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4974. virtual void stop(bool aborting) { }
  4975. virtual void reset() { }
  4976. virtual void checkAbort() { }
  4977. virtual unsigned queryId() const { throwUnexpected(); }
  4978. virtual void resetEOF() { }
  4979. };
  4980. class CIndirectRoxieInput : public CPseudoRoxieInput
  4981. {
  4982. public:
  4983. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4984. {
  4985. }
  4986. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4987. {
  4988. input->start(parentExtractSize, parentExtract, paused);
  4989. }
  4990. virtual void stop(bool aborting)
  4991. {
  4992. input->stop(aborting);
  4993. }
  4994. virtual void reset()
  4995. {
  4996. input->reset();
  4997. }
  4998. virtual void checkAbort()
  4999. {
  5000. input->checkAbort();
  5001. }
  5002. virtual const void * nextInGroup()
  5003. {
  5004. return input->nextInGroup();
  5005. }
  5006. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5007. {
  5008. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5009. }
  5010. virtual unsigned __int64 queryTotalCycles() const
  5011. {
  5012. return input->queryTotalCycles();
  5013. }
  5014. virtual unsigned __int64 queryLocalCycles() const
  5015. {
  5016. return input->queryLocalCycles();
  5017. }
  5018. virtual IRoxieInput *queryInput(unsigned idx) const
  5019. {
  5020. return input->queryInput(idx);
  5021. }
  5022. virtual unsigned queryId() const
  5023. {
  5024. return input->queryId();
  5025. }
  5026. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5027. {
  5028. return input->gatherConjunctions(collector);
  5029. }
  5030. virtual void resetEOF()
  5031. {
  5032. input->resetEOF();
  5033. }
  5034. virtual unsigned numConcreteOutputs() const
  5035. {
  5036. return input->numConcreteOutputs();
  5037. }
  5038. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  5039. {
  5040. return input->queryConcreteInput(idx);
  5041. }
  5042. virtual IOutputMetaData * queryOutputMeta() const
  5043. {
  5044. return input->queryOutputMeta();
  5045. }
  5046. virtual IRoxieServerActivity *queryActivity()
  5047. {
  5048. return input->queryActivity();
  5049. }
  5050. void setInput(IRoxieInput * _input)
  5051. {
  5052. input = _input;
  5053. }
  5054. protected:
  5055. IRoxieInput * input;
  5056. };
  5057. class CExtractMapperInput : public CIndirectRoxieInput
  5058. {
  5059. unsigned savedParentExtractSize;
  5060. const byte * savedParentExtract;
  5061. public:
  5062. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  5063. {
  5064. savedParentExtractSize = 0;
  5065. savedParentExtract = NULL;
  5066. }
  5067. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5068. {
  5069. input->start(savedParentExtractSize, savedParentExtract, paused);
  5070. }
  5071. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5072. {
  5073. savedParentExtractSize = _savedParentExtractSize;
  5074. savedParentExtract = _savedParentExtract;
  5075. }
  5076. };
  5077. class CGraphResult : public CInterface, implements IGraphResult
  5078. {
  5079. CriticalSection cs;
  5080. byte **rowset;
  5081. size32_t count;
  5082. bool complete;
  5083. void clear()
  5084. {
  5085. CriticalBlock func(cs);
  5086. rtlReleaseRowset(count, rowset);
  5087. rowset = NULL;
  5088. count = 0;
  5089. complete = false;
  5090. }
  5091. public:
  5092. IMPLEMENT_IINTERFACE
  5093. CGraphResult()
  5094. {
  5095. complete = false; // dummy result is not supposed to be used...
  5096. rowset = NULL;
  5097. count = 0;
  5098. }
  5099. CGraphResult(size32_t _count, byte **_rowset)
  5100. : count(_count), rowset(_rowset)
  5101. {
  5102. complete = true;
  5103. }
  5104. ~CGraphResult()
  5105. {
  5106. clear();
  5107. }
  5108. // interface IGraphResult
  5109. virtual IRoxieInput * createIterator()
  5110. {
  5111. if (!complete)
  5112. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5113. return new CGraphResultIterator(this);
  5114. }
  5115. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5116. {
  5117. if (!complete)
  5118. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5119. result = rtlLinkRowset(rowset);
  5120. countResult = count;
  5121. }
  5122. virtual const void * getLinkedRowResult()
  5123. {
  5124. if (!complete)
  5125. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5126. if (count != 1)
  5127. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5128. const void * ret = rowset[0];
  5129. LinkRoxieRow(ret);
  5130. return ret;
  5131. }
  5132. //other
  5133. const void * getRow(unsigned i)
  5134. {
  5135. CriticalBlock func(cs);
  5136. if (i >= count)
  5137. return NULL;
  5138. const void * ret = rowset[i];
  5139. if (ret) LinkRoxieRow(ret);
  5140. return ret;
  5141. }
  5142. protected:
  5143. class CGraphResultIterator : public CPseudoRoxieInput
  5144. {
  5145. unsigned i;
  5146. Linked<CGraphResult> result;
  5147. public:
  5148. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5149. IMPLEMENT_IINTERFACE
  5150. public:
  5151. virtual const void * nextInGroup()
  5152. {
  5153. return result->getRow(i++);
  5154. }
  5155. };
  5156. };
  5157. //=================================================================================
  5158. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5159. {
  5160. IHThorLocalResultReadArg &helper;
  5161. CriticalSection iterCrit;
  5162. Owned<IRoxieInput> iter;
  5163. ILocalGraphEx * graph;
  5164. unsigned graphId;
  5165. unsigned sequence;
  5166. public:
  5167. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5168. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5169. {
  5170. graph = NULL;
  5171. sequence = 0;
  5172. }
  5173. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5174. {
  5175. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5176. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5177. sequence = helper.querySequence();
  5178. }
  5179. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5180. {
  5181. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5182. iter.setown(graph->createResultIterator(sequence));
  5183. }
  5184. virtual void reset()
  5185. {
  5186. {
  5187. CriticalBlock b(iterCrit);
  5188. iter.clear();
  5189. }
  5190. CRoxieServerActivity::reset();
  5191. };
  5192. virtual const void *nextInGroup()
  5193. {
  5194. ActivityTimer t(totalCycles, timeActivities);
  5195. Linked<IRoxieInput> useIter;
  5196. {
  5197. CriticalBlock b(iterCrit);
  5198. if (!iter)
  5199. return NULL;
  5200. useIter.set(iter);
  5201. }
  5202. const void * next = useIter->nextInGroup();
  5203. if (next)
  5204. {
  5205. processed++;
  5206. atomic_inc(&rowsIn);
  5207. }
  5208. return next;
  5209. }
  5210. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5211. {
  5212. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5213. }
  5214. };
  5215. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5216. {
  5217. unsigned graphId;
  5218. public:
  5219. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5220. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5221. {
  5222. }
  5223. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5224. {
  5225. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5226. }
  5227. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5228. {
  5229. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5230. }
  5231. };
  5232. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5233. {
  5234. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5235. }
  5236. //=================================================================================
  5237. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5238. {
  5239. IHThorLocalResultReadArg &helper;
  5240. Owned<IRoxieInput> streamInput;
  5241. unsigned sequence;
  5242. public:
  5243. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5244. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5245. {
  5246. sequence = 0;
  5247. }
  5248. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5249. {
  5250. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5251. sequence = helper.querySequence();
  5252. }
  5253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5254. {
  5255. assertex(streamInput != NULL);
  5256. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5257. streamInput->start(parentExtractSize, parentExtract, paused);
  5258. }
  5259. virtual void stop(bool aborting)
  5260. {
  5261. CRoxieServerActivity::stop(aborting);
  5262. streamInput->stop(aborting);
  5263. }
  5264. virtual void reset()
  5265. {
  5266. streamInput->reset();
  5267. CRoxieServerActivity::reset();
  5268. };
  5269. virtual const void *nextInGroup()
  5270. {
  5271. ActivityTimer t(totalCycles, timeActivities);
  5272. const void * next = streamInput->nextInGroup();
  5273. if (next)
  5274. {
  5275. processed++;
  5276. atomic_inc(&rowsIn);
  5277. }
  5278. return next;
  5279. }
  5280. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5281. {
  5282. if (id == sequence)
  5283. {
  5284. streamInput.set(_input);
  5285. return true;
  5286. }
  5287. return false;
  5288. }
  5289. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5290. {
  5291. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5292. }
  5293. };
  5294. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5295. {
  5296. public:
  5297. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5298. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5299. {
  5300. }
  5301. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5302. {
  5303. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5304. }
  5305. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5306. {
  5307. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5308. }
  5309. };
  5310. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5311. {
  5312. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5313. }
  5314. //=====================================================================================================
  5315. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5316. {
  5317. IHThorLocalResultWriteArg &helper;
  5318. ILocalGraphEx * graph;
  5319. unsigned graphId;
  5320. public:
  5321. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5322. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5323. {
  5324. graph = NULL;
  5325. }
  5326. virtual bool needsAllocator() const { return true; }
  5327. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5328. {
  5329. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5330. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5331. }
  5332. virtual void onExecute()
  5333. {
  5334. RtlLinkedDatasetBuilder builder(rowAllocator);
  5335. input->readAll(builder);
  5336. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5337. graph->setResult(helper.querySequence(), result);
  5338. }
  5339. virtual const void *nextInGroup()
  5340. {
  5341. return input->nextInGroup(); // I can act as a passthrough input
  5342. }
  5343. IRoxieInput * querySelectOutput(unsigned id)
  5344. {
  5345. if (id == helper.querySequence())
  5346. {
  5347. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5348. return LINK(this);
  5349. }
  5350. return NULL;
  5351. }
  5352. };
  5353. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5354. {
  5355. unsigned graphId;
  5356. public:
  5357. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5358. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5359. {
  5360. isInternal = true;
  5361. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5362. }
  5363. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5364. {
  5365. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId, usageCount);
  5366. }
  5367. };
  5368. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5369. {
  5370. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5371. }
  5372. //=====================================================================================================
  5373. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5374. {
  5375. IHThorDictionaryResultWriteArg &helper;
  5376. ILocalGraphEx * graph;
  5377. unsigned graphId;
  5378. public:
  5379. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  5380. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5381. {
  5382. graph = NULL;
  5383. }
  5384. virtual bool needsAllocator() const { return true; }
  5385. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5386. {
  5387. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5388. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5389. }
  5390. virtual void onExecute()
  5391. {
  5392. unsigned sequence = helper.querySequence();
  5393. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5394. loop
  5395. {
  5396. const void *row = input->nextInGroup();
  5397. if (!row)
  5398. {
  5399. row = input->nextInGroup();
  5400. if (!row)
  5401. break;
  5402. }
  5403. builder.appendOwn(row);
  5404. processed++;
  5405. }
  5406. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5407. graph->setResult(helper.querySequence(), result);
  5408. }
  5409. virtual const void *nextInGroup()
  5410. {
  5411. return input->nextInGroup(); // I can act as a passthrough input
  5412. }
  5413. IRoxieInput * querySelectOutput(unsigned id)
  5414. {
  5415. if (id == helper.querySequence())
  5416. {
  5417. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5418. return LINK(this);
  5419. }
  5420. return NULL;
  5421. }
  5422. };
  5423. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5424. {
  5425. unsigned graphId;
  5426. public:
  5427. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5428. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5429. {
  5430. isInternal = true;
  5431. }
  5432. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5433. {
  5434. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, usageCount, graphId);
  5435. }
  5436. };
  5437. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5438. {
  5439. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5440. }
  5441. //=================================================================================
  5442. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5443. {
  5444. protected:
  5445. IHThorGraphLoopResultReadArg &helper;
  5446. CriticalSection iterCrit;
  5447. Owned<IRoxieInput> iter;
  5448. ILocalGraphEx * graph;
  5449. unsigned graphId;
  5450. unsigned sequence;
  5451. public:
  5452. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5453. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5454. {
  5455. graph = NULL;
  5456. sequence = 0;
  5457. }
  5458. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5459. {
  5460. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5461. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5462. }
  5463. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5464. {
  5465. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5466. if (iter)
  5467. iter->start(parentExtractSize, parentExtract, paused);
  5468. else
  5469. {
  5470. sequence = helper.querySequence();
  5471. if ((int)sequence >= 0)
  5472. {
  5473. try
  5474. {
  5475. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5476. }
  5477. catch (IException * E)
  5478. {
  5479. throw makeWrappedException(E);
  5480. }
  5481. }
  5482. }
  5483. }
  5484. virtual void stop(bool aborting)
  5485. {
  5486. if (iter)
  5487. iter->stop(aborting);
  5488. CRoxieServerActivity::stop(aborting);
  5489. }
  5490. virtual void reset()
  5491. {
  5492. {
  5493. CriticalBlock b(iterCrit);
  5494. if (iter)
  5495. iter->reset();
  5496. iter.clear();
  5497. }
  5498. CRoxieServerActivity::reset();
  5499. };
  5500. virtual const void *nextInGroup()
  5501. {
  5502. ActivityTimer t(totalCycles, timeActivities);
  5503. Linked<IRoxieInput> useIter;
  5504. {
  5505. CriticalBlock b(iterCrit);
  5506. if (!iter)
  5507. return NULL;
  5508. useIter.set(iter);
  5509. }
  5510. const void * next = useIter->nextInGroup();
  5511. if (next)
  5512. {
  5513. processed++;
  5514. atomic_inc(&rowsIn);
  5515. }
  5516. return next;
  5517. }
  5518. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5519. {
  5520. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5521. }
  5522. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5523. {
  5524. ensureCreated();
  5525. basehelper.onStart(parentExtract, NULL);
  5526. processor.noteUseIteration(helper.querySequence());
  5527. }
  5528. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5529. {
  5530. //helper already initialised from the gratherIterationUsage() call.
  5531. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5532. }
  5533. virtual IInputSteppingMeta * querySteppingMeta()
  5534. {
  5535. assertex(iter);
  5536. return iter->querySteppingMeta();
  5537. }
  5538. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5539. {
  5540. assertex(iter);
  5541. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5542. }
  5543. };
  5544. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5545. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5546. {
  5547. public:
  5548. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5549. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5550. {
  5551. sequence = _sequence;
  5552. }
  5553. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5554. {
  5555. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5556. if ((int)sequence >= 0)
  5557. {
  5558. try
  5559. {
  5560. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5561. }
  5562. catch (IException * E)
  5563. {
  5564. throw makeWrappedException(E);
  5565. }
  5566. }
  5567. }
  5568. };
  5569. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5570. {
  5571. unsigned graphId;
  5572. public:
  5573. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5574. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5575. {
  5576. }
  5577. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5578. {
  5579. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5580. }
  5581. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5582. {
  5583. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5584. }
  5585. };
  5586. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5587. {
  5588. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5589. }
  5590. //=====================================================================================================
  5591. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5592. {
  5593. IHThorGraphLoopResultWriteArg &helper;
  5594. ILocalGraphEx * graph;
  5595. unsigned graphId;
  5596. public:
  5597. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5598. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5599. {
  5600. graph = NULL;
  5601. }
  5602. virtual bool needsAllocator() const { return true; }
  5603. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5604. {
  5605. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5606. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5607. }
  5608. virtual void onExecute()
  5609. {
  5610. RtlLinkedDatasetBuilder builder(rowAllocator);
  5611. input->readAll(builder);
  5612. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5613. graph->setGraphLoopResult(result);
  5614. }
  5615. virtual IRoxieInput *queryOutput(unsigned idx)
  5616. {
  5617. if (idx==0)
  5618. return this;
  5619. else
  5620. return NULL;
  5621. }
  5622. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5623. {
  5624. return input->gatherConjunctions(collector);
  5625. }
  5626. virtual void resetEOF()
  5627. {
  5628. input->resetEOF();
  5629. }
  5630. virtual const void *nextInGroup()
  5631. {
  5632. const void * next = input->nextInGroup();
  5633. if (next)
  5634. processed++;
  5635. return next;
  5636. }
  5637. virtual bool isPassThrough()
  5638. {
  5639. return true;
  5640. }
  5641. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5642. {
  5643. ActivityTimer t(totalCycles, timeActivities);
  5644. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5645. if (next)
  5646. processed++;
  5647. return next;
  5648. }
  5649. IInputSteppingMeta * querySteppingMeta()
  5650. {
  5651. return input->querySteppingMeta();
  5652. }
  5653. virtual IOutputMetaData * queryOutputMeta() const
  5654. {
  5655. return input->queryOutputMeta();
  5656. }
  5657. };
  5658. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5659. {
  5660. unsigned graphId;
  5661. public:
  5662. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5663. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5664. {
  5665. isInternal = true;
  5666. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5667. }
  5668. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5669. {
  5670. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId, usageCount);
  5671. }
  5672. };
  5673. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5674. {
  5675. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5676. }
  5677. #if 0
  5678. //=====================================================================================================
  5679. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5680. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5681. {
  5682. next = NULL;
  5683. }
  5684. void CHThorLocalResultSpillActivity::ready()
  5685. {
  5686. CHThorSimpleActivityBase::ready();
  5687. next = input->nextInGroup();
  5688. grouped = input->isGrouped();
  5689. rowdata.clear();
  5690. }
  5691. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5692. {
  5693. const void * ret = next;
  5694. next = input->nextInGroup();
  5695. if (!ret && !next)
  5696. return NULL;
  5697. if (ret)
  5698. {
  5699. size32_t thisSize = outputMeta->getRecordSize(ret);
  5700. rowdata.append(thisSize, ret);
  5701. if (grouped)
  5702. rowdata.append(next == NULL);
  5703. }
  5704. return ret;
  5705. }
  5706. void CHThorLocalResultSpillActivity::done()
  5707. {
  5708. loop
  5709. {
  5710. const void * ret = nextInGroup();
  5711. if (!ret)
  5712. {
  5713. ret = nextInGroup();
  5714. if (!ret)
  5715. break;
  5716. }
  5717. ReleaseRoxieRow(ret);
  5718. }
  5719. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5720. CHThorSimpleActivityBase::done();
  5721. }
  5722. #endif
  5723. //=================================================================================
  5724. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5725. {
  5726. protected:
  5727. IHThorDedupArg &helper;
  5728. unsigned numKept;
  5729. unsigned numToKeep;
  5730. public:
  5731. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5732. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5733. {
  5734. numKept = 0;
  5735. numToKeep = 0;
  5736. }
  5737. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5738. {
  5739. numKept = 0;
  5740. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5741. numToKeep = helper.numToKeep();
  5742. }
  5743. };
  5744. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5745. {
  5746. IRangeCompare * stepCompare;
  5747. const void *prev;
  5748. public:
  5749. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5750. : CRoxieServerDedupActivity(_factory, _probeManager)
  5751. {
  5752. prev = NULL;
  5753. stepCompare = NULL;
  5754. }
  5755. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5756. {
  5757. prev = NULL;
  5758. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5759. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5760. stepCompare = NULL;
  5761. if (stepMeta)
  5762. stepCompare = stepMeta->queryCompare();
  5763. }
  5764. virtual void reset()
  5765. {
  5766. ReleaseClearRoxieRow(prev);
  5767. CRoxieServerDedupActivity::reset();
  5768. }
  5769. virtual const void * nextInGroup()
  5770. {
  5771. ActivityTimer t(totalCycles, timeActivities);
  5772. const void * next;
  5773. loop
  5774. {
  5775. next = input->nextInGroup();
  5776. if (!prev || !next || !helper.matches(prev,next))
  5777. {
  5778. numKept = 0;
  5779. break;
  5780. }
  5781. if (numKept < numToKeep-1)
  5782. {
  5783. numKept++;
  5784. break;
  5785. }
  5786. ReleaseRoxieRow(next);
  5787. }
  5788. ReleaseRoxieRow(prev);
  5789. prev = next;
  5790. if (next)
  5791. {
  5792. LinkRoxieRow(next);
  5793. processed++;
  5794. }
  5795. return next;
  5796. }
  5797. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5798. {
  5799. ActivityTimer t(totalCycles, timeActivities);
  5800. const void * next;
  5801. loop
  5802. {
  5803. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5804. //If the record was an in-exact match from the index then return it immediately
  5805. //and don't cause it to dedup following legal records.
  5806. if (!wasCompleteMatch)
  5807. {
  5808. assertex(stepExtra.returnMismatches());
  5809. return next;
  5810. }
  5811. if (!prev || !next || !helper.matches(prev,next))
  5812. {
  5813. numKept = 0;
  5814. break;
  5815. }
  5816. if (numKept < numToKeep-1)
  5817. {
  5818. numKept++;
  5819. break;
  5820. }
  5821. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5822. if (stepExtra.returnMismatches())
  5823. {
  5824. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5825. //condition to advance
  5826. if (stepCompare->docompare(next, seek, numFields) != 0)
  5827. {
  5828. wasCompleteMatch = false;
  5829. break;
  5830. }
  5831. }
  5832. ReleaseRoxieRow(next);
  5833. }
  5834. ReleaseRoxieRow(prev);
  5835. prev = next;
  5836. if (next)
  5837. {
  5838. LinkRoxieRow(next);
  5839. processed++;
  5840. }
  5841. return next;
  5842. }
  5843. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5844. {
  5845. return input->gatherConjunctions(collector);
  5846. }
  5847. virtual void resetEOF()
  5848. {
  5849. input->resetEOF();
  5850. }
  5851. IInputSteppingMeta * querySteppingMeta()
  5852. {
  5853. return input->querySteppingMeta();
  5854. }
  5855. };
  5856. //=================================================================================
  5857. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5858. {
  5859. const void *kept;
  5860. bool first;
  5861. public:
  5862. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5863. : CRoxieServerDedupActivity(_factory, _probeManager)
  5864. {
  5865. kept = NULL;
  5866. first = true;
  5867. }
  5868. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5869. {
  5870. first = true;
  5871. kept = NULL;
  5872. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5873. }
  5874. virtual void reset()
  5875. {
  5876. ReleaseClearRoxieRow(kept);
  5877. CRoxieServerActivity::reset();
  5878. }
  5879. virtual const void * nextInGroup()
  5880. {
  5881. ActivityTimer t(totalCycles, timeActivities);
  5882. if (first)
  5883. {
  5884. kept = input->nextInGroup();
  5885. first = false;
  5886. }
  5887. const void * next;
  5888. loop
  5889. {
  5890. next = input->nextInGroup();
  5891. if (!kept || !next || !helper.matches(kept,next))
  5892. {
  5893. numKept = 0;
  5894. break;
  5895. }
  5896. if (numKept < numToKeep-1)
  5897. {
  5898. numKept++;
  5899. break;
  5900. }
  5901. ReleaseRoxieRow(kept);
  5902. kept = next;
  5903. }
  5904. const void * ret = kept;
  5905. kept = next;
  5906. // CTXLOG("dedup returns %p", ret);
  5907. if (ret) processed++;
  5908. return ret;
  5909. }
  5910. };
  5911. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5912. {
  5913. IHThorDedupArg &helper;
  5914. unsigned survivorIndex;
  5915. ConstPointerArray survivors;
  5916. bool keepLeft;
  5917. bool eof;
  5918. bool first;
  5919. ICompare *primaryCompare;
  5920. public:
  5921. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5922. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5923. {
  5924. keepLeft = _keepLeft;
  5925. primaryCompare = helper.queryComparePrimary();
  5926. eof = false;
  5927. first = true;
  5928. survivorIndex = 0;
  5929. }
  5930. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5931. {
  5932. eof = false;
  5933. first = true;
  5934. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5935. }
  5936. virtual void reset()
  5937. {
  5938. #ifdef _DEBUG
  5939. while (survivors.isItem(survivorIndex))
  5940. {
  5941. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5942. }
  5943. #endif
  5944. survivors.kill();
  5945. eof = false;
  5946. first = true;
  5947. CRoxieServerActivity::reset();
  5948. }
  5949. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5950. {
  5951. for (unsigned idxL = first; idxL < last; idxL++)
  5952. {
  5953. const void * left = group.item(idxL);
  5954. if (left)
  5955. {
  5956. for (unsigned idxR = first; idxR < last; idxR++)
  5957. {
  5958. const void * right = group.item(idxR);
  5959. if ((idxL != idxR) && right)
  5960. {
  5961. if (helper.matches(left, right))
  5962. {
  5963. if (keepLeft)
  5964. {
  5965. group.replace(NULL, idxR);
  5966. ReleaseRoxieRow(right);
  5967. }
  5968. else
  5969. {
  5970. group.replace(NULL, idxL);
  5971. ReleaseRoxieRow(left);
  5972. break;
  5973. }
  5974. }
  5975. }
  5976. }
  5977. }
  5978. }
  5979. }
  5980. void dedupRange(unsigned first, unsigned last, void ** rows)
  5981. {
  5982. for (unsigned idxL = first; idxL < last; idxL++)
  5983. {
  5984. void * left = rows[idxL];
  5985. if (left)
  5986. {
  5987. for (unsigned idxR = first; idxR < last; idxR++)
  5988. {
  5989. void * right = rows[idxR];
  5990. if ((idxL != idxR) && right)
  5991. {
  5992. if (helper.matches(left, right))
  5993. {
  5994. if (keepLeft)
  5995. {
  5996. rows[idxR] = NULL;
  5997. ReleaseRoxieRow(right);
  5998. }
  5999. else
  6000. {
  6001. rows[idxL] = NULL;
  6002. ReleaseRoxieRow(left);
  6003. break;
  6004. }
  6005. }
  6006. }
  6007. }
  6008. }
  6009. }
  6010. }
  6011. bool calcNextDedupAll()
  6012. {
  6013. survivors.kill();
  6014. survivorIndex = 0;
  6015. ConstPointerArray group;
  6016. if (eof || !input->nextGroup(group))
  6017. {
  6018. eof = true;
  6019. return false;
  6020. }
  6021. unsigned max = group.ordinality();
  6022. if (primaryCompare)
  6023. {
  6024. //hard, if not impossible, to hit this code once optimisations in place
  6025. MemoryAttr indexbuff(max*sizeof(void *));
  6026. void ** temp = (void **)indexbuff.bufferBase();
  6027. void * *rows = const_cast<void * *>(group.getArray());
  6028. qsortvecstableinplace(rows, max, *primaryCompare, temp);
  6029. unsigned first = 0;
  6030. for (unsigned idx = 1; idx < max; idx++)
  6031. {
  6032. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6033. {
  6034. dedupRange(first, idx, rows);
  6035. first = idx;
  6036. }
  6037. }
  6038. dedupRange(first, max, rows);
  6039. for(unsigned idx2=0; idx2<max; ++idx2)
  6040. {
  6041. void * cur = rows[idx2];
  6042. if(cur)
  6043. survivors.append(cur);
  6044. }
  6045. }
  6046. else
  6047. {
  6048. dedupRange(0, max, group);
  6049. for(unsigned idx=0; idx<max; ++idx)
  6050. {
  6051. const void * cur = group.item(idx);
  6052. if(cur)
  6053. survivors.append(cur);
  6054. }
  6055. }
  6056. return true;
  6057. }
  6058. virtual const void *nextInGroup()
  6059. {
  6060. ActivityTimer t(totalCycles, timeActivities);
  6061. if (first)
  6062. {
  6063. calcNextDedupAll();
  6064. first = false;
  6065. }
  6066. while (survivors.isItem(survivorIndex))
  6067. {
  6068. const void *ret = survivors.item(survivorIndex++);
  6069. if (ret)
  6070. {
  6071. processed++;
  6072. return ret;
  6073. }
  6074. }
  6075. calcNextDedupAll();
  6076. return NULL;
  6077. }
  6078. };
  6079. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6080. {
  6081. bool compareAll;
  6082. bool keepLeft;
  6083. public:
  6084. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6085. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6086. {
  6087. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6088. compareAll = helper->compareAll();
  6089. keepLeft = helper->keepLeft();
  6090. }
  6091. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6092. {
  6093. if (compareAll)
  6094. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  6095. else if (keepLeft)
  6096. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  6097. else
  6098. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  6099. }
  6100. };
  6101. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6102. {
  6103. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6104. }
  6105. //=================================================================================
  6106. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6107. {
  6108. bool eof;
  6109. IHThorHashDedupArg &helper;
  6110. class HashDedupElement
  6111. {
  6112. public:
  6113. HashDedupElement(unsigned _hash, const void *_keyRow)
  6114. : hash(_hash), keyRow(_keyRow)
  6115. {
  6116. }
  6117. ~HashDedupElement()
  6118. {
  6119. ReleaseRoxieRow(keyRow);
  6120. }
  6121. inline unsigned queryHash() const
  6122. {
  6123. return hash;
  6124. }
  6125. inline const void *queryRow() const
  6126. {
  6127. return keyRow;
  6128. }
  6129. private:
  6130. unsigned hash;
  6131. const void *keyRow;
  6132. };
  6133. class HashDedupTable : public SuperHashTable
  6134. {
  6135. public:
  6136. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6137. : helper(_helper),
  6138. activityId(_activityId),
  6139. keySize(helper.queryKeySize())
  6140. {
  6141. }
  6142. virtual ~HashDedupTable() { releaseAll(); }
  6143. virtual unsigned getHashFromElement(const void *et) const
  6144. {
  6145. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6146. return element->queryHash();
  6147. }
  6148. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6149. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6150. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6151. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6152. {
  6153. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6154. if (fphash != element->queryHash())
  6155. return false;
  6156. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6157. }
  6158. virtual void onAdd(void *et) {}
  6159. virtual void onRemove(void *et)
  6160. {
  6161. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6162. delete element;
  6163. }
  6164. void onCreate(IRoxieSlaveContext *ctx)
  6165. {
  6166. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6167. }
  6168. void reset()
  6169. {
  6170. kill();
  6171. }
  6172. bool insert(const void * row)
  6173. {
  6174. unsigned hash = helper.queryHash()->hash(row);
  6175. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6176. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6177. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6178. if (find(hash, keyRow.get()))
  6179. return false;
  6180. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6181. return true;
  6182. }
  6183. private:
  6184. IHThorHashDedupArg & helper;
  6185. CachedOutputMetaData keySize;
  6186. Owned<IEngineRowAllocator> keyRowAllocator;
  6187. unsigned activityId;
  6188. } table;
  6189. public:
  6190. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6191. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6192. {
  6193. eof = false;
  6194. }
  6195. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6196. {
  6197. eof = false;
  6198. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6199. }
  6200. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6201. {
  6202. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6203. table.onCreate(ctx);
  6204. }
  6205. virtual void reset()
  6206. {
  6207. table.reset();
  6208. eof = false;
  6209. CRoxieServerActivity::reset();
  6210. }
  6211. virtual const void *nextInGroup()
  6212. {
  6213. ActivityTimer t(totalCycles, timeActivities);
  6214. while(!eof)
  6215. {
  6216. const void * next = input->nextInGroup();
  6217. if(!next)
  6218. {
  6219. if (table.count() == 0)
  6220. eof = true;
  6221. table.reset();
  6222. return NULL;
  6223. }
  6224. if(table.insert(next))
  6225. return next;
  6226. else
  6227. ReleaseRoxieRow(next);
  6228. }
  6229. return NULL;
  6230. }
  6231. };
  6232. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6233. {
  6234. public:
  6235. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6236. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6237. {
  6238. }
  6239. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6240. {
  6241. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6242. }
  6243. };
  6244. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6245. {
  6246. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6247. }
  6248. //=================================================================================
  6249. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6250. {
  6251. IHThorRollupArg &helper;
  6252. OwnedConstRoxieRow left;
  6253. OwnedConstRoxieRow prev;
  6254. OwnedConstRoxieRow right;
  6255. bool readFirstRow;
  6256. public:
  6257. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6258. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6259. {
  6260. readFirstRow = false;
  6261. }
  6262. ~CRoxieServerRollupActivity()
  6263. {
  6264. }
  6265. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6266. {
  6267. readFirstRow = false;
  6268. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6269. }
  6270. virtual void reset()
  6271. {
  6272. left.clear();
  6273. prev.clear();
  6274. right.clear();
  6275. CRoxieServerActivity::reset();
  6276. }
  6277. virtual bool needsAllocator() const { return true; }
  6278. virtual const void * nextInGroup()
  6279. {
  6280. ActivityTimer t(totalCycles, timeActivities);
  6281. if (!readFirstRow)
  6282. {
  6283. left.setown(input->nextInGroup());
  6284. prev.set(left);
  6285. readFirstRow = true;
  6286. }
  6287. loop
  6288. {
  6289. right.setown(input->nextInGroup());
  6290. if(!prev || !right || !helper.matches(prev,right))
  6291. {
  6292. const void * ret = left.getClear();
  6293. if(ret)
  6294. processed++;
  6295. left.setown(right.getClear());
  6296. prev.set(left);
  6297. return ret;
  6298. }
  6299. try
  6300. {
  6301. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6302. unsigned outSize = helper.transform(rowBuilder, left, right);
  6303. if (outSize)
  6304. left.setown(rowBuilder.finalizeRowClear(outSize));
  6305. if (helper.getFlags() & RFrolledismatchleft)
  6306. prev.set(left);
  6307. else
  6308. prev.set(right);
  6309. }
  6310. catch(IException * E)
  6311. {
  6312. throw makeWrappedException(E);
  6313. }
  6314. }
  6315. }
  6316. };
  6317. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6318. {
  6319. public:
  6320. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6321. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6322. {
  6323. }
  6324. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6325. {
  6326. return new CRoxieServerRollupActivity(this, _probeManager);
  6327. }
  6328. };
  6329. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6330. {
  6331. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6332. }
  6333. //=================================================================================
  6334. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6335. {
  6336. IHThorNormalizeArg &helper;
  6337. unsigned numThisRow;
  6338. unsigned curRow;
  6339. const void *buffer;
  6340. unsigned numProcessedLastGroup;
  6341. public:
  6342. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6343. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6344. {
  6345. buffer = NULL;
  6346. numThisRow = 0;
  6347. curRow = 0;
  6348. numProcessedLastGroup = 0;
  6349. }
  6350. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6351. {
  6352. numThisRow = 0;
  6353. curRow = 0;
  6354. numProcessedLastGroup = 0;
  6355. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6356. }
  6357. virtual void reset()
  6358. {
  6359. ReleaseClearRoxieRow(buffer);
  6360. CRoxieServerActivity::reset();
  6361. }
  6362. virtual bool needsAllocator() const { return true; }
  6363. virtual const void * nextInGroup()
  6364. {
  6365. ActivityTimer t(totalCycles, timeActivities);
  6366. loop
  6367. {
  6368. while (curRow == numThisRow)
  6369. {
  6370. if (buffer)
  6371. ReleaseClearRoxieRow(buffer);
  6372. buffer = input->nextInGroup();
  6373. if (!buffer && (processed == numProcessedLastGroup))
  6374. buffer = input->nextInGroup();
  6375. if (!buffer)
  6376. {
  6377. numProcessedLastGroup = processed;
  6378. return NULL;
  6379. }
  6380. curRow = 0;
  6381. numThisRow = helper.numExpandedRows(buffer);
  6382. }
  6383. try
  6384. {
  6385. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6386. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6387. if (actualSize != 0)
  6388. {
  6389. processed++;
  6390. return rowBuilder.finalizeRowClear(actualSize);
  6391. }
  6392. }
  6393. catch (IException *E)
  6394. {
  6395. throw makeWrappedException(E);
  6396. }
  6397. }
  6398. }
  6399. };
  6400. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6401. {
  6402. public:
  6403. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6404. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6405. {
  6406. }
  6407. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6408. {
  6409. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6410. }
  6411. };
  6412. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6413. {
  6414. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6415. }
  6416. //=================================================================================
  6417. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6418. {
  6419. IHThorNormalizeChildArg &helper;
  6420. unsigned numThisRow;
  6421. unsigned curRow;
  6422. const void *buffer;
  6423. unsigned numProcessedLastGroup;
  6424. INormalizeChildIterator * cursor;
  6425. const void * curChildRow;
  6426. bool advanceInput()
  6427. {
  6428. loop
  6429. {
  6430. ReleaseClearRoxieRow(buffer);
  6431. buffer = input->nextInGroup();
  6432. if (!buffer && (processed == numProcessedLastGroup))
  6433. buffer = input->nextInGroup();
  6434. if (!buffer)
  6435. {
  6436. numProcessedLastGroup = processed;
  6437. return false;
  6438. }
  6439. curChildRow = cursor->first(buffer);
  6440. if (curChildRow)
  6441. {
  6442. curRow = 0;
  6443. return true;
  6444. }
  6445. }
  6446. }
  6447. public:
  6448. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6449. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6450. {
  6451. buffer = NULL;
  6452. cursor = NULL;
  6453. numThisRow = 0;
  6454. curRow = 0;
  6455. numProcessedLastGroup = 0;
  6456. curChildRow = NULL;
  6457. }
  6458. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6459. {
  6460. numThisRow = 0;
  6461. curRow = 0;
  6462. numProcessedLastGroup = 0;
  6463. curChildRow = NULL;
  6464. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6465. cursor = helper.queryIterator();
  6466. }
  6467. virtual void stop(bool aborting)
  6468. {
  6469. CRoxieServerActivity::stop(aborting);
  6470. }
  6471. virtual void reset()
  6472. {
  6473. cursor = NULL;
  6474. ReleaseClearRoxieRow(buffer);
  6475. CRoxieServerActivity::reset();
  6476. }
  6477. virtual bool needsAllocator() const { return true; }
  6478. const void *nextInGroup()
  6479. {
  6480. ActivityTimer t(totalCycles, timeActivities);
  6481. loop
  6482. {
  6483. if (!buffer)
  6484. {
  6485. if (!advanceInput())
  6486. return NULL;
  6487. }
  6488. try
  6489. {
  6490. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6491. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6492. curChildRow = cursor->next();
  6493. if (!curChildRow)
  6494. ReleaseClearRoxieRow(buffer);
  6495. if (outSize != 0)
  6496. {
  6497. processed++;
  6498. return rowBuilder.finalizeRowClear(outSize);
  6499. }
  6500. }
  6501. catch (IException *E)
  6502. {
  6503. throw makeWrappedException(E);
  6504. }
  6505. }
  6506. }
  6507. };
  6508. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6509. {
  6510. public:
  6511. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6512. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6513. {
  6514. }
  6515. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6516. {
  6517. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6518. }
  6519. };
  6520. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6521. {
  6522. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6523. }
  6524. //=================================================================================
  6525. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6526. {
  6527. IHThorNormalizeLinkedChildArg &helper;
  6528. OwnedConstRoxieRow curParent;
  6529. OwnedConstRoxieRow curChild;
  6530. unsigned numProcessedLastGroup;
  6531. bool advanceInput()
  6532. {
  6533. loop
  6534. {
  6535. curParent.setown(input->nextInGroup());
  6536. if (!curParent && (processed == numProcessedLastGroup))
  6537. curParent.setown(input->nextInGroup());
  6538. if (!curParent)
  6539. {
  6540. numProcessedLastGroup = processed;
  6541. return false;
  6542. }
  6543. curChild.set(helper.first(curParent));
  6544. if (curChild)
  6545. return true;
  6546. }
  6547. }
  6548. public:
  6549. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6550. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6551. {
  6552. numProcessedLastGroup = 0;
  6553. }
  6554. ~CRoxieServerNormalizeLinkedChildActivity()
  6555. {
  6556. }
  6557. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6558. {
  6559. numProcessedLastGroup = 0;
  6560. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6561. }
  6562. virtual void reset()
  6563. {
  6564. curParent.clear();
  6565. curChild.clear();
  6566. CRoxieServerActivity::reset();
  6567. }
  6568. const void *nextInGroup()
  6569. {
  6570. ActivityTimer t(totalCycles, timeActivities);
  6571. loop
  6572. {
  6573. if (!curParent)
  6574. {
  6575. if (!advanceInput())
  6576. return NULL;
  6577. }
  6578. try
  6579. {
  6580. const void *ret = curChild.getClear();
  6581. curChild.set(helper.next());
  6582. if (!curChild)
  6583. curParent.clear();
  6584. if (ret)
  6585. {
  6586. processed++;
  6587. return ret;
  6588. }
  6589. }
  6590. catch (IException *E)
  6591. {
  6592. throw makeWrappedException(E);
  6593. }
  6594. }
  6595. }
  6596. };
  6597. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6598. {
  6599. public:
  6600. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6601. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6602. {
  6603. }
  6604. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6605. {
  6606. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6607. }
  6608. };
  6609. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6610. {
  6611. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6612. }
  6613. //=================================================================================
  6614. interface ISortAlgorithm : extends IInterface
  6615. {
  6616. virtual void prepare(IRoxieInput *input) = 0;
  6617. virtual const void *next() = 0;
  6618. virtual void reset() = 0;
  6619. };
  6620. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6621. {
  6622. protected:
  6623. unsigned curIndex;
  6624. ConstPointerArray sorted;
  6625. ICompare *compare;
  6626. public:
  6627. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6628. {
  6629. curIndex = 0;
  6630. }
  6631. virtual void prepare(IRoxieInput *input)
  6632. {
  6633. curIndex = 0;
  6634. if (input->nextGroup(sorted))
  6635. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6636. }
  6637. virtual const void *next()
  6638. {
  6639. if (sorted.isItem(curIndex))
  6640. return sorted.item(curIndex++);
  6641. return NULL;
  6642. }
  6643. virtual void reset()
  6644. {
  6645. while (sorted.isItem(curIndex))
  6646. ReleaseRoxieRow(sorted.item(curIndex++));
  6647. curIndex = 0;
  6648. sorted.kill();
  6649. }
  6650. };
  6651. class CStableQuickSortAlgorithm : public CQuickSortAlgorithm
  6652. {
  6653. public:
  6654. CStableQuickSortAlgorithm(ICompare *_compare) : CQuickSortAlgorithm(_compare)
  6655. {
  6656. }
  6657. virtual void prepare(IRoxieInput *input)
  6658. {
  6659. curIndex = 0;
  6660. if (input->nextGroup(sorted))
  6661. {
  6662. unsigned numRows = sorted.ordinality();
  6663. void **rows = const_cast<void * *>(sorted.getArray());
  6664. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6665. void **temp = (void **) tempAttr.bufferBase();
  6666. qsortvecstableinplace(rows, numRows, *compare, temp);
  6667. }
  6668. }
  6669. };
  6670. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6671. {
  6672. enum {
  6673. InitialSortElements = 0,
  6674. //The number of rows that can be added without entering a critical section, and therefore also the number
  6675. //of rows that might not get freed when memory gets tight.
  6676. CommitStep=32
  6677. };
  6678. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6679. roxiemem::RoxieSimpleInputRowArray sorted;
  6680. ICompare *compare;
  6681. IRoxieSlaveContext * ctx;
  6682. Owned<IDiskMerger> diskMerger;
  6683. Owned<IRowStream> diskReader;
  6684. IOutputMetaData *rowMeta;
  6685. unsigned activityId;
  6686. bool stable;
  6687. public:
  6688. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId, bool _stable)
  6689. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep, _activityId),
  6690. ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId), stable(_stable)
  6691. {
  6692. ctx->queryRowManager().addRowBuffer(this);
  6693. }
  6694. ~CSpillingQuickSortAlgorithm()
  6695. {
  6696. ctx->queryRowManager().removeRowBuffer(this);
  6697. diskReader.clear();
  6698. }
  6699. virtual void prepare(IRoxieInput *input)
  6700. {
  6701. loop
  6702. {
  6703. const void * next = input->nextInGroup();
  6704. if (!next)
  6705. break;
  6706. if (!rowsToSort.append(next))
  6707. {
  6708. {
  6709. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6710. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6711. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6712. //rows first).
  6713. if (rowsToSort.numCommitted() != 0)
  6714. {
  6715. rowsToSort.flush();
  6716. spillRows();
  6717. }
  6718. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6719. //spillRows() cannot shift active row pointer since it can be called from any thread
  6720. rowsToSort.flush();
  6721. }
  6722. if (!rowsToSort.append(next))
  6723. {
  6724. ReleaseRoxieRow(next);
  6725. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6726. }
  6727. }
  6728. }
  6729. rowsToSort.flush();
  6730. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6731. if (diskMerger)
  6732. {
  6733. spillRows();
  6734. rowsToSort.kill();
  6735. diskReader.setown(diskMerger->merge(compare));
  6736. }
  6737. else
  6738. {
  6739. unsigned numRows = rowsToSort.numCommitted();
  6740. if (numRows)
  6741. {
  6742. void ** rows = const_cast<void * *>(rowsToSort.getBlock(numRows));
  6743. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6744. if (stable)
  6745. {
  6746. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6747. void **temp = (void **) tempAttr.bufferBase();
  6748. qsortvecstableinplace(rows, numRows, *compare, temp);
  6749. }
  6750. else
  6751. qsortvec(rows, numRows, *compare);
  6752. }
  6753. sorted.transferFrom(rowsToSort);
  6754. }
  6755. }
  6756. virtual const void *next()
  6757. {
  6758. if(diskReader)
  6759. return diskReader->nextRow();
  6760. return sorted.dequeue();
  6761. }
  6762. virtual void reset()
  6763. {
  6764. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6765. //fewer heap allocations with not freeing up the memory from large group sorts.
  6766. rowsToSort.clearRows();
  6767. sorted.kill();
  6768. //Disk reader must be cleared before the merger - or the files may still be locked.
  6769. diskReader.clear();
  6770. diskMerger.clear();
  6771. }
  6772. //interface roxiemem::IBufferedRowCallback
  6773. virtual unsigned getSpillCost() const
  6774. {
  6775. //Spill global sorts before grouped sorts
  6776. if (rowMeta->isGrouped())
  6777. return 20;
  6778. return 10;
  6779. }
  6780. virtual bool freeBufferedRows(bool critical)
  6781. {
  6782. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6783. return spillRows();
  6784. }
  6785. protected:
  6786. bool spillRows()
  6787. {
  6788. unsigned numRows = rowsToSort.numCommitted();
  6789. if (numRows == 0)
  6790. return false;
  6791. const void * * rows = rowsToSort.getBlock(numRows);
  6792. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6793. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6794. for (unsigned i= 0; i < numRows; i++)
  6795. {
  6796. out->putRow(rows[i]);
  6797. }
  6798. rowsToSort.noteSpilled(numRows);
  6799. return true;
  6800. }
  6801. IDiskMerger * queryMerger()
  6802. {
  6803. if (!diskMerger)
  6804. {
  6805. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6806. StringBuffer spillBasename;
  6807. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%" I64F "u", seq);
  6808. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6809. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6810. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6811. }
  6812. return diskMerger;
  6813. }
  6814. };
  6815. #define INSERTION_SORT_BLOCKSIZE 1024
  6816. class SortedBlock : public CInterface, implements IInterface
  6817. {
  6818. unsigned sequence;
  6819. const void **rows;
  6820. unsigned length;
  6821. unsigned pos;
  6822. SortedBlock(const SortedBlock &);
  6823. public:
  6824. IMPLEMENT_IINTERFACE;
  6825. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6826. {
  6827. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6828. length = 0;
  6829. pos = 0;
  6830. }
  6831. ~SortedBlock()
  6832. {
  6833. while (pos < length)
  6834. ReleaseRoxieRow(rows[pos++]);
  6835. ReleaseRoxieRow(rows);
  6836. }
  6837. int compareTo(SortedBlock *r, ICompare *compare)
  6838. {
  6839. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6840. if (!rc)
  6841. rc = sequence - r->sequence;
  6842. return rc;
  6843. }
  6844. const void *next()
  6845. {
  6846. if (pos < length)
  6847. return rows[pos++];
  6848. else
  6849. return NULL;
  6850. }
  6851. inline bool eof()
  6852. {
  6853. return pos==length;
  6854. }
  6855. bool insert(const void *next, ICompare *_compare )
  6856. {
  6857. unsigned b = length;
  6858. if (b == INSERTION_SORT_BLOCKSIZE)
  6859. return false;
  6860. else if (b < 7)
  6861. {
  6862. while (b)
  6863. {
  6864. if (_compare->docompare(next, rows[b-1]) >= 0)
  6865. break;
  6866. b--;
  6867. }
  6868. if (b != length)
  6869. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6870. rows[b] = next;
  6871. length++;
  6872. return true;
  6873. }
  6874. else
  6875. {
  6876. unsigned int a = 0;
  6877. while ((int)a<b)
  6878. {
  6879. int i = (a+b)/2;
  6880. int rc = _compare->docompare(next, rows[i]);
  6881. if (rc>=0)
  6882. a = i+1;
  6883. else
  6884. b = i;
  6885. }
  6886. if (a != length)
  6887. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6888. rows[a] = next;
  6889. length++;
  6890. return true;
  6891. }
  6892. }
  6893. };
  6894. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6895. {
  6896. SortedBlock *curBlock;
  6897. unsigned blockNo;
  6898. IArrayOf<SortedBlock> blocks;
  6899. unsigned activityId;
  6900. IRowManager *rowManager;
  6901. ICompare *compare;
  6902. void newBlock()
  6903. {
  6904. blocks.append(*curBlock);
  6905. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6906. }
  6907. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6908. {
  6909. return l.compareTo(&r, compare);
  6910. }
  6911. void makeHeap()
  6912. {
  6913. /* Permute blocks to establish the heap property
  6914. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6915. The children of p must both be greater than or equal to p
  6916. The parent of a child c is given by p = (c-1)/2
  6917. */
  6918. unsigned i;
  6919. unsigned n = blocks.length();
  6920. SortedBlock **s = blocks.getArray();
  6921. for (i=1; i<n; i++)
  6922. {
  6923. SortedBlock * r = s[i];
  6924. int c = i; /* child */
  6925. while (c > 0)
  6926. {
  6927. int p = (c-1)/2; /* parent */
  6928. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6929. break;
  6930. s[c] = s[p];
  6931. s[p] = r;
  6932. c = p;
  6933. }
  6934. }
  6935. }
  6936. void remakeHeap()
  6937. {
  6938. /* The row associated with block[0] will have changed
  6939. This code restores the heap property
  6940. */
  6941. unsigned p = 0; /* parent */
  6942. unsigned n = blocks.length();
  6943. SortedBlock **s = blocks.getArray();
  6944. while (1)
  6945. {
  6946. unsigned c = p*2 + 1; /* child */
  6947. if ( c >= n )
  6948. break;
  6949. /* Select smaller child */
  6950. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6951. /* If child is greater or equal than parent then we are done */
  6952. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6953. break;
  6954. /* Swap parent and child */
  6955. SortedBlock *r = s[c];
  6956. s[c] = s[p];
  6957. s[p] = r;
  6958. /* child becomes parent */
  6959. p = c;
  6960. }
  6961. }
  6962. public:
  6963. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6964. : compare(_compare)
  6965. {
  6966. rowManager = _rowManager;
  6967. activityId = _activityId;
  6968. curBlock = NULL;
  6969. blockNo = 0;
  6970. }
  6971. virtual void reset()
  6972. {
  6973. blocks.kill();
  6974. delete curBlock;
  6975. curBlock = NULL;
  6976. blockNo = 0;
  6977. }
  6978. virtual void prepare(IRoxieInput *input)
  6979. {
  6980. blockNo = 0;
  6981. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6982. loop
  6983. {
  6984. const void *next = input->nextInGroup();
  6985. if (!next)
  6986. break;
  6987. if (!curBlock->insert(next, compare))
  6988. {
  6989. newBlock();
  6990. curBlock->insert(next, compare);
  6991. }
  6992. }
  6993. if (blockNo > 1)
  6994. {
  6995. blocks.append(*curBlock);
  6996. curBlock = NULL;
  6997. makeHeap();
  6998. }
  6999. }
  7000. virtual const void * next()
  7001. {
  7002. const void *ret;
  7003. if (blockNo==1) // single block case..
  7004. {
  7005. ret = curBlock->next();
  7006. }
  7007. else if (blocks.length())
  7008. {
  7009. SortedBlock &top = blocks.item(0);
  7010. ret = top.next();
  7011. if (top.eof())
  7012. blocks.replace(blocks.popGet(), 0);
  7013. remakeHeap();
  7014. }
  7015. else
  7016. ret = NULL;
  7017. return ret;
  7018. }
  7019. };
  7020. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  7021. {
  7022. unsigned curIndex;
  7023. ConstPointerArray sorted;
  7024. bool inputAlreadySorted;
  7025. IntArray sequences;
  7026. bool eof;
  7027. ICompare *compare;
  7028. #ifdef _CHECK_HEAPSORT
  7029. void checkHeap() const
  7030. {
  7031. unsigned n = sorted.ordinality();
  7032. if (n)
  7033. {
  7034. ICompare *_compare = compare;
  7035. void **s = sorted.getArray();
  7036. int *sq = sequences.getArray();
  7037. unsigned p;
  7038. #if 0
  7039. CTXLOG("------------------------%d entries-----------------", n);
  7040. for (p = 0; p < n; p++)
  7041. {
  7042. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  7043. }
  7044. #endif
  7045. for (p = 0; p < n; p++)
  7046. {
  7047. unsigned c = p*2+1;
  7048. if (c<n)
  7049. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7050. c++;
  7051. if (c<n)
  7052. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7053. }
  7054. }
  7055. }
  7056. #else
  7057. inline void checkHeap() const {}
  7058. #endif
  7059. const void *removeHeap()
  7060. {
  7061. unsigned n = sorted.ordinality();
  7062. if (n)
  7063. {
  7064. const void *ret = sorted.item(0);
  7065. if (n > 1 && ret)
  7066. {
  7067. ICompare *_compare = compare;
  7068. const void **s = sorted.getArray();
  7069. int *sq = sequences.getArray();
  7070. unsigned v = 0; // vacancy
  7071. loop
  7072. {
  7073. unsigned c = 2*v + 1;
  7074. if (c < n)
  7075. {
  7076. unsigned f = c; // favourite to fill it
  7077. c++;
  7078. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  7079. f = c;
  7080. sq[v] = sq[f];
  7081. if ((s[v] = s[f]) != NULL)
  7082. v = f;
  7083. else
  7084. break;
  7085. }
  7086. else
  7087. {
  7088. s[v] = NULL;
  7089. break;
  7090. }
  7091. }
  7092. }
  7093. checkHeap();
  7094. return ret;
  7095. }
  7096. else
  7097. return NULL;
  7098. }
  7099. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  7100. {
  7101. int rc = _compare->docompare(s[l], s[r]);
  7102. if (!rc)
  7103. rc = sq[l] - sq[r];
  7104. return rc;
  7105. }
  7106. void insertHeap(const void *next)
  7107. {
  7108. // Upside-down heap sort
  7109. // Maintain a heap where every parent is lower than each of its children
  7110. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  7111. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  7112. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  7113. // Nice features:
  7114. // 1. Deterministic
  7115. // 2. Sort time can be overlapped with upstream/downstream processes - there is no delay between receiving last record from input and deliveriing first to output
  7116. // 3. Already sorted case can be spotted at zero cost while reading.
  7117. // 4. If you don't read all the results, you don't have to complete the sort
  7118. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  7119. unsigned n = sorted.ordinality();
  7120. sorted.append(next);
  7121. sequences.append(n);
  7122. if (!n)
  7123. return;
  7124. ICompare *_compare = compare;
  7125. const void **s = sorted.getArray();
  7126. if (inputAlreadySorted)
  7127. {
  7128. if (_compare->docompare(next, s[n-1]) >= 0)
  7129. return;
  7130. else
  7131. {
  7132. // MORE - could delay creating sequences until now...
  7133. inputAlreadySorted = false;
  7134. }
  7135. }
  7136. int *sq = sequences.getArray();
  7137. unsigned q = n;
  7138. while (n)
  7139. {
  7140. unsigned parent = (n-1) / 2;
  7141. const void *p = s[parent];
  7142. if (_compare->docompare(p, next) <= 0)
  7143. break;
  7144. s[n] = p;
  7145. sq[n] = sq[parent];
  7146. s[parent] = next;
  7147. sq[parent] = q;
  7148. n = parent;
  7149. }
  7150. }
  7151. public:
  7152. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  7153. {
  7154. inputAlreadySorted = true;
  7155. curIndex = 0;
  7156. eof = false;
  7157. }
  7158. virtual void reset()
  7159. {
  7160. eof = false;
  7161. if (inputAlreadySorted)
  7162. {
  7163. while (sorted.isItem(curIndex))
  7164. ReleaseRoxieRow(sorted.item(curIndex++));
  7165. sorted.kill();
  7166. }
  7167. else
  7168. {
  7169. ReleaseRoxieRowSet(sorted);
  7170. }
  7171. inputAlreadySorted = true;
  7172. sequences.kill();
  7173. }
  7174. virtual void prepare(IRoxieInput *input)
  7175. {
  7176. inputAlreadySorted = true;
  7177. curIndex = 0;
  7178. eof = false;
  7179. assertex(sorted.ordinality()==0);
  7180. const void *next = input->nextInGroup();
  7181. if (!next)
  7182. {
  7183. eof = true;
  7184. return;
  7185. }
  7186. loop
  7187. {
  7188. insertHeap(next);
  7189. next = input->nextInGroup();
  7190. if (!next)
  7191. break;
  7192. }
  7193. checkHeap();
  7194. }
  7195. virtual const void * next()
  7196. {
  7197. if (inputAlreadySorted)
  7198. {
  7199. if (sorted.isItem(curIndex))
  7200. {
  7201. return sorted.item(curIndex++);
  7202. }
  7203. else
  7204. return NULL;
  7205. }
  7206. else
  7207. return removeHeap();
  7208. }
  7209. };
  7210. typedef enum {heapSort, insertionSort, quickSort, stableQuickSort, spillingQuickSort, stableSpillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7211. class CRoxieServerSortActivity : public CRoxieServerActivity
  7212. {
  7213. protected:
  7214. IHThorSortArg &helper;
  7215. ICompare *compare;
  7216. Owned<ISortAlgorithm> sorter;
  7217. bool readInput;
  7218. RoxieSortAlgorithm sortAlgorithm;
  7219. unsigned sortFlags;
  7220. public:
  7221. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7222. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7223. {
  7224. compare = helper.queryCompare();
  7225. readInput = false;
  7226. }
  7227. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7228. {
  7229. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7230. switch (sortAlgorithm)
  7231. {
  7232. case heapSort:
  7233. sorter.setown(new CHeapSortAlgorithm(compare));
  7234. break;
  7235. case insertionSort:
  7236. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7237. break;
  7238. case quickSort:
  7239. sorter.setown(new CQuickSortAlgorithm(compare));
  7240. break;
  7241. case stableQuickSort:
  7242. sorter.setown(new CStableQuickSortAlgorithm(compare));
  7243. break;
  7244. case spillingQuickSort:
  7245. case stableSpillingQuickSort:
  7246. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, sortAlgorithm==stableSpillingQuickSort));
  7247. break;
  7248. case unknownSort:
  7249. sorter.clear(); // create it later....
  7250. break;
  7251. default:
  7252. throwUnexpected();
  7253. break;
  7254. }
  7255. }
  7256. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7257. {
  7258. assertex(!readInput);
  7259. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7260. }
  7261. virtual void reset()
  7262. {
  7263. if (sorter)
  7264. sorter->reset();
  7265. readInput = false;
  7266. CRoxieServerActivity::reset();
  7267. }
  7268. virtual const void * nextInGroup()
  7269. {
  7270. ActivityTimer t(totalCycles, timeActivities);
  7271. if (!readInput)
  7272. {
  7273. if (sortAlgorithm == unknownSort)
  7274. {
  7275. sorter.clear();
  7276. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7277. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7278. if (useAlgorithm)
  7279. {
  7280. if (stricmp(useAlgorithm, "quicksort")==0)
  7281. {
  7282. switch (sortFlags & (TAFstable|TAFspill))
  7283. {
  7284. case 0: sortAlgorithm = quickSort; break;
  7285. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7286. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7287. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7288. }
  7289. }
  7290. else if (stricmp(useAlgorithm, "heapsort")==0)
  7291. sorter.setown(new CHeapSortAlgorithm(compare));
  7292. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7293. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7294. else
  7295. {
  7296. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7297. if (sortFlags & TAFspill)
  7298. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, (sortFlags & TAFstable) != 0));
  7299. else if (sortFlags & TAFunstable)
  7300. sorter.setown(new CQuickSortAlgorithm(compare));
  7301. else
  7302. sorter.setown(new CHeapSortAlgorithm(compare));
  7303. }
  7304. }
  7305. else
  7306. sorter.setown(new CHeapSortAlgorithm(compare)); // shouldn't really happen but there was a vintage of codegen that did not set the flag when algorithm not specified...
  7307. }
  7308. sorter->prepare(input);
  7309. readInput = true;
  7310. }
  7311. const void *ret = sorter->next();
  7312. if (ret)
  7313. processed++;
  7314. else
  7315. {
  7316. sorter->reset();
  7317. readInput = false; // ready for next group
  7318. }
  7319. return ret;
  7320. }
  7321. };
  7322. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7323. {
  7324. RoxieSortAlgorithm sortAlgorithm;
  7325. unsigned sortFlags;
  7326. bool forceSpill;
  7327. public:
  7328. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7329. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7330. {
  7331. forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  7332. if (forceSpill)
  7333. {
  7334. sortAlgorithm = stableSpillingQuickSort;
  7335. sortFlags = TAFstable|TAFspill;
  7336. }
  7337. else
  7338. {
  7339. sortAlgorithm = heapSort;
  7340. sortFlags = TAFstable;
  7341. }
  7342. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7343. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7344. if (sortMethod)
  7345. {
  7346. sortFlags = sortMethod->getAlgorithmFlags();
  7347. if (forceSpill)
  7348. sortFlags |= TAFspill;
  7349. if (sortFlags & TAFspill)
  7350. sortAlgorithm = stableSpillingQuickSort;
  7351. else if (sortFlags & TAFunstable)
  7352. sortAlgorithm = quickSort;
  7353. if (!(sortFlags & TAFconstant))
  7354. sortAlgorithm = unknownSort;
  7355. else
  7356. {
  7357. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7358. if (useAlgorithm)
  7359. {
  7360. if (stricmp(useAlgorithm, "quicksort")==0)
  7361. {
  7362. switch (sortFlags & (TAFstable|TAFspill))
  7363. {
  7364. case 0: sortAlgorithm = quickSort; break;
  7365. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7366. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7367. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7368. }
  7369. }
  7370. else if (stricmp(useAlgorithm, "heapsort")==0)
  7371. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7372. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7373. sortAlgorithm = insertionSort;
  7374. else
  7375. {
  7376. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7377. if (sortFlags & TAFunstable)
  7378. sortAlgorithm = quickSort;
  7379. else
  7380. sortAlgorithm = heapSort;
  7381. }
  7382. }
  7383. }
  7384. }
  7385. }
  7386. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7387. {
  7388. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7389. }
  7390. };
  7391. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7392. {
  7393. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7394. }
  7395. //=====================================================================================================
  7396. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7397. {
  7398. IHThorSortedArg &helper;
  7399. ICompare * compare;
  7400. const void *prev;
  7401. IRangeCompare * stepCompare;
  7402. public:
  7403. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7404. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7405. {
  7406. prev = NULL;
  7407. compare = helper.queryCompare();
  7408. stepCompare = NULL;
  7409. }
  7410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7411. {
  7412. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7413. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7414. if (stepMeta)
  7415. stepCompare = stepMeta->queryCompare();
  7416. prev = NULL;
  7417. }
  7418. virtual void reset()
  7419. {
  7420. ReleaseClearRoxieRow(prev);
  7421. CRoxieServerActivity::reset();
  7422. }
  7423. virtual const void * nextInGroup()
  7424. {
  7425. ActivityTimer t(totalCycles, timeActivities);
  7426. const void *ret = input->nextInGroup();
  7427. if (ret && prev && compare->docompare(prev, ret) > 0)
  7428. {
  7429. // MORE - better to give mismatching rows that indexes?
  7430. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7431. }
  7432. ReleaseRoxieRow(prev);
  7433. prev = ret;
  7434. if (ret)
  7435. {
  7436. LinkRoxieRow(prev);
  7437. processed++;
  7438. }
  7439. return ret;
  7440. }
  7441. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7442. {
  7443. ActivityTimer t(totalCycles, timeActivities);
  7444. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7445. if (ret && prev && compare->docompare(prev, ret) > 0)
  7446. {
  7447. // MORE - better to give mismatching rows that indexes?
  7448. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7449. }
  7450. ReleaseRoxieRow(prev);
  7451. prev = ret;
  7452. if (ret)
  7453. {
  7454. LinkRoxieRow(prev);
  7455. processed++;
  7456. }
  7457. return ret;
  7458. }
  7459. IInputSteppingMeta * querySteppingMeta()
  7460. {
  7461. return input->querySteppingMeta();
  7462. }
  7463. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7464. {
  7465. return input->gatherConjunctions(collector);
  7466. }
  7467. virtual void resetEOF()
  7468. {
  7469. input->resetEOF();
  7470. }
  7471. };
  7472. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7473. {
  7474. public:
  7475. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7476. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7477. {
  7478. }
  7479. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7480. {
  7481. return new CRoxieServerSortedActivity(this, _probeManager);
  7482. }
  7483. };
  7484. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7485. {
  7486. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7487. }
  7488. //=====================================================================================================
  7489. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7490. {
  7491. /*
  7492. BE VERY CAREFUL - this code is tricky.
  7493. Note that starts and stops (and resets) can occur in strange orders
  7494. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7495. The last stop should call the upstream stop.
  7496. The first reset should call the upstream reset.
  7497. 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
  7498. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7499. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7500. ignored in the minIndex calculation
  7501. */
  7502. public:
  7503. IHThorArg &helper;
  7504. unsigned activeOutputs;
  7505. unsigned numOutputs;
  7506. unsigned numOriginalOutputs;
  7507. QueueOf<const void, true> buffer;
  7508. CriticalSection crit;
  7509. CriticalSection crit2;
  7510. unsigned tailIdx;
  7511. unsigned headIdx;
  7512. Owned<IException> error;
  7513. class OutputAdaptor : public CInterface, implements IRoxieInput
  7514. {
  7515. bool eof, eofpending, stopped;
  7516. public:
  7517. CRoxieServerThroughSpillActivity *parent;
  7518. unsigned idx;
  7519. unsigned oid;
  7520. unsigned processed;
  7521. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7522. public:
  7523. IMPLEMENT_IINTERFACE;
  7524. OutputAdaptor()
  7525. {
  7526. parent = NULL;
  7527. oid = 0;
  7528. idx = 0;
  7529. processed = 0;
  7530. totalCycles = 0;
  7531. eofpending = false;
  7532. eof = false;
  7533. stopped = false;
  7534. }
  7535. ~OutputAdaptor()
  7536. {
  7537. if (traceStartStop)
  7538. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7539. if (processed && parent && parent->factory)
  7540. {
  7541. parent->factory->noteProcessed(oid, processed);
  7542. if (parent->ctx)
  7543. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  7544. }
  7545. }
  7546. void init()
  7547. {
  7548. if (traceStartStop)
  7549. DBGLOG("%p init Input adaptor %d", this, oid);
  7550. idx = 0;
  7551. processed = 0;
  7552. eofpending = false;
  7553. eof = false;
  7554. stopped = false;
  7555. }
  7556. virtual unsigned queryId() const
  7557. {
  7558. return parent->queryId();
  7559. }
  7560. virtual IRoxieServerActivity *queryActivity()
  7561. {
  7562. return parent;
  7563. }
  7564. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7565. {
  7566. return parent->queryIndexReadActivity();
  7567. }
  7568. virtual unsigned __int64 queryTotalCycles() const
  7569. {
  7570. return totalCycles;
  7571. }
  7572. virtual unsigned __int64 queryLocalCycles() const
  7573. {
  7574. return 0; // Should never be called
  7575. }
  7576. virtual IRoxieInput *queryInput(unsigned idx) const
  7577. {
  7578. return parent->queryInput(idx);
  7579. }
  7580. virtual const void * nextInGroup()
  7581. {
  7582. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7583. if (eof)
  7584. return NULL;
  7585. const void *ret = parent->readBuffered(idx, oid);
  7586. #ifdef TRACE_SPLIT
  7587. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7588. #endif
  7589. if (ret)
  7590. {
  7591. processed++;
  7592. eofpending = false;
  7593. }
  7594. else if (eofpending)
  7595. eof = true;
  7596. else
  7597. eofpending = true;
  7598. return ret;
  7599. }
  7600. virtual IOutputMetaData * queryOutputMeta() const
  7601. {
  7602. return parent->queryOutputMeta();
  7603. }
  7604. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7605. {
  7606. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7607. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7608. // for minIndex to give the correct answers
  7609. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7610. if (traceStartStop)
  7611. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7612. parent->start(oid, parentExtractSize, parentExtract, paused);
  7613. }
  7614. virtual void stop(bool aborting)
  7615. {
  7616. if (traceStartStop)
  7617. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7618. if (!stopped)
  7619. {
  7620. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7621. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7622. }
  7623. };
  7624. virtual void reset()
  7625. {
  7626. if (traceStartStop)
  7627. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7628. parent->reset(oid);
  7629. idx = 0; // value should not be relevant really but this is the safest...
  7630. stopped = false;
  7631. };
  7632. virtual void resetEOF()
  7633. {
  7634. parent->resetEOF();
  7635. }
  7636. virtual void checkAbort()
  7637. {
  7638. parent->checkAbort();
  7639. }
  7640. } *adaptors;
  7641. bool *used;
  7642. unsigned nextFreeOutput()
  7643. {
  7644. unsigned i = numOutputs;
  7645. while (i)
  7646. {
  7647. i--;
  7648. if (!used[i])
  7649. return i;
  7650. }
  7651. throwUnexpected();
  7652. }
  7653. unsigned minIndex(unsigned exceptOid)
  7654. {
  7655. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7656. // this is trying to determine whether any of the adaptors will in the future read a given record
  7657. unsigned minIdx = (unsigned) -1;
  7658. for (unsigned i = 0; i < numOutputs; i++)
  7659. {
  7660. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7661. minIdx = adaptors[i].idx;
  7662. }
  7663. return minIdx;
  7664. }
  7665. inline bool isLastTailReader(unsigned exceptOid)
  7666. {
  7667. for (unsigned i = 0; i < numOutputs; i++)
  7668. {
  7669. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7670. return false;
  7671. }
  7672. return true;
  7673. }
  7674. void initOutputs()
  7675. {
  7676. activeOutputs = numOutputs;
  7677. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7678. if (used[i])
  7679. adaptors[i].init();
  7680. state = STATEstarting;
  7681. }
  7682. public:
  7683. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7684. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7685. {
  7686. numOriginalOutputs = numOutputs;
  7687. adaptors = new OutputAdaptor[numOutputs];
  7688. used = new bool[numOutputs];
  7689. for (unsigned i = 0; i < numOutputs; i++)
  7690. {
  7691. adaptors[i].parent = this;
  7692. adaptors[i].oid = i;
  7693. used[i] = false;
  7694. }
  7695. tailIdx = 0;
  7696. headIdx = 0;
  7697. activeOutputs = numOutputs;
  7698. }
  7699. ~CRoxieServerThroughSpillActivity()
  7700. {
  7701. delete [] adaptors;
  7702. delete [] used;
  7703. }
  7704. const void *readBuffered(unsigned &idx, unsigned oid)
  7705. {
  7706. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7707. const unsigned curIdx = idx;
  7708. if (curIdx == headIdx) // test once without getting the crit2 sec
  7709. {
  7710. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7711. if (curIdx == headIdx) // test again now that we have it
  7712. {
  7713. 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
  7714. if (error)
  7715. throw error.getLink();
  7716. try
  7717. {
  7718. const void *row = input->nextInGroup();
  7719. if (activeOutputs==1)
  7720. {
  7721. #ifdef TRACE_SPLIT
  7722. CTXLOG("spill %d optimised return of %p", activityId, row);
  7723. #endif
  7724. headIdx++;
  7725. idx++;
  7726. return row; // optimization for the case where only one output still active.
  7727. }
  7728. CriticalBlock b(crit);
  7729. headIdx++;
  7730. idx++;
  7731. if (activeOutputs==1)
  7732. return row; // optimization for the case where only one output still active.
  7733. buffer.enqueue(row);
  7734. if (row) LinkRoxieRow(row);
  7735. return row;
  7736. }
  7737. catch (IException *E)
  7738. {
  7739. #ifdef TRACE_SPLIT
  7740. CTXLOG("spill %d caught exception", activityId);
  7741. #endif
  7742. error.set(E);
  7743. throw;
  7744. }
  7745. catch (...)
  7746. {
  7747. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7748. error.set(E);
  7749. throw E;
  7750. }
  7751. }
  7752. }
  7753. CriticalBlock b(crit);
  7754. 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
  7755. unsigned lidx = curIdx - tailIdx;
  7756. idx++;
  7757. if (!lidx)
  7758. {
  7759. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7760. // 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
  7761. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7762. {
  7763. tailIdx++;
  7764. const void *ret = buffer.dequeue(); // no need to link - last puller
  7765. #ifdef TRACE_SPLIT
  7766. CTXLOG("last puller return of %p", ret);
  7767. #endif
  7768. return ret;
  7769. }
  7770. }
  7771. const void *ret = buffer.item(lidx);
  7772. if (ret) LinkRoxieRow(ret);
  7773. #ifdef TRACE_SPLIT
  7774. CTXLOG("standard return of %p", ret);
  7775. #endif
  7776. return ret;
  7777. }
  7778. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7779. {
  7780. CriticalBlock b(crit);
  7781. if (error)
  7782. throw error.getLink();
  7783. if (factory)
  7784. factory->noteStarted(oid);
  7785. if (traceStartStop)
  7786. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7787. if (state != STATEstarted)
  7788. {
  7789. if (state != STATEstarting)
  7790. initOutputs();
  7791. tailIdx = 0;
  7792. headIdx = 0;
  7793. error.clear();
  7794. try
  7795. {
  7796. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7797. }
  7798. catch (IException *E)
  7799. {
  7800. #ifdef TRACE_SPLIT
  7801. CTXLOG("spill %d caught exception in start", activityId);
  7802. #endif
  7803. error.set(E);
  7804. throw;
  7805. }
  7806. catch (...)
  7807. {
  7808. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7809. error.set(E);
  7810. throw E;
  7811. }
  7812. }
  7813. }
  7814. void stop(unsigned oid, unsigned & idx, bool aborting)
  7815. {
  7816. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7817. CriticalBlock b(crit);
  7818. #ifdef TRACE_STARTSTOP
  7819. if (traceStartStop)
  7820. {
  7821. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7822. if (watchActivityId && watchActivityId==activityId)
  7823. {
  7824. CTXLOG("WATCH: stop %d", activityId);
  7825. }
  7826. }
  7827. #endif
  7828. if (state != STATEstarting && state != STATEstarted)
  7829. initOutputs();
  7830. if (activeOutputs > 1)
  7831. {
  7832. if (tailIdx==idx)
  7833. {
  7834. // Discard all buffered rows that are there purely for this adaptor to read them
  7835. unsigned min = minIndex(oid);
  7836. if (min != (unsigned) -1)
  7837. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7838. // Should never happen though if there are still some active.
  7839. // there may be a small window where adaptors are blocked on the semaphore...
  7840. {
  7841. #ifdef TRACE_SPLIT
  7842. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7843. #endif
  7844. while (tailIdx < min)
  7845. {
  7846. ReleaseRoxieRow(buffer.dequeue());
  7847. tailIdx++;
  7848. }
  7849. }
  7850. }
  7851. activeOutputs--;
  7852. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7853. return;
  7854. }
  7855. #ifdef TRACE_SPLIT
  7856. CTXLOG("%p: All outputs done", this);
  7857. #endif
  7858. activeOutputs = numOutputs;
  7859. CRoxieServerActivity::stop(aborting);
  7860. };
  7861. void reset(unsigned oid)
  7862. {
  7863. if (traceStartStop)
  7864. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7865. activeOutputs = numOutputs;
  7866. while (buffer.ordinality())
  7867. ReleaseRoxieRow(buffer.dequeue());
  7868. error.clear();
  7869. if (state != STATEreset) // make sure input is only reset once
  7870. CRoxieServerActivity::reset();
  7871. };
  7872. virtual const void *nextInGroup()
  7873. {
  7874. throwUnexpected(); // Internal logic error - we are not anybody's input
  7875. }
  7876. virtual IOutputMetaData * queryOutputMeta() const
  7877. {
  7878. // if (outputMeta)
  7879. // return outputMeta;
  7880. // else
  7881. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7882. }
  7883. virtual IRoxieInput *queryOutput(unsigned idx)
  7884. {
  7885. if (idx==(unsigned)-1)
  7886. idx = nextFreeOutput(); // MORE - what is this used for?
  7887. assertex(idx < numOriginalOutputs);
  7888. assertex(!used[idx]);
  7889. used[idx] = true;
  7890. return &adaptors[idx];
  7891. }
  7892. virtual void resetOutputsUsed()
  7893. {
  7894. numOutputs = 1;
  7895. activeOutputs = 1;
  7896. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7897. }
  7898. virtual void noteOutputUsed()
  7899. {
  7900. assertex(numOutputs < numOriginalOutputs);
  7901. numOutputs++;
  7902. activeOutputs = numOutputs;
  7903. }
  7904. virtual bool isPassThrough()
  7905. {
  7906. return numOutputs==1;
  7907. }
  7908. };
  7909. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7910. {
  7911. public:
  7912. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7913. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7914. {
  7915. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7916. setNumOutputs(helper->getTempUsageCount() + 1);
  7917. }
  7918. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7919. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7920. {
  7921. setNumOutputs(_numOutputs);
  7922. }
  7923. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7924. {
  7925. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7926. }
  7927. };
  7928. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7929. {
  7930. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7931. }
  7932. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7933. {
  7934. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7935. }
  7936. //----------------------------------------------------------------------------------------------
  7937. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7938. {
  7939. public:
  7940. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7941. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7942. {
  7943. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7944. setNumOutputs(helper->numBranches());
  7945. }
  7946. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7947. {
  7948. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7949. }
  7950. };
  7951. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7952. {
  7953. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7954. }
  7955. //=====================================================================================================
  7956. #define PIPE_BUFSIZE 0x8000
  7957. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7958. {
  7959. StringBuffer msg;
  7960. if(pipe->hasError())
  7961. {
  7962. try
  7963. {
  7964. char error[512];
  7965. size32_t sz = pipe->readError(sizeof(error), error);
  7966. if(sz && sz!=(size32_t)-1)
  7967. msg.append(", stderr: '").append(sz, error).append("'");
  7968. }
  7969. catch (IException *e)
  7970. {
  7971. EXCLOG(e, "Error reading pipe stderr");
  7972. e->Release();
  7973. }
  7974. }
  7975. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7976. }
  7977. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7978. {
  7979. IHThorPipeReadArg &helper;
  7980. Owned<IPipeProcess> pipe;
  7981. StringAttr pipeCommand;
  7982. Owned<IOutputRowDeserializer> rowDeserializer;
  7983. Owned<IReadRowStream> readTransformer;
  7984. bool groupSignalled;
  7985. public:
  7986. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7987. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7988. {
  7989. groupSignalled = true;
  7990. }
  7991. virtual bool needsAllocator() const { return true; }
  7992. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7993. {
  7994. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7995. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7996. }
  7997. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7998. {
  7999. groupSignalled = true; // i.e. don't start with a NULL row
  8000. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8001. if (!readTransformer)
  8002. {
  8003. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8004. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8005. }
  8006. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8007. openPipe(pipeProgram);
  8008. }
  8009. virtual void stop(bool aborting)
  8010. {
  8011. CRoxieServerActivity::stop(aborting);
  8012. pipe.clear();
  8013. readTransformer->setStream(NULL);
  8014. }
  8015. virtual const void *nextInGroup()
  8016. {
  8017. ActivityTimer t(totalCycles, timeActivities);
  8018. while (!waitForPipe())
  8019. {
  8020. if (!pipe)
  8021. return NULL;
  8022. if (helper.getPipeFlags() & TPFgroupeachrow)
  8023. {
  8024. if (!groupSignalled)
  8025. {
  8026. groupSignalled = true;
  8027. return NULL;
  8028. }
  8029. }
  8030. }
  8031. const void *ret = readTransformer->next();
  8032. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8033. processed++;
  8034. groupSignalled = false;
  8035. return ret;
  8036. }
  8037. protected:
  8038. bool waitForPipe()
  8039. {
  8040. if (!pipe)
  8041. return false; // done
  8042. if (!readTransformer->eos())
  8043. return true;
  8044. verifyPipe();
  8045. return false;
  8046. }
  8047. void openPipe(char const * cmd)
  8048. {
  8049. pipeCommand.setown(cmd);
  8050. pipe.setown(createPipeProcess());
  8051. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8052. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8053. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8054. readTransformer->setStream(pipeReader.get());
  8055. }
  8056. void verifyPipe()
  8057. {
  8058. if (pipe)
  8059. {
  8060. unsigned err = pipe->wait();
  8061. if(err && !(helper.getPipeFlags() & TPFnofail))
  8062. {
  8063. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8064. }
  8065. pipe.clear();
  8066. }
  8067. }
  8068. };
  8069. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8070. {
  8071. IHThorPipeThroughArg &helper;
  8072. RecordPullerThread puller;
  8073. Owned<IPipeProcess> pipe;
  8074. StringAttr pipeCommand;
  8075. InterruptableSemaphore pipeVerified;
  8076. InterruptableSemaphore pipeOpened;
  8077. CachedOutputMetaData inputMeta;
  8078. Owned<IOutputRowSerializer> rowSerializer;
  8079. Owned<IOutputRowDeserializer> rowDeserializer;
  8080. Owned<IPipeWriteXformHelper> writeTransformer;
  8081. Owned<IReadRowStream> readTransformer;
  8082. bool firstRead;
  8083. bool recreate;
  8084. bool inputExhausted;
  8085. bool groupSignalled;
  8086. public:
  8087. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8088. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8089. {
  8090. recreate = helper.recreateEachRow();
  8091. groupSignalled = true;
  8092. firstRead = false;
  8093. inputExhausted = false;
  8094. }
  8095. virtual bool needsAllocator() const { return true; }
  8096. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8097. {
  8098. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8099. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8100. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8101. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8102. }
  8103. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8104. {
  8105. firstRead = true;
  8106. inputExhausted = false;
  8107. groupSignalled = true; // i.e. don't start with a NULL row
  8108. pipeVerified.reinit();
  8109. pipeOpened.reinit();
  8110. writeTransformer->ready();
  8111. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8112. if (!readTransformer)
  8113. {
  8114. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8115. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8116. }
  8117. if(!recreate)
  8118. {
  8119. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8120. openPipe(pipeProgram);
  8121. }
  8122. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8123. }
  8124. virtual void setInput(unsigned idx, IRoxieInput *_in)
  8125. {
  8126. if (idx)
  8127. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  8128. puller.setInput(this, _in);
  8129. inputMeta.set(_in->queryOutputMeta());
  8130. }
  8131. virtual void stop(bool aborting)
  8132. {
  8133. pipeVerified.interrupt(NULL);
  8134. pipeOpened.interrupt(NULL);
  8135. puller.stop(aborting);
  8136. CRoxieServerActivity::stop(aborting);
  8137. pipe.clear();
  8138. readTransformer->setStream(NULL);
  8139. }
  8140. virtual void reset()
  8141. {
  8142. puller.reset();
  8143. CRoxieServerActivity::reset();
  8144. }
  8145. virtual const void *nextInGroup()
  8146. {
  8147. ActivityTimer t(totalCycles, timeActivities);
  8148. while (!waitForPipe())
  8149. {
  8150. if (!pipe)
  8151. return NULL;
  8152. if (helper.getPipeFlags() & TPFgroupeachrow)
  8153. {
  8154. if (!groupSignalled)
  8155. {
  8156. groupSignalled = true;
  8157. return NULL;
  8158. }
  8159. }
  8160. }
  8161. const void *ret = readTransformer->next();
  8162. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8163. processed++;
  8164. groupSignalled = false;
  8165. return ret;
  8166. }
  8167. virtual void processRow(const void *row)
  8168. {
  8169. // called from puller thread
  8170. if(recreate)
  8171. openPipe(helper.getNameFromRow(row));
  8172. writeTransformer->writeTranslatedText(row, pipe);
  8173. ReleaseRoxieRow(row);
  8174. if(recreate)
  8175. {
  8176. closePipe();
  8177. pipeVerified.wait();
  8178. }
  8179. }
  8180. virtual void processDone()
  8181. {
  8182. // called from puller thread
  8183. if(recreate)
  8184. {
  8185. inputExhausted = true;
  8186. pipeOpened.signal();
  8187. }
  8188. else
  8189. {
  8190. closePipe();
  8191. pipeVerified.wait();
  8192. }
  8193. }
  8194. virtual void processEOG()
  8195. {
  8196. }
  8197. void processGroup(const ConstPointerArray &)
  8198. {
  8199. throwUnexpected();
  8200. }
  8201. virtual bool fireException(IException *e)
  8202. {
  8203. pipeOpened.interrupt(LINK(e));
  8204. pipeVerified.interrupt(e);
  8205. return true;
  8206. }
  8207. private:
  8208. bool waitForPipe()
  8209. {
  8210. if (firstRead)
  8211. {
  8212. pipeOpened.wait();
  8213. firstRead = false;
  8214. }
  8215. if (!pipe)
  8216. return false; // done
  8217. if (!readTransformer->eos())
  8218. return true;
  8219. verifyPipe();
  8220. if (recreate && !inputExhausted)
  8221. pipeOpened.wait();
  8222. return false;
  8223. }
  8224. void openPipe(char const * cmd)
  8225. {
  8226. pipeCommand.setown(cmd);
  8227. pipe.setown(createPipeProcess());
  8228. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8229. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8230. writeTransformer->writeHeader(pipe);
  8231. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8232. readTransformer->setStream(pipeReader.get());
  8233. pipeOpened.signal();
  8234. }
  8235. void closePipe()
  8236. {
  8237. writeTransformer->writeFooter(pipe);
  8238. pipe->closeInput();
  8239. }
  8240. void verifyPipe()
  8241. {
  8242. if (pipe)
  8243. {
  8244. unsigned err = pipe->wait();
  8245. if(err && !(helper.getPipeFlags() & TPFnofail))
  8246. {
  8247. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8248. }
  8249. pipe.clear();
  8250. pipeVerified.signal();
  8251. }
  8252. }
  8253. };
  8254. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8255. {
  8256. IHThorPipeWriteArg &helper;
  8257. Owned<IPipeProcess> pipe;
  8258. StringAttr pipeCommand;
  8259. CachedOutputMetaData inputMeta;
  8260. Owned<IOutputRowSerializer> rowSerializer;
  8261. Owned<IPipeWriteXformHelper> writeTransformer;
  8262. bool firstRead;
  8263. bool recreate;
  8264. bool inputExhausted;
  8265. public:
  8266. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8267. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8268. {
  8269. recreate = helper.recreateEachRow();
  8270. firstRead = false;
  8271. inputExhausted = false;
  8272. }
  8273. virtual bool needsAllocator() const { return true; }
  8274. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8275. {
  8276. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8277. inputMeta.set(input->queryOutputMeta());
  8278. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8279. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8280. }
  8281. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8282. {
  8283. firstRead = true;
  8284. inputExhausted = false;
  8285. writeTransformer->ready();
  8286. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8287. if(!recreate)
  8288. {
  8289. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8290. openPipe(pipeProgram);
  8291. }
  8292. }
  8293. virtual void stop(bool aborting)
  8294. {
  8295. if (!aborting && helper.getSequence() >= 0)
  8296. {
  8297. WorkunitUpdate wu = ctx->updateWorkUnit();
  8298. if (wu)
  8299. {
  8300. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8301. if (result)
  8302. {
  8303. result->setResultTotalRowCount(processed);
  8304. result->setResultStatus(ResultStatusCalculated);
  8305. }
  8306. }
  8307. }
  8308. CRoxieServerActivity::stop(aborting);
  8309. pipe.clear();
  8310. }
  8311. virtual void onExecute()
  8312. {
  8313. loop
  8314. {
  8315. const void *row = input->nextInGroup();
  8316. if (!row)
  8317. {
  8318. row = input->nextInGroup();
  8319. if (!row)
  8320. break;
  8321. }
  8322. processed++;
  8323. if(recreate)
  8324. openPipe(helper.getNameFromRow(row));
  8325. writeTransformer->writeTranslatedText(row, pipe);
  8326. ReleaseRoxieRow(row);
  8327. if(recreate)
  8328. closePipe();
  8329. }
  8330. closePipe();
  8331. }
  8332. private:
  8333. void openPipe(char const * cmd)
  8334. {
  8335. pipeCommand.setown(cmd);
  8336. pipe.setown(createPipeProcess());
  8337. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8338. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8339. writeTransformer->writeHeader(pipe);
  8340. }
  8341. void closePipe()
  8342. {
  8343. writeTransformer->writeFooter(pipe);
  8344. pipe->closeInput();
  8345. unsigned err = pipe->wait();
  8346. if(err && !(helper.getPipeFlags() & TPFnofail))
  8347. {
  8348. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8349. }
  8350. pipe.clear();
  8351. }
  8352. };
  8353. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8354. {
  8355. public:
  8356. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8357. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8358. {
  8359. }
  8360. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8361. {
  8362. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8363. }
  8364. };
  8365. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8366. {
  8367. public:
  8368. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8369. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8370. {
  8371. }
  8372. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8373. {
  8374. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8375. }
  8376. };
  8377. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8378. {
  8379. public:
  8380. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8381. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8382. {
  8383. }
  8384. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8385. {
  8386. return new CRoxieServerPipeWriteActivity(this, _probeManager, usageCount);
  8387. }
  8388. };
  8389. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8390. {
  8391. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8392. }
  8393. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8394. {
  8395. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8396. }
  8397. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8398. {
  8399. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8400. }
  8401. //=====================================================================================================
  8402. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8403. {
  8404. IHThorStreamedIteratorArg &helper;
  8405. Owned<IRowStream> rows;
  8406. public:
  8407. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8408. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8409. {
  8410. }
  8411. ~CRoxieServerStreamedIteratorActivity()
  8412. {
  8413. }
  8414. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8415. {
  8416. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8417. rows.setown(helper.createInput());
  8418. }
  8419. virtual void stop(bool aborting)
  8420. {
  8421. if (rows)
  8422. {
  8423. rows->stop();
  8424. rows.clear();
  8425. }
  8426. CRoxieServerActivity::stop(aborting);
  8427. }
  8428. virtual const void *nextInGroup()
  8429. {
  8430. ActivityTimer t(totalCycles, timeActivities);
  8431. assertex(rows != NULL);
  8432. const void * next = rows->nextRow();
  8433. if (next)
  8434. processed++;
  8435. return next;
  8436. }
  8437. };
  8438. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8439. {
  8440. public:
  8441. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8442. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8443. {
  8444. }
  8445. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8446. {
  8447. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8448. }
  8449. };
  8450. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8451. {
  8452. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8453. }
  8454. //=====================================================================================================
  8455. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8456. {
  8457. IHThorFilterArg &helper;
  8458. bool anyThisGroup;
  8459. IRangeCompare * stepCompare;
  8460. public:
  8461. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8462. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8463. {
  8464. anyThisGroup = false;
  8465. stepCompare = NULL;
  8466. }
  8467. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8468. {
  8469. anyThisGroup = false;
  8470. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8471. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8472. stepCompare = NULL;
  8473. if (!eof)
  8474. {
  8475. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8476. if (stepMeta)
  8477. stepCompare = stepMeta->queryCompare();
  8478. }
  8479. }
  8480. virtual const void * nextInGroup()
  8481. {
  8482. ActivityTimer t(totalCycles, timeActivities);
  8483. if (eof)
  8484. return NULL;
  8485. loop
  8486. {
  8487. const void * ret = input->nextInGroup();
  8488. if (!ret)
  8489. {
  8490. //stop returning two NULLs in a row.
  8491. if (anyThisGroup)
  8492. {
  8493. anyThisGroup = false;
  8494. return NULL;
  8495. }
  8496. ret = input->nextInGroup();
  8497. if (!ret)
  8498. {
  8499. eof = true;
  8500. return NULL; // eof...
  8501. }
  8502. }
  8503. if (helper.isValid(ret))
  8504. {
  8505. anyThisGroup = true;
  8506. processed++;
  8507. return ret;
  8508. }
  8509. ReleaseRoxieRow(ret);
  8510. }
  8511. }
  8512. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8513. {
  8514. //Could assert that this isn't grouped
  8515. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8516. ActivityTimer t(totalCycles, timeActivities);
  8517. if (eof)
  8518. return NULL;
  8519. loop
  8520. {
  8521. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8522. if (!ret)
  8523. {
  8524. eof = true;
  8525. return NULL;
  8526. }
  8527. if (!wasCompleteMatch)
  8528. {
  8529. anyThisGroup = false; // RKC->GH - is this right??
  8530. return ret;
  8531. }
  8532. if (helper.isValid(ret))
  8533. {
  8534. anyThisGroup = true;
  8535. processed++;
  8536. return ret;
  8537. }
  8538. if (!stepExtra.returnMismatches())
  8539. {
  8540. ReleaseRoxieRow(ret);
  8541. return nextInGroup();
  8542. }
  8543. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8544. //condition to advance
  8545. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8546. {
  8547. wasCompleteMatch = false;
  8548. anyThisGroup = false; // WHY?
  8549. return ret;
  8550. }
  8551. ReleaseRoxieRow(ret);
  8552. }
  8553. }
  8554. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8555. {
  8556. return input->gatherConjunctions(collector);
  8557. }
  8558. virtual void resetEOF()
  8559. {
  8560. eof = prefiltered;
  8561. anyThisGroup = false;
  8562. input->resetEOF();
  8563. }
  8564. IInputSteppingMeta * querySteppingMeta()
  8565. {
  8566. return input->querySteppingMeta();
  8567. }
  8568. };
  8569. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8570. {
  8571. public:
  8572. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8573. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8574. {
  8575. }
  8576. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8577. {
  8578. return new CRoxieServerFilterActivity(this, _probeManager);
  8579. }
  8580. };
  8581. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8582. {
  8583. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8584. }
  8585. //=====================================================================================================
  8586. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8587. {
  8588. IHThorFilterGroupArg &helper;
  8589. unsigned curIndex;
  8590. ConstPointerArray gathered;
  8591. IRangeCompare * stepCompare;
  8592. public:
  8593. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8594. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8595. {
  8596. curIndex = 0;
  8597. stepCompare = NULL;
  8598. }
  8599. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8600. {
  8601. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8602. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8603. assertex(eof == !helper.canMatchAny());
  8604. curIndex = 0;
  8605. stepCompare = NULL;
  8606. if (!eof)
  8607. {
  8608. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8609. if (inputStepping)
  8610. stepCompare = inputStepping->queryCompare();
  8611. }
  8612. }
  8613. virtual void reset()
  8614. {
  8615. releaseGathered();
  8616. CRoxieServerLateStartActivity::reset();
  8617. }
  8618. inline void releaseGathered()
  8619. {
  8620. while (gathered.isItem(curIndex))
  8621. ReleaseRoxieRow(gathered.item(curIndex++));
  8622. gathered.kill();
  8623. }
  8624. virtual const void * nextInGroup()
  8625. {
  8626. ActivityTimer t(totalCycles, timeActivities);
  8627. loop
  8628. {
  8629. if (eof)
  8630. return NULL;
  8631. if (gathered.ordinality())
  8632. {
  8633. if (gathered.isItem(curIndex))
  8634. {
  8635. const void * ret = gathered.item(curIndex++);
  8636. processed++;
  8637. return ret;
  8638. }
  8639. curIndex = 0;
  8640. gathered.kill();
  8641. return NULL;
  8642. }
  8643. const void * ret = input->nextInGroup();
  8644. while (ret)
  8645. {
  8646. gathered.append(ret);
  8647. ret = input->nextInGroup();
  8648. }
  8649. unsigned num = gathered.ordinality();
  8650. if (num != 0)
  8651. {
  8652. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8653. ReleaseRoxieRowSet(gathered); // read next group
  8654. }
  8655. else
  8656. eof = true;
  8657. }
  8658. }
  8659. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8660. {
  8661. ActivityTimer t(totalCycles, timeActivities);
  8662. if (eof)
  8663. return NULL;
  8664. if (gathered.ordinality())
  8665. {
  8666. while (gathered.isItem(curIndex))
  8667. {
  8668. const void * ret = gathered.item(curIndex++);
  8669. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8670. {
  8671. processed++;
  8672. return ret;
  8673. }
  8674. ReleaseRoxieRow(ret);
  8675. }
  8676. curIndex = 0;
  8677. gathered.kill();
  8678. //nextSteppedGE never returns an end of group marker.
  8679. }
  8680. //Not completely sure about this - it could lead the the start of a group being skipped,
  8681. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8682. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8683. //MORE: What do we do with wasCompleteMatch? something like the following????
  8684. #if 0
  8685. loop
  8686. {
  8687. const void * ret;
  8688. if (stepExtra.returnMismatches())
  8689. {
  8690. bool matchedCompletely = true;
  8691. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8692. if (!wasCompleteMatch)
  8693. return ret;
  8694. }
  8695. else
  8696. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8697. #endif
  8698. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8699. while (ret)
  8700. {
  8701. gathered.append(ret);
  8702. ret = input->nextInGroup();
  8703. }
  8704. unsigned num = gathered.ordinality();
  8705. if (num != 0)
  8706. {
  8707. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8708. ReleaseRoxieRowSet(gathered); // read next group
  8709. }
  8710. else
  8711. eof = true;
  8712. return nextUngrouped(this);
  8713. }
  8714. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8715. {
  8716. return input->gatherConjunctions(collector);
  8717. }
  8718. virtual void resetEOF()
  8719. {
  8720. eof = false;
  8721. releaseGathered();
  8722. input->resetEOF();
  8723. }
  8724. IInputSteppingMeta * querySteppingMeta()
  8725. {
  8726. return input->querySteppingMeta();
  8727. }
  8728. };
  8729. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8730. {
  8731. public:
  8732. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8733. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8734. {
  8735. }
  8736. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8737. {
  8738. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8739. }
  8740. };
  8741. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8742. {
  8743. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8744. }
  8745. //=================================================================================
  8746. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8747. {
  8748. IHThorSideEffectArg &helper;
  8749. CriticalSection ecrit;
  8750. Owned<IException> exception;
  8751. bool executed;
  8752. public:
  8753. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8754. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8755. {
  8756. executed = false;
  8757. }
  8758. virtual const void * nextInGroup()
  8759. {
  8760. ActivityTimer t(totalCycles, timeActivities);
  8761. CriticalBlock b(ecrit);
  8762. if (exception)
  8763. throw(exception.getLink());
  8764. if (!executed)
  8765. {
  8766. try
  8767. {
  8768. executed = true;
  8769. helper.action();
  8770. }
  8771. catch(IException *E)
  8772. {
  8773. exception.set(E);
  8774. throw;
  8775. }
  8776. }
  8777. return NULL;
  8778. }
  8779. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8780. {
  8781. CriticalBlock b(ecrit);
  8782. if (exception)
  8783. throw(exception.getLink());
  8784. if (!executed)
  8785. {
  8786. try
  8787. {
  8788. ActivityTimer t(totalCycles, timeActivities);
  8789. executed = true;
  8790. start(parentExtractSize, parentExtract, false);
  8791. helper.action();
  8792. stop(false);
  8793. }
  8794. catch(IException *E)
  8795. {
  8796. ctx->notifyAbort(E);
  8797. stop(true);
  8798. exception.set(E);
  8799. throw;
  8800. }
  8801. }
  8802. }
  8803. virtual void reset()
  8804. {
  8805. executed = false;
  8806. exception.clear();
  8807. CRoxieServerActivity::reset();
  8808. }
  8809. };
  8810. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8811. {
  8812. bool isRoot;
  8813. public:
  8814. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8815. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8816. {
  8817. }
  8818. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8819. {
  8820. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8821. }
  8822. virtual bool isSink() const
  8823. {
  8824. return isRoot && !meta.queryOriginal();
  8825. }
  8826. };
  8827. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8828. {
  8829. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8830. }
  8831. //=================================================================================
  8832. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8833. {
  8834. IHThorActionArg &helper;
  8835. public:
  8836. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8837. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  8838. {
  8839. }
  8840. virtual void onExecute()
  8841. {
  8842. helper.action();
  8843. }
  8844. };
  8845. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8846. {
  8847. public:
  8848. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8849. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8850. {
  8851. }
  8852. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8853. {
  8854. return new CRoxieServerActionActivity(this, _probeManager, usageCount);
  8855. }
  8856. };
  8857. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8858. {
  8859. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8860. }
  8861. //=================================================================================
  8862. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8863. {
  8864. IHThorSampleArg &helper;
  8865. unsigned numSamples;
  8866. unsigned numToSkip;
  8867. unsigned whichSample;
  8868. bool anyThisGroup;
  8869. bool eof;
  8870. public:
  8871. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8872. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8873. {
  8874. numSamples = 0;
  8875. numToSkip = 0;
  8876. whichSample = 0;
  8877. anyThisGroup = false;
  8878. eof = false;
  8879. }
  8880. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8881. {
  8882. anyThisGroup = false;
  8883. eof = false;
  8884. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8885. numSamples = helper.getProportion();
  8886. whichSample = helper.getSampleNumber();
  8887. numToSkip = (whichSample ? whichSample-1 : 0);
  8888. }
  8889. virtual const void * nextInGroup()
  8890. {
  8891. ActivityTimer t(totalCycles, timeActivities);
  8892. if (eof)
  8893. return NULL;
  8894. loop
  8895. {
  8896. const void * ret = input->nextInGroup();
  8897. if (!ret)
  8898. {
  8899. //this does work with groups - may or may not be useful...
  8900. //reset the sample for each group.... probably best.
  8901. numToSkip = (whichSample ? whichSample-1 : 0);
  8902. if (anyThisGroup)
  8903. {
  8904. anyThisGroup = false;
  8905. return NULL;
  8906. }
  8907. ret = input->nextInGroup();
  8908. if (!ret)
  8909. {
  8910. eof = true;
  8911. return NULL; // eof...
  8912. }
  8913. }
  8914. if (numToSkip == 0)
  8915. {
  8916. anyThisGroup = true;
  8917. numToSkip = numSamples-1;
  8918. processed++;
  8919. return ret;
  8920. }
  8921. numToSkip--;
  8922. ReleaseRoxieRow(ret);
  8923. }
  8924. }
  8925. };
  8926. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8927. {
  8928. public:
  8929. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8930. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8931. {
  8932. }
  8933. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8934. {
  8935. return new CRoxieServerSampleActivity(this, _probeManager);
  8936. }
  8937. };
  8938. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8939. {
  8940. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8941. }
  8942. //=================================================================================
  8943. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8944. {
  8945. IHThorChooseSetsArg &helper;
  8946. unsigned numSets;
  8947. unsigned * setCounts;
  8948. bool done;
  8949. public:
  8950. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8951. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8952. {
  8953. setCounts = NULL;
  8954. numSets = 0;
  8955. done = false;
  8956. }
  8957. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8958. {
  8959. done = false;
  8960. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8961. numSets = helper.getNumSets();
  8962. setCounts = new unsigned[numSets];
  8963. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8964. helper.setCounts(setCounts);
  8965. }
  8966. virtual void reset()
  8967. {
  8968. delete [] setCounts;
  8969. setCounts = NULL;
  8970. CRoxieServerActivity::reset();
  8971. }
  8972. virtual const void * nextInGroup()
  8973. {
  8974. ActivityTimer t(totalCycles, timeActivities);
  8975. if (done)
  8976. return NULL;
  8977. loop
  8978. {
  8979. const void * ret = input->nextInGroup();
  8980. if (!ret)
  8981. {
  8982. ret = input->nextInGroup();
  8983. if (!ret)
  8984. {
  8985. done = true;
  8986. return NULL;
  8987. }
  8988. }
  8989. processed++;
  8990. switch (helper.getRecordAction(ret))
  8991. {
  8992. case 2:
  8993. done = true;
  8994. return ret;
  8995. case 1:
  8996. return ret;
  8997. }
  8998. ReleaseRoxieRow(ret);
  8999. }
  9000. }
  9001. };
  9002. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9003. {
  9004. public:
  9005. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9006. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9007. {
  9008. }
  9009. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9010. {
  9011. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  9012. }
  9013. };
  9014. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9015. {
  9016. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9017. }
  9018. //=================================================================================
  9019. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9020. {
  9021. protected:
  9022. IHThorChooseSetsExArg &helper;
  9023. unsigned numSets;
  9024. unsigned curIndex;
  9025. unsigned * setCounts;
  9026. count_t * limits;
  9027. bool done;
  9028. ConstPointerArray gathered;
  9029. virtual bool includeRow(const void * row) = 0;
  9030. virtual void calculateSelection() = 0;
  9031. public:
  9032. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9033. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9034. {
  9035. setCounts = NULL;
  9036. limits = NULL;
  9037. done = false;
  9038. curIndex = 0;
  9039. numSets = 0;
  9040. }
  9041. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9042. {
  9043. done = false;
  9044. curIndex = 0;
  9045. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9046. numSets = helper.getNumSets();
  9047. setCounts = new unsigned[numSets];
  9048. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9049. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9050. helper.getLimits(limits);
  9051. }
  9052. virtual void reset()
  9053. {
  9054. delete [] setCounts;
  9055. setCounts = NULL;
  9056. free(limits);
  9057. limits = NULL;
  9058. while (gathered.isItem(curIndex))
  9059. ReleaseRoxieRow(gathered.item(curIndex++));
  9060. gathered.kill();
  9061. CRoxieServerActivity::reset();
  9062. }
  9063. virtual const void * nextInGroup()
  9064. {
  9065. ActivityTimer t(totalCycles, timeActivities);
  9066. if (gathered.ordinality() == 0)
  9067. {
  9068. curIndex = 0;
  9069. if (!input->nextGroup(gathered))
  9070. {
  9071. done = true;
  9072. return NULL;
  9073. }
  9074. ForEachItemIn(idx1, gathered)
  9075. {
  9076. unsigned category = helper.getCategory(gathered.item(idx1));
  9077. if (category)
  9078. setCounts[category-1]++;
  9079. }
  9080. calculateSelection();
  9081. }
  9082. while (gathered.isItem(curIndex))
  9083. {
  9084. const void * row = gathered.item(curIndex);
  9085. gathered.replace(NULL, curIndex);
  9086. curIndex++;
  9087. if (includeRow(row))
  9088. {
  9089. processed++;
  9090. return row;
  9091. }
  9092. ReleaseRoxieRow(row);
  9093. }
  9094. gathered.kill();
  9095. return NULL;
  9096. }
  9097. };
  9098. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9099. {
  9100. unsigned * numToSkip;
  9101. public:
  9102. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9103. {
  9104. numToSkip = NULL;
  9105. }
  9106. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9107. {
  9108. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9109. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9110. }
  9111. virtual void reset()
  9112. {
  9113. free(numToSkip);
  9114. numToSkip = NULL;
  9115. CRoxieServerChooseSetsExActivity::reset();
  9116. }
  9117. protected:
  9118. virtual void calculateSelection()
  9119. {
  9120. for (unsigned idx=0; idx < numSets; idx++)
  9121. {
  9122. if (setCounts[idx] < limits[idx])
  9123. numToSkip[idx] = 0;
  9124. else
  9125. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9126. }
  9127. }
  9128. virtual bool includeRow(const void * row)
  9129. {
  9130. unsigned category = helper.getCategory(row);
  9131. if (category)
  9132. {
  9133. if (numToSkip[category-1] == 0)
  9134. return true;
  9135. numToSkip[category-1]--;
  9136. }
  9137. return false;
  9138. }
  9139. };
  9140. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9141. {
  9142. count_t * counter;
  9143. public:
  9144. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9145. {
  9146. counter = NULL;
  9147. }
  9148. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9149. {
  9150. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9151. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9152. }
  9153. virtual void reset()
  9154. {
  9155. free(counter);
  9156. counter = NULL;
  9157. CRoxieServerChooseSetsExActivity::reset();
  9158. }
  9159. protected:
  9160. virtual void calculateSelection()
  9161. {
  9162. }
  9163. virtual bool includeRow(const void * row)
  9164. {
  9165. unsigned category = helper.getCategory(row);
  9166. if (category)
  9167. {
  9168. assertex(category <= numSets);
  9169. counter[category-1] += limits[category-1];
  9170. if(counter[category-1] >= setCounts[category-1])
  9171. {
  9172. counter[category-1] -= setCounts[category-1];
  9173. return true;
  9174. }
  9175. }
  9176. return false;
  9177. }
  9178. };
  9179. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9180. {
  9181. public:
  9182. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9183. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9184. {
  9185. }
  9186. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9187. {
  9188. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  9189. }
  9190. };
  9191. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9192. {
  9193. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9194. }
  9195. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9196. {
  9197. public:
  9198. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9199. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9200. {
  9201. }
  9202. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9203. {
  9204. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  9205. }
  9206. };
  9207. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9208. {
  9209. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9210. }
  9211. //=================================================================================
  9212. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9213. {
  9214. IHThorEnthArg &helper;
  9215. unsigned __int64 numerator;
  9216. unsigned __int64 denominator;
  9217. unsigned __int64 counter;
  9218. bool eof;
  9219. public:
  9220. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9221. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9222. {
  9223. eof = false;
  9224. numerator = denominator = counter = 0;
  9225. }
  9226. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9227. {
  9228. eof = false;
  9229. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9230. numerator = helper.getProportionNumerator();
  9231. denominator = helper.getProportionDenominator();
  9232. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9233. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9234. if (counter >= denominator)
  9235. counter %= denominator;
  9236. }
  9237. inline bool wanted()
  9238. {
  9239. counter += numerator;
  9240. if(counter >= denominator)
  9241. {
  9242. counter -= denominator;
  9243. return true;
  9244. }
  9245. return false;
  9246. }
  9247. virtual const void * nextInGroup()
  9248. {
  9249. ActivityTimer t(totalCycles, timeActivities);
  9250. if (eof)
  9251. return NULL;
  9252. const void * ret;
  9253. loop
  9254. {
  9255. ret = input->nextInGroup();
  9256. if(!ret) //end of group
  9257. ret = input->nextInGroup();
  9258. if(!ret) //eof
  9259. {
  9260. eof = true;
  9261. return ret;
  9262. }
  9263. if (wanted())
  9264. return ret;
  9265. ReleaseRoxieRow(ret);
  9266. }
  9267. }
  9268. };
  9269. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9270. {
  9271. public:
  9272. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9273. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9274. {
  9275. }
  9276. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9277. {
  9278. return new CRoxieServerEnthActivity(this, _probeManager);
  9279. }
  9280. };
  9281. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9282. {
  9283. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9284. }
  9285. //=================================================================================
  9286. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9287. {
  9288. IHThorAggregateArg &helper;
  9289. bool eof;
  9290. bool isInputGrouped;
  9291. bool abortEarly;
  9292. public:
  9293. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9294. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9295. {
  9296. eof = false;
  9297. isInputGrouped = false;
  9298. abortEarly = false;
  9299. }
  9300. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9301. {
  9302. eof = false;
  9303. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9304. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9305. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9306. }
  9307. virtual bool needsAllocator() const { return true; }
  9308. virtual const void * nextInGroup()
  9309. {
  9310. ActivityTimer t(totalCycles, timeActivities);
  9311. if (eof)
  9312. return NULL;
  9313. const void * next = input->nextInGroup();
  9314. if (!next && isInputGrouped)
  9315. {
  9316. eof = true;
  9317. return NULL;
  9318. }
  9319. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9320. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9321. if (next)
  9322. {
  9323. finalSize = helper.processFirst(rowBuilder, next);
  9324. ReleaseRoxieRow(next);
  9325. if (!abortEarly)
  9326. {
  9327. loop
  9328. {
  9329. next = input->nextInGroup();
  9330. if (!next)
  9331. break;
  9332. finalSize = helper.processNext(rowBuilder, next);
  9333. ReleaseRoxieRow(next);
  9334. }
  9335. }
  9336. }
  9337. if (!isInputGrouped) // either read all, or aborted early
  9338. eof = true;
  9339. processed++;
  9340. return rowBuilder.finalizeRowClear(finalSize);
  9341. }
  9342. };
  9343. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9344. {
  9345. public:
  9346. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9347. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9348. {
  9349. }
  9350. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9351. {
  9352. return new CRoxieServerAggregateActivity(this, _probeManager);
  9353. }
  9354. };
  9355. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9356. {
  9357. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9358. }
  9359. //=================================================================================
  9360. typedef unsigned t_hashPrefix;
  9361. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9362. {
  9363. IHThorHashAggregateArg &helper;
  9364. RowAggregator aggregated;
  9365. bool eof;
  9366. bool gathered;
  9367. bool isGroupedAggregate;
  9368. public:
  9369. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9370. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9371. isGroupedAggregate(_isGroupedAggregate),
  9372. aggregated(helper, helper)
  9373. {
  9374. eof = false;
  9375. gathered = false;
  9376. }
  9377. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9378. {
  9379. eof = false;
  9380. gathered = false;
  9381. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9382. }
  9383. virtual void reset()
  9384. {
  9385. aggregated.reset();
  9386. CRoxieServerActivity::reset();
  9387. }
  9388. virtual bool needsAllocator() const { return true; }
  9389. virtual const void * nextInGroup()
  9390. {
  9391. ActivityTimer t(totalCycles, timeActivities);
  9392. if (eof)
  9393. return NULL;
  9394. if (!gathered)
  9395. {
  9396. aggregated.start(rowAllocator);
  9397. bool eog = true;
  9398. loop
  9399. {
  9400. const void * next = input->nextInGroup();
  9401. if (!next)
  9402. {
  9403. if (isGroupedAggregate)
  9404. {
  9405. if (eog)
  9406. eof = true;
  9407. break;
  9408. }
  9409. next = input->nextInGroup();
  9410. if (!next)
  9411. break;
  9412. }
  9413. eog = false;
  9414. aggregated.addRow(next);
  9415. ReleaseRoxieRow(next);
  9416. }
  9417. gathered = true;
  9418. }
  9419. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9420. if (next)
  9421. {
  9422. processed++;
  9423. return next->finalizeRowClear();
  9424. }
  9425. if (!isGroupedAggregate)
  9426. eof = true;
  9427. aggregated.reset();
  9428. gathered = false;
  9429. return NULL;
  9430. }
  9431. };
  9432. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9433. {
  9434. public:
  9435. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9436. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9437. {
  9438. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9439. }
  9440. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9441. {
  9442. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9443. }
  9444. protected:
  9445. bool isGroupedAggregate;
  9446. };
  9447. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9448. {
  9449. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9450. }
  9451. //=================================================================================
  9452. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9453. {
  9454. IHThorDegroupArg &helper;
  9455. bool eof;
  9456. public:
  9457. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9458. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9459. {
  9460. eof = false;
  9461. }
  9462. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9463. {
  9464. eof = false;
  9465. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9466. }
  9467. virtual const void * nextInGroup()
  9468. {
  9469. ActivityTimer t(totalCycles, timeActivities);
  9470. if (eof)
  9471. return NULL;
  9472. const void * ret = input->nextInGroup();
  9473. if (!ret)
  9474. ret = input->nextInGroup();
  9475. if (ret)
  9476. processed++;
  9477. else
  9478. eof = true;
  9479. return ret;
  9480. }
  9481. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9482. {
  9483. ActivityTimer t(totalCycles, timeActivities);
  9484. if (eof)
  9485. return NULL;
  9486. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9487. if (ret)
  9488. processed++;
  9489. else
  9490. eof = true;
  9491. return ret;
  9492. }
  9493. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9494. {
  9495. return input->gatherConjunctions(collector);
  9496. }
  9497. virtual void resetEOF()
  9498. {
  9499. eof = false;
  9500. input->resetEOF();
  9501. }
  9502. IInputSteppingMeta * querySteppingMeta()
  9503. {
  9504. return input->querySteppingMeta();
  9505. }
  9506. };
  9507. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9508. {
  9509. public:
  9510. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9511. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9512. {
  9513. }
  9514. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9515. {
  9516. return new CRoxieServerDegroupActivity(this, _probeManager);
  9517. }
  9518. };
  9519. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9520. {
  9521. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9522. }
  9523. //=================================================================================
  9524. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9525. {
  9526. IHThorDiskReadArg &helper;
  9527. bool needTransform;
  9528. bool eof;
  9529. bool anyThisGroup;
  9530. unsigned __int64 rowLimit;
  9531. unsigned __int64 choosenLimit;
  9532. public:
  9533. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9534. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9535. {
  9536. needTransform = helper.needTransform();
  9537. rowLimit = (unsigned __int64) -1;
  9538. choosenLimit = 0;
  9539. eof = false;
  9540. anyThisGroup = false;
  9541. }
  9542. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9543. {
  9544. anyThisGroup = false;
  9545. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9546. if (helper.canMatchAny())
  9547. eof = false;
  9548. else
  9549. eof = true;
  9550. choosenLimit = helper.getChooseNLimit();
  9551. rowLimit = helper.getRowLimit();
  9552. helper.setCallback(NULL); // members should not be called - change if they are
  9553. }
  9554. virtual bool needsAllocator() const { return true; }
  9555. virtual const void * nextInGroup()
  9556. {
  9557. ActivityTimer t(totalCycles, timeActivities);
  9558. if (eof)
  9559. return NULL;
  9560. if (processed==choosenLimit)
  9561. {
  9562. eof = true;
  9563. return NULL;
  9564. }
  9565. if (needTransform)
  9566. {
  9567. loop
  9568. {
  9569. const void *in = input->nextInGroup();
  9570. if (!in)
  9571. {
  9572. if (anyThisGroup)
  9573. {
  9574. anyThisGroup = false;
  9575. return NULL;
  9576. }
  9577. in = input->nextInGroup();
  9578. if (!in)
  9579. {
  9580. eof = true;
  9581. return NULL; // eof...
  9582. }
  9583. }
  9584. unsigned outSize;
  9585. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9586. try
  9587. {
  9588. outSize = helper.transform(rowBuilder, in);
  9589. ReleaseRoxieRow(in);
  9590. }
  9591. catch (IException *E)
  9592. {
  9593. throw makeWrappedException(E);
  9594. }
  9595. if (outSize)
  9596. {
  9597. anyThisGroup = true;
  9598. processed++;
  9599. if (processed==rowLimit)
  9600. {
  9601. if (traceLevel > 4)
  9602. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9603. helper.onLimitExceeded();
  9604. }
  9605. return rowBuilder.finalizeRowClear(outSize);
  9606. }
  9607. }
  9608. }
  9609. else
  9610. {
  9611. const void *ret = input->nextInGroup();
  9612. if (ret)
  9613. {
  9614. processed++;
  9615. if (processed==rowLimit)
  9616. {
  9617. if (traceLevel > 4)
  9618. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9619. ReleaseClearRoxieRow(ret);
  9620. helper.onLimitExceeded(); // should not return
  9621. throwUnexpected();
  9622. }
  9623. }
  9624. return ret;
  9625. }
  9626. }
  9627. };
  9628. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9629. {
  9630. public:
  9631. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9632. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9633. {
  9634. }
  9635. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9636. {
  9637. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9638. }
  9639. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9640. {
  9641. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9642. setInput(0, source, sourceIdx);
  9643. else
  9644. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9645. }
  9646. };
  9647. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9648. {
  9649. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9650. }
  9651. //=================================================================================
  9652. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9653. {
  9654. public:
  9655. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9656. : CRoxieServerActivity(_factory, _probeManager)
  9657. {
  9658. }
  9659. ~CRoxieServerSpillWriteActivity()
  9660. {
  9661. }
  9662. virtual const void *nextInGroup()
  9663. {
  9664. ActivityTimer t(totalCycles, timeActivities);
  9665. return input->nextInGroup();
  9666. }
  9667. };
  9668. //==================================================================================
  9669. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9670. {
  9671. protected:
  9672. Owned<IExtRowWriter> outSeq;
  9673. Owned<IOutputRowSerializer> rowSerializer;
  9674. Linked<IFileIOStream> diskout;
  9675. bool blockcompressed;
  9676. bool extend;
  9677. bool overwrite;
  9678. bool encrypted;
  9679. bool grouped;
  9680. IHThorDiskWriteArg &helper;
  9681. CachedOutputMetaData diskmeta;
  9682. Owned<IRoxieWriteHandler> writer;
  9683. bool tallycrc;
  9684. unsigned __int64 uncompressedBytesWritten;
  9685. CRC32 crc;
  9686. void updateWorkUnitResult(unsigned __int64 reccount)
  9687. {
  9688. assertex(writer);
  9689. // MORE - a lot of this is common with hthor
  9690. WorkunitUpdate wu = ctx->updateWorkUnit();
  9691. if (wu)
  9692. {
  9693. OwnedRoxieString rawLogicalName = helper.getFileName();
  9694. StringBuffer lfn; // logical filename
  9695. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  9696. if (lfn.length())
  9697. {
  9698. unsigned flags = helper.getFlags();
  9699. WUFileKind fileKind;
  9700. if (TDXtemporary & flags)
  9701. fileKind = WUFileTemporary;
  9702. else if(TDXjobtemp & flags)
  9703. fileKind = WUFileJobOwned;
  9704. else if(TDWowned & flags)
  9705. fileKind = WUFileOwned;
  9706. else
  9707. fileKind = WUFileStandard;
  9708. StringArray clusters;
  9709. writer->getClusters(clusters);
  9710. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9711. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9712. {
  9713. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9714. if (result)
  9715. {
  9716. result->setResultTotalRowCount(reccount);
  9717. result->setResultStatus(ResultStatusCalculated);
  9718. if (helper.getFlags() & TDWresult)
  9719. result->setResultFilename(lfn.str());
  9720. else
  9721. result->setResultLogicalName(lfn.str());
  9722. }
  9723. }
  9724. }
  9725. }
  9726. }
  9727. void resolve()
  9728. {
  9729. OwnedRoxieString rawLogicalName = helper.getFileName();
  9730. assertex(rawLogicalName);
  9731. assertex((helper.getFlags() & TDXtemporary) == 0);
  9732. StringArray clusters;
  9733. unsigned clusterIdx = 0;
  9734. while(true)
  9735. {
  9736. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9737. if(!cluster)
  9738. break;
  9739. clusters.append(cluster);
  9740. clusterIdx++;
  9741. }
  9742. if (clusters.length())
  9743. {
  9744. if (extend)
  9745. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9746. }
  9747. else
  9748. {
  9749. if (roxieName.length())
  9750. clusters.append(roxieName.str());
  9751. else
  9752. clusters.append(".");
  9753. }
  9754. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  9755. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9756. }
  9757. public:
  9758. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9759. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  9760. {
  9761. extend = ((helper.getFlags() & TDWextend) != 0);
  9762. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9763. grouped = false; // don't think we need to support it...
  9764. diskmeta.set(helper.queryDiskRecordSize());
  9765. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9766. encrypted = false; // set later
  9767. tallycrc = true;
  9768. uncompressedBytesWritten = 0;
  9769. }
  9770. ~CRoxieServerDiskWriteActivity()
  9771. {
  9772. }
  9773. virtual bool needsAllocator() const
  9774. {
  9775. return true;
  9776. }
  9777. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9778. {
  9779. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9780. resolve();
  9781. Owned<IFileIO> io;
  9782. void *ekey;
  9783. size32_t ekeylen;
  9784. helper.getEncryptKey(ekeylen, ekey);
  9785. Owned<ICompressor> ecomp;
  9786. if (ekeylen!=0)
  9787. {
  9788. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9789. memset(ekey,0,ekeylen);
  9790. rtlFree(ekey);
  9791. encrypted = true;
  9792. blockcompressed = true;
  9793. }
  9794. if (blockcompressed)
  9795. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9796. else
  9797. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9798. if (!io)
  9799. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9800. diskout.setown(createBufferedIOStream(io));
  9801. if (extend)
  9802. diskout->seek(0, IFSend);
  9803. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9804. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9805. rowSerializer.set(rowIf->queryRowSerializer());
  9806. unsigned rwFlags = rw_autoflush;
  9807. if(grouped)
  9808. rwFlags |= rw_grouped;
  9809. if(tallycrc)
  9810. rwFlags |= rw_crc;
  9811. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9812. }
  9813. virtual void stop(bool aborting)
  9814. {
  9815. if (aborting)
  9816. {
  9817. if (writer)
  9818. writer->finish(false, this);
  9819. }
  9820. else
  9821. {
  9822. if (outSeq)
  9823. outSeq->flush(&crc);
  9824. if (outSeq)
  9825. uncompressedBytesWritten = outSeq->getPosition();
  9826. if (writer)
  9827. {
  9828. updateWorkUnitResult(processed);
  9829. writer->finish(true, this);
  9830. }
  9831. }
  9832. writer.clear();
  9833. CRoxieServerActivity::stop(aborting);
  9834. }
  9835. virtual void reset()
  9836. {
  9837. CRoxieServerActivity::reset();
  9838. diskout.clear();
  9839. outSeq.clear();
  9840. writer.clear();
  9841. uncompressedBytesWritten = 0;
  9842. crc.reset();
  9843. }
  9844. virtual void onExecute()
  9845. {
  9846. loop
  9847. {
  9848. const void *nextrec = input->nextInGroup();
  9849. if (!nextrec)
  9850. {
  9851. nextrec = input->nextInGroup();
  9852. if (!nextrec)
  9853. break;
  9854. }
  9855. processed++;
  9856. outSeq->putRow(nextrec);
  9857. }
  9858. }
  9859. virtual void setFileProperties(IFileDescriptor *desc) const
  9860. {
  9861. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9862. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9863. if (blockcompressed)
  9864. {
  9865. // caller has already set @size from file size...
  9866. fileProps.setPropBool("@blockCompressed", true);
  9867. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9868. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9869. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9870. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9871. }
  9872. else if (tallycrc && crc.get())
  9873. partProps.setPropInt64("@fileCrc", crc.get());
  9874. if (encrypted)
  9875. fileProps.setPropBool("@encrypted", true);
  9876. fileProps.setPropInt64("@recordCount", processed);
  9877. unsigned flags = helper.getFlags();
  9878. if (flags & TDWpersist)
  9879. fileProps.setPropBool("@persistent", true);
  9880. if (grouped)
  9881. fileProps.setPropBool("@grouped", true);
  9882. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9883. fileProps.setPropBool("@owned", true);
  9884. if (flags & TDWresult)
  9885. fileProps.setPropBool("@result", true);
  9886. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9887. if (workUnit)
  9888. {
  9889. SCMStringBuffer owner, wuid, job;
  9890. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9891. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9892. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9893. }
  9894. if (flags & TDWexpires)
  9895. setExpiryTime(fileProps, helper.getExpiryDays());
  9896. if (flags & TDWupdate)
  9897. {
  9898. unsigned eclCRC;
  9899. unsigned __int64 totalCRC;
  9900. helper.getUpdateCRCs(eclCRC, totalCRC);
  9901. fileProps.setPropInt("@eclCRC", eclCRC);
  9902. fileProps.setPropInt64("@totalCRC", totalCRC);
  9903. }
  9904. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9905. IRecordSize * inputMeta = input->queryOutputMeta();
  9906. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9907. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9908. const char *recordECL = helper.queryRecordECL();
  9909. if (recordECL && *recordECL)
  9910. fileProps.setProp("ECL", recordECL);
  9911. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9912. }
  9913. virtual IUserDescriptor *queryUserDescriptor() const
  9914. {
  9915. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9916. if (workUnit)
  9917. return workUnit->queryUserDescriptor();
  9918. else
  9919. return NULL;
  9920. }
  9921. virtual bool isOutputTransformed() const { return false; }
  9922. };
  9923. //=================================================================================
  9924. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9925. {
  9926. IHThorCsvWriteArg &csvHelper;
  9927. CSVOutputStream csvOutput;
  9928. public:
  9929. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9930. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9931. {
  9932. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9933. }
  9934. virtual void onExecute()
  9935. {
  9936. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9937. if (header)
  9938. {
  9939. csvOutput.beginLine();
  9940. csvOutput.writeHeaderLn(strlen(header), header);
  9941. diskout->write(csvOutput.length(), csvOutput.str());
  9942. }
  9943. loop
  9944. {
  9945. const void *nextrec = input->nextInGroup();
  9946. if (!nextrec)
  9947. {
  9948. nextrec = input->nextInGroup();
  9949. if (!nextrec)
  9950. break;
  9951. }
  9952. processed++;
  9953. csvOutput.beginLine();
  9954. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9955. csvOutput.endLine();
  9956. diskout->write(csvOutput.length(), csvOutput.str());
  9957. ReleaseRoxieRow(nextrec);
  9958. }
  9959. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9960. if (footer)
  9961. {
  9962. csvOutput.beginLine();
  9963. csvOutput.writeHeaderLn(strlen(footer), footer);
  9964. diskout->write(csvOutput.length(), csvOutput.str());
  9965. }
  9966. }
  9967. virtual void setFileProperties(IFileDescriptor *desc) const
  9968. {
  9969. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9970. IPropertyTree &props = desc->queryProperties();
  9971. props.setProp("@format","utf8n");
  9972. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9973. StringBuffer separator;
  9974. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9975. const char *s = rs;
  9976. while (s && *s)
  9977. {
  9978. if (',' == *s)
  9979. separator.append("\\,");
  9980. else
  9981. separator.append(*s);
  9982. ++s;
  9983. }
  9984. props.setProp("@csvSeparate", separator.str());
  9985. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9986. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9987. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9988. props.setProp("@kind", "csv");
  9989. }
  9990. virtual bool isOutputTransformed() const { return true; }
  9991. };
  9992. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9993. {
  9994. IHThorXmlWriteArg &xmlHelper;
  9995. StringAttr rowTag;
  9996. ThorActivityKind kind;
  9997. unsigned headerLength;
  9998. unsigned footerLength;
  9999. public:
  10000. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10001. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10002. {
  10003. }
  10004. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10005. {
  10006. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10007. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10008. if (!xmlpath)
  10009. rowTag.set(DEFAULTXMLROWTAG);
  10010. else
  10011. {
  10012. const char *path = xmlpath;
  10013. if (*path == '/') path++;
  10014. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10015. rowTag.set(path);
  10016. }
  10017. }
  10018. virtual void onExecute()
  10019. {
  10020. StringBuffer header;
  10021. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10022. if (kind==TAKjsonwrite)
  10023. buildJsonHeader(header, suppliedHeader, rowTag);
  10024. else if (suppliedHeader)
  10025. header.set(suppliedHeader);
  10026. else
  10027. header.append(DEFAULTXMLHEADER).newline();
  10028. headerLength = header.length();
  10029. diskout->write(header.length(), header.str());
  10030. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10031. writer->outputBeginArray(rowTag); //need to set this
  10032. writer->clear(); //but not output it
  10033. loop
  10034. {
  10035. OwnedConstRoxieRow nextrec = input->nextInGroup();
  10036. if (!nextrec)
  10037. {
  10038. nextrec.setown(input->nextInGroup());
  10039. if (!nextrec)
  10040. break;
  10041. }
  10042. processed++;
  10043. writer->clear().outputBeginNested(rowTag, false);
  10044. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10045. writer->outputEndNested(rowTag);
  10046. diskout->write(writer->length(), writer->str());
  10047. }
  10048. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10049. StringBuffer footer;
  10050. if (kind==TAKjsonwrite)
  10051. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10052. else if (suppliedFooter)
  10053. footer.append(suppliedFooter);
  10054. else
  10055. footer.append(DEFAULTXMLFOOTER);
  10056. footerLength=footer.length();
  10057. diskout->write(footer.length(), footer);
  10058. }
  10059. virtual void reset()
  10060. {
  10061. CRoxieServerDiskWriteActivity::reset();
  10062. rowTag.clear();
  10063. }
  10064. virtual void setFileProperties(IFileDescriptor *desc) const
  10065. {
  10066. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10067. desc->queryProperties().setProp("@format","utf8n");
  10068. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10069. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10070. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10071. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10072. }
  10073. virtual bool isOutputTransformed() const { return true; }
  10074. };
  10075. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10076. {
  10077. bool isRoot;
  10078. bool isTemp;
  10079. public:
  10080. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10081. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  10082. {
  10083. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10084. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10085. setNumOutputs(helper->getTempUsageCount());
  10086. if (_kind!=TAKdiskwrite)
  10087. assertex(numOutputs == 0);
  10088. }
  10089. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10090. {
  10091. switch (numOutputs)
  10092. {
  10093. case 0:
  10094. switch (kind)
  10095. {
  10096. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  10097. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  10098. case TAKxmlwrite:
  10099. case TAKjsonwrite:
  10100. return new CRoxieServerXmlWriteActivity(this, _probeManager, kind);
  10101. };
  10102. throwUnexpected();
  10103. case 1:
  10104. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  10105. default:
  10106. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  10107. }
  10108. }
  10109. virtual bool isSink() const
  10110. {
  10111. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10112. }
  10113. };
  10114. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10115. {
  10116. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10117. }
  10118. //=================================================================================
  10119. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10120. {
  10121. IHThorIndexWriteArg &helper;
  10122. bool overwrite;
  10123. Owned<ClusterWriteHandler> clusterHandler;
  10124. Owned<IRoxieWriteHandler> writer;
  10125. unsigned __int64 reccount;
  10126. unsigned int fileCrc;
  10127. StringBuffer filename;
  10128. void updateWorkUnitResult()
  10129. {
  10130. // MORE - a lot of this is common with hthor
  10131. WorkunitUpdate wu = ctx->updateWorkUnit();
  10132. if (wu)
  10133. {
  10134. OwnedRoxieString rawLogicalName = helper.getFileName();
  10135. StringBuffer lfn; // logical filename
  10136. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10137. if (lfn.length())
  10138. {
  10139. if (helper.getSequence() >= 0)
  10140. {
  10141. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10142. if (result)
  10143. {
  10144. result->setResultTotalRowCount(reccount);
  10145. result->setResultStatus(ResultStatusCalculated);
  10146. result->setResultLogicalName(lfn.str());
  10147. }
  10148. }
  10149. if(clusterHandler)
  10150. clusterHandler->finish(writer->queryFile());
  10151. CTXLOG("Created roxie index file %s", lfn.str());
  10152. }
  10153. }
  10154. }
  10155. virtual void resolve()
  10156. {
  10157. StringArray clusters;
  10158. unsigned clusterIdx = 0;
  10159. while(true)
  10160. {
  10161. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10162. if(!cluster)
  10163. break;
  10164. clusters.append(cluster);
  10165. clusterIdx++;
  10166. }
  10167. if (roxieName.length())
  10168. clusters.append(roxieName.str());
  10169. else
  10170. clusters.append(".");
  10171. OwnedRoxieString fname(helper.getFileName());
  10172. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10173. filename.set(writer->queryFile()->queryFilename());
  10174. if (writer->queryFile()->exists())
  10175. {
  10176. if (overwrite)
  10177. {
  10178. CTXLOG("Removing existing %s from DFS",filename.str());
  10179. writer->queryFile()->remove();
  10180. }
  10181. else
  10182. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10183. }
  10184. }
  10185. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10186. {
  10187. size32_t nameLen;
  10188. char * nameBuff;
  10189. size32_t valueLen;
  10190. char * valueBuff;
  10191. unsigned idx = 0;
  10192. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10193. {
  10194. StringBuffer name(nameLen, nameBuff);
  10195. StringBuffer value(valueLen, valueBuff);
  10196. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10197. {
  10198. OwnedRoxieString fname(helper.getFileName());
  10199. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10200. }
  10201. if(!validateXMLTag(name.str()))
  10202. {
  10203. OwnedRoxieString fname(helper.getFileName());
  10204. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10205. }
  10206. if(!metadata)
  10207. metadata.setown(createPTree("metadata"));
  10208. metadata->setProp(name.str(), value.str());
  10209. }
  10210. }
  10211. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10212. {
  10213. if(!metadata)
  10214. metadata.setown(createPTree("metadata"));
  10215. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10216. void * layoutMetaBuff;
  10217. size32_t layoutMetaSize;
  10218. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10219. {
  10220. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10221. rtlFree(layoutMetaBuff);
  10222. }
  10223. }
  10224. public:
  10225. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10226. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10227. {
  10228. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10229. reccount = 0;
  10230. fileCrc = 0;
  10231. }
  10232. ~CRoxieServerIndexWriteActivity()
  10233. {
  10234. }
  10235. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10236. {
  10237. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10238. resolve();
  10239. }
  10240. virtual void onExecute()
  10241. {
  10242. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10243. size32_t maxDiskRecordSize;
  10244. if (isVariable)
  10245. {
  10246. if (helper.getFlags() & TIWmaxlength)
  10247. maxDiskRecordSize = helper.getMaxKeySize();
  10248. else
  10249. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10250. }
  10251. else
  10252. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10253. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10254. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10255. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10256. fileCrc = -1;
  10257. {
  10258. Owned<IFileIO> io;
  10259. try
  10260. {
  10261. io.setown(writer->queryFile()->open(IFOcreate));
  10262. }
  10263. catch(IException * e)
  10264. {
  10265. e->Release();
  10266. clearKeyStoreCache(false);
  10267. io.setown(writer->queryFile()->open(IFOcreate));
  10268. }
  10269. if(!io)
  10270. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10271. Owned<IFileIOStream> out = createIOStream(io);
  10272. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10273. if (helper.getFlags() & TIWrowcompress)
  10274. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10275. else if (!(helper.getFlags() & TIWnolzwcompress))
  10276. flags |= HTREE_COMPRESSED_KEY;
  10277. if (isVariable)
  10278. flags |= HTREE_VARSIZE;
  10279. Owned<IPropertyTree> metadata;
  10280. buildUserMetadata(metadata);
  10281. buildLayoutMetadata(metadata);
  10282. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10283. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10284. class BcWrapper : implements IBlobCreator
  10285. {
  10286. IKeyBuilder *builder;
  10287. public:
  10288. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10289. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10290. {
  10291. return builder->createBlob(size, (const char *) ptr);
  10292. }
  10293. } bc(builder);
  10294. // Loop thru the results
  10295. loop
  10296. {
  10297. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10298. if (!nextrec)
  10299. {
  10300. nextrec.setown(input->nextInGroup());
  10301. if (!nextrec)
  10302. break;
  10303. }
  10304. try
  10305. {
  10306. unsigned __int64 fpos;
  10307. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10308. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10309. builder->processKeyData(rowBuffer, fpos, thisSize);
  10310. }
  10311. catch(IException * e)
  10312. {
  10313. throw makeWrappedException(e);
  10314. }
  10315. reccount++;
  10316. }
  10317. if(metadata)
  10318. builder->finish(metadata,&fileCrc);
  10319. else
  10320. builder->finish(&fileCrc);
  10321. }
  10322. }
  10323. virtual void stop(bool aborting)
  10324. {
  10325. if (writer)
  10326. {
  10327. if (!aborting)
  10328. updateWorkUnitResult();
  10329. writer->finish(!aborting, this);
  10330. writer.clear();
  10331. }
  10332. CRoxieServerActivity::stop(aborting);
  10333. }
  10334. virtual void reset()
  10335. {
  10336. CRoxieServerActivity::reset();
  10337. writer.clear();
  10338. }
  10339. //interface IRoxiePublishCallback
  10340. virtual void setFileProperties(IFileDescriptor *desc) const
  10341. {
  10342. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10343. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10344. // Now publish to name services
  10345. StringBuffer dir,base;
  10346. offset_t indexFileSize = writer->queryFile()->size();
  10347. if(clusterHandler)
  10348. clusterHandler->splitPhysicalFilename(dir, base);
  10349. else
  10350. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10351. desc->setDefaultDir(dir.str());
  10352. //properties of the first file part.
  10353. Owned<IPropertyTree> attrs;
  10354. if(clusterHandler)
  10355. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10356. else
  10357. {
  10358. // add cluster
  10359. StringBuffer mygroupname;
  10360. desc->setNumParts(1);
  10361. desc->setPartMask(base.str());
  10362. attrs.set(&desc->queryPart(0)->queryProperties());
  10363. }
  10364. attrs->setPropInt64("@size", indexFileSize);
  10365. CDateTime createTime, modifiedTime, accessedTime;
  10366. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10367. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10368. unsigned hour, min, sec, nanosec;
  10369. modifiedTime.getTime(hour, min, sec, nanosec);
  10370. modifiedTime.setTime(hour, min, sec, 0);
  10371. StringBuffer timestr;
  10372. modifiedTime.getString(timestr);
  10373. if(timestr.length())
  10374. attrs->setProp("@modified", timestr.str());
  10375. if(clusterHandler)
  10376. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10377. // properties of the logical file
  10378. IPropertyTree & properties = desc->queryProperties();
  10379. properties.setProp("@kind", "key");
  10380. properties.setPropInt64("@size", indexFileSize);
  10381. properties.setPropInt64("@recordCount", reccount);
  10382. SCMStringBuffer info;
  10383. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10384. if (workUnit)
  10385. {
  10386. properties.setProp("@owner", workUnit->getUser(info).str());
  10387. info.clear();
  10388. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10389. info.clear();
  10390. properties.setProp("@job", workUnit->getJobName(info).str());
  10391. }
  10392. char const * rececl = helper.queryRecordECL();
  10393. if(rececl && *rececl)
  10394. properties.setProp("ECL", rececl);
  10395. if (helper.getFlags() & TIWexpires)
  10396. setExpiryTime(properties, helper.getExpiryDays());
  10397. if (helper.getFlags() & TIWupdate)
  10398. {
  10399. unsigned eclCRC;
  10400. unsigned __int64 totalCRC;
  10401. helper.getUpdateCRCs(eclCRC, totalCRC);
  10402. properties.setPropInt("@eclCRC", eclCRC);
  10403. properties.setPropInt64("@totalCRC", totalCRC);
  10404. }
  10405. properties.setPropInt("@fileCrc", fileCrc);
  10406. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10407. void * layoutMetaBuff;
  10408. size32_t layoutMetaSize;
  10409. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10410. {
  10411. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10412. rtlFree(layoutMetaBuff);
  10413. }
  10414. }
  10415. IUserDescriptor *queryUserDescriptor() const
  10416. {
  10417. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10418. if (workUnit)
  10419. return workUnit->queryUserDescriptor();
  10420. else
  10421. return NULL;
  10422. }
  10423. };
  10424. //=================================================================================
  10425. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10426. {
  10427. public:
  10428. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10429. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10430. {
  10431. setNumOutputs(0);
  10432. }
  10433. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10434. {
  10435. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10436. }
  10437. virtual bool isSink() const
  10438. {
  10439. return true;
  10440. }
  10441. };
  10442. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10443. {
  10444. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10445. }
  10446. //=================================================================================
  10447. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10448. {
  10449. if((flags & JFmatchAbortLimitSkips) != 0)
  10450. {
  10451. limitFail = false;
  10452. limitOnFail = false;
  10453. }
  10454. else
  10455. {
  10456. limitOnFail = ((flags & JFonfail) != 0);
  10457. limitFail = !limitOnFail;
  10458. }
  10459. }
  10460. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10461. {
  10462. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10463. IHThorJoinArg &helper;
  10464. ICompare * collate;
  10465. ICompare * collateupper;
  10466. ThorActivityKind activityKind;
  10467. bool leftOuterJoin;
  10468. bool rightOuterJoin;
  10469. bool exclude;
  10470. bool limitFail;
  10471. bool limitOnFail;
  10472. unsigned keepLimit;
  10473. unsigned joinLimit;
  10474. unsigned atmostLimit;
  10475. unsigned abortLimit;
  10476. unsigned atmostsTriggered;
  10477. bool betweenjoin;
  10478. OwnedRowArray right;
  10479. const void * left;
  10480. const void * pendingRight;
  10481. unsigned rightIndex;
  10482. unsigned joinCounter;
  10483. BoolArray matchedRight;
  10484. bool matchedLeft;
  10485. Owned<IException> failingLimit;
  10486. ConstPointerArray filteredRight;
  10487. Owned<IRHLimitedCompareHelper> limitedhelper;
  10488. OwnedConstRoxieRow defaultLeft;
  10489. OwnedConstRoxieRow defaultRight;
  10490. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10491. Owned<IEngineRowAllocator> defaultRightAllocator;
  10492. bool cloneLeft;
  10493. void createDefaultLeft()
  10494. {
  10495. if (!defaultLeft)
  10496. {
  10497. if (!defaultLeftAllocator)
  10498. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10499. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10500. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10501. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10502. }
  10503. }
  10504. void createDefaultRight()
  10505. {
  10506. if (!defaultRight)
  10507. {
  10508. if (!defaultRightAllocator)
  10509. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10510. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10511. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10512. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10513. }
  10514. }
  10515. public:
  10516. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10517. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10518. {
  10519. // MORE - some of this should be done in factory
  10520. unsigned joinFlags = helper.getJoinFlags();
  10521. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10522. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10523. exclude = (joinFlags & JFexclude) != 0;
  10524. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10525. getLimitType(joinFlags, limitFail, limitOnFail);
  10526. if (joinFlags & JFslidingmatch)
  10527. {
  10528. betweenjoin = true;
  10529. collate = helper.queryCompareLeftRightLower();
  10530. collateupper = helper.queryCompareLeftRightUpper();
  10531. }
  10532. else
  10533. {
  10534. betweenjoin = false;
  10535. collate = collateupper = helper.queryCompareLeftRight();
  10536. }
  10537. rightIndex = 0;
  10538. joinCounter = 0;
  10539. state = JSfill;
  10540. matchedLeft = false;
  10541. joinLimit = 0;
  10542. keepLimit = 0; // wait until ctx available
  10543. atmostLimit = 0; // wait until ctx available
  10544. abortLimit = 0; // wait until ctx available
  10545. atmostsTriggered = 0;
  10546. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10547. left = NULL;
  10548. pendingRight = NULL;
  10549. activityKind = _factory->getKind();
  10550. }
  10551. virtual bool needsAllocator() const { return true; }
  10552. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10553. {
  10554. left = NULL;
  10555. rightIndex = 0;
  10556. joinCounter = 0;
  10557. state = JSfill;
  10558. matchedLeft = false;
  10559. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10560. keepLimit = helper.getKeepLimit();
  10561. if (keepLimit == 0)
  10562. keepLimit = (unsigned)-1;
  10563. atmostsTriggered = 0;
  10564. atmostLimit = helper.getJoinLimit();
  10565. if(atmostLimit == 0)
  10566. atmostLimit = (unsigned)-1;
  10567. else
  10568. assertex(!rightOuterJoin && !betweenjoin);
  10569. abortLimit = helper.getMatchAbortLimit();
  10570. if (abortLimit == 0)
  10571. abortLimit = (unsigned)-1;
  10572. if (rightOuterJoin)
  10573. createDefaultLeft();
  10574. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10575. createDefaultRight();
  10576. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10577. { //limited match join (s[1..n])
  10578. limitedhelper.setown(createRHLimitedCompareHelper());
  10579. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10580. }
  10581. }
  10582. virtual void reset()
  10583. {
  10584. if (atmostsTriggered)
  10585. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  10586. right.clear();
  10587. ReleaseClearRoxieRow(left);
  10588. ReleaseClearRoxieRow(pendingRight);
  10589. defaultRight.clear();
  10590. defaultLeft.clear();
  10591. CRoxieServerTwoInputActivity::reset();
  10592. }
  10593. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10594. {
  10595. switch(idx)
  10596. {
  10597. case 0:
  10598. if ((helper.getJoinFlags() & JFparallel) != 0)
  10599. {
  10600. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10601. puller->setInput(0, _in);
  10602. _in = puller;
  10603. }
  10604. input = _in;
  10605. break;
  10606. case 1:
  10607. input1 = _in;
  10608. break;
  10609. default:
  10610. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10611. }
  10612. }
  10613. virtual IRoxieInput *queryOutput(unsigned idx)
  10614. {
  10615. if (idx==(unsigned)-1)
  10616. idx = 0;
  10617. return idx ? NULL : this;
  10618. }
  10619. void fillLeft()
  10620. {
  10621. matchedLeft = false;
  10622. left = input->nextInGroup();
  10623. if (!left)
  10624. left = input->nextInGroup();
  10625. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10626. fillRight();
  10627. if (limitedhelper && 0==rightIndex)
  10628. {
  10629. rightIndex = 0;
  10630. joinCounter = 0;
  10631. right.clear();
  10632. matchedRight.kill();
  10633. if (left)
  10634. {
  10635. limitedhelper->getGroup(right,left);
  10636. ForEachItemIn(idx, right)
  10637. matchedRight.append(false);
  10638. }
  10639. }
  10640. }
  10641. void fillRight()
  10642. {
  10643. if (limitedhelper)
  10644. return;
  10645. failingLimit.clear();
  10646. if(betweenjoin && left)
  10647. {
  10648. aindex_t start = 0;
  10649. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10650. start++;
  10651. if(start>0)
  10652. right.clearPart(0, start);
  10653. }
  10654. else
  10655. right.clear();
  10656. rightIndex = 0;
  10657. joinCounter = 0;
  10658. unsigned groupCount = 0;
  10659. const void * next;
  10660. while(true)
  10661. {
  10662. if(pendingRight)
  10663. {
  10664. next = pendingRight;
  10665. pendingRight = NULL;
  10666. }
  10667. else
  10668. {
  10669. next = input1->nextInGroup();
  10670. }
  10671. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10672. {
  10673. while(next)
  10674. {
  10675. ReleaseClearRoxieRow(next);
  10676. next = input1->nextInGroup();
  10677. }
  10678. continue;
  10679. }
  10680. while(next)
  10681. {
  10682. if(groupCount==abortLimit)
  10683. {
  10684. if(limitFail)
  10685. failLimit();
  10686. if (ctx->queryDebugContext())
  10687. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10688. if(limitOnFail)
  10689. {
  10690. assertex(!failingLimit);
  10691. try
  10692. {
  10693. failLimit();
  10694. }
  10695. catch(IException * except)
  10696. {
  10697. failingLimit.setown(except);
  10698. }
  10699. assertex(failingLimit != NULL);
  10700. }
  10701. right.append(next);
  10702. do
  10703. {
  10704. next = input1->nextInGroup();
  10705. ReleaseRoxieRow(next);
  10706. } while(next);
  10707. break;
  10708. }
  10709. else if(groupCount==atmostLimit)
  10710. {
  10711. atmostsTriggered++;
  10712. right.clear();
  10713. groupCount = 0;
  10714. while(next)
  10715. {
  10716. ReleaseRoxieRow(next);
  10717. next = input1->nextInGroup();
  10718. }
  10719. }
  10720. else
  10721. {
  10722. right.append(next);
  10723. groupCount++;
  10724. }
  10725. next = input1->nextInGroup();
  10726. }
  10727. // 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
  10728. if(betweenjoin && left)
  10729. {
  10730. pendingRight = input1->nextInGroup();
  10731. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10732. break;
  10733. }
  10734. else
  10735. break;
  10736. }
  10737. matchedRight.kill();
  10738. ForEachItemIn(idx, right)
  10739. matchedRight.append(false);
  10740. }
  10741. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  10742. {
  10743. if (cloneLeft)
  10744. {
  10745. LinkRoxieRow(curLeft);
  10746. return curLeft;
  10747. }
  10748. try
  10749. {
  10750. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10751. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  10752. if (thisSize)
  10753. return rowBuilder.finalizeRowClear(thisSize);
  10754. else
  10755. return NULL;
  10756. }
  10757. catch (IException *E)
  10758. {
  10759. throw makeWrappedException(E);
  10760. }
  10761. }
  10762. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10763. {
  10764. try
  10765. {
  10766. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10767. unsigned numRows = rows.ordinality();
  10768. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10769. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10770. if (thisSize)
  10771. return rowBuilder.finalizeRowClear(thisSize);
  10772. else
  10773. return NULL;
  10774. }
  10775. catch (IException *E)
  10776. {
  10777. throw makeWrappedException(E);
  10778. }
  10779. }
  10780. const void * joinException(const void * curLeft, IException * except)
  10781. {
  10782. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10783. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10784. return rowBuilder.finalizeRowClear(thisSize);
  10785. }
  10786. void failLimit()
  10787. {
  10788. helper.onMatchAbortLimitExceeded();
  10789. CommonXmlWriter xmlwrite(0);
  10790. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10791. {
  10792. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10793. }
  10794. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10795. }
  10796. virtual const void * nextInGroup()
  10797. {
  10798. ActivityTimer t(totalCycles, timeActivities);
  10799. loop
  10800. {
  10801. switch (state)
  10802. {
  10803. case JSfill:
  10804. fillLeft();
  10805. state = JSfillright;
  10806. break;
  10807. case JSfillright:
  10808. fillRight();
  10809. state = JScollate;
  10810. break;
  10811. case JSfillleft:
  10812. fillLeft();
  10813. state = JScollate;
  10814. break;
  10815. case JScollate:
  10816. if (right.ordinality() == 0)
  10817. {
  10818. if (left == NULL)
  10819. return NULL;
  10820. state = JSleftonly;
  10821. }
  10822. else
  10823. {
  10824. if (!left)
  10825. state = JSrightonly;
  10826. else
  10827. {
  10828. int diff;
  10829. if(betweenjoin)
  10830. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10831. else
  10832. diff = collate->docompare(left, right.item(0));
  10833. bool limitExceeded = right.ordinality()>abortLimit;
  10834. if (diff == 0)
  10835. {
  10836. if (limitExceeded)
  10837. {
  10838. const void * ret = NULL;
  10839. if(failingLimit)
  10840. ret = joinException(left, failingLimit);
  10841. ReleaseRoxieRow(left);
  10842. left = NULL;
  10843. state = JSfillleft;
  10844. ForEachItemIn(idx, right)
  10845. matchedRight.replace(true, idx);
  10846. if(ret)
  10847. {
  10848. processed++;
  10849. return ret;
  10850. }
  10851. }
  10852. else
  10853. {
  10854. state = JScompare;
  10855. joinLimit = keepLimit;
  10856. }
  10857. }
  10858. else if (diff < 0)
  10859. state = JSleftonly;
  10860. else if (limitExceeded)
  10861. {
  10862. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10863. state = JSfillright;
  10864. }
  10865. else
  10866. state = JSrightonly;
  10867. }
  10868. }
  10869. break;
  10870. case JSrightonly:
  10871. if (rightOuterJoin)
  10872. {
  10873. switch (activityKind)
  10874. {
  10875. case TAKjoin:
  10876. {
  10877. while (right.isItem(rightIndex))
  10878. {
  10879. if (!matchedRight.item(rightIndex))
  10880. {
  10881. const void * rhs = right.item(rightIndex++);
  10882. const void *ret = joinRecords(defaultLeft, rhs, 0);
  10883. if (ret)
  10884. {
  10885. processed++;
  10886. return ret;
  10887. }
  10888. }
  10889. else
  10890. rightIndex++;
  10891. }
  10892. break;
  10893. }
  10894. //Probably excessive to implement the following, but possibly useful
  10895. case TAKdenormalize:
  10896. {
  10897. OwnedConstRoxieRow newLeft;
  10898. newLeft.set(defaultLeft);
  10899. unsigned rowSize = 0;
  10900. unsigned leftCount = 0;
  10901. while (right.isItem(rightIndex))
  10902. {
  10903. if (!matchedRight.item(rightIndex))
  10904. {
  10905. const void * rhs = right.item(rightIndex);
  10906. try
  10907. {
  10908. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10909. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10910. if (thisSize)
  10911. {
  10912. rowSize = thisSize;
  10913. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10914. }
  10915. }
  10916. catch (IException *E)
  10917. {
  10918. throw makeWrappedException(E);
  10919. }
  10920. }
  10921. rightIndex++;
  10922. }
  10923. state = JSfillright;
  10924. if (rowSize)
  10925. {
  10926. processed++;
  10927. return newLeft.getClear();
  10928. }
  10929. break;
  10930. }
  10931. case TAKdenormalizegroup:
  10932. {
  10933. filteredRight.kill();
  10934. while (right.isItem(rightIndex))
  10935. {
  10936. if (!matchedRight.item(rightIndex))
  10937. filteredRight.append(right.item(rightIndex));
  10938. rightIndex++;
  10939. }
  10940. state = JSfillright;
  10941. if (filteredRight.ordinality())
  10942. {
  10943. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10944. filteredRight.kill();
  10945. if (ret)
  10946. {
  10947. processed++;
  10948. return ret;
  10949. }
  10950. }
  10951. break;
  10952. }
  10953. }
  10954. }
  10955. state = JSfillright;
  10956. break;
  10957. case JSleftonly:
  10958. {
  10959. const void * ret = NULL;
  10960. if (!matchedLeft && leftOuterJoin)
  10961. {
  10962. switch (activityKind)
  10963. {
  10964. case TAKjoin:
  10965. ret = joinRecords(left, defaultRight, 0);
  10966. break;
  10967. case TAKdenormalize:
  10968. ret = left;
  10969. left = NULL;
  10970. break;
  10971. case TAKdenormalizegroup:
  10972. filteredRight.kill();
  10973. ret = denormalizeRecords(left, filteredRight);
  10974. break;
  10975. }
  10976. }
  10977. ReleaseRoxieRow(left);
  10978. left = NULL;
  10979. state = JSfillleft;
  10980. if (ret)
  10981. {
  10982. processed++;
  10983. return ret;
  10984. }
  10985. break;
  10986. }
  10987. case JScompare:
  10988. if (joinLimit != 0)
  10989. {
  10990. switch (activityKind)
  10991. {
  10992. case TAKjoin:
  10993. {
  10994. while (right.isItem(rightIndex))
  10995. {
  10996. const void * rhs = right.item(rightIndex++);
  10997. if (helper.match(left, rhs))
  10998. {
  10999. matchedRight.replace(true, rightIndex-1);
  11000. matchedLeft = true;
  11001. if (!exclude)
  11002. {
  11003. const void *ret = joinRecords(left, rhs, ++joinCounter);
  11004. if (ret)
  11005. {
  11006. processed++;
  11007. joinLimit--;
  11008. return ret;
  11009. }
  11010. }
  11011. }
  11012. }
  11013. break;
  11014. }
  11015. case TAKdenormalize:
  11016. {
  11017. OwnedConstRoxieRow newLeft;
  11018. newLeft.set(left);
  11019. unsigned rowSize = 0;
  11020. unsigned leftCount = 0;
  11021. while (right.isItem(rightIndex) && joinLimit)
  11022. {
  11023. try
  11024. {
  11025. const void * rhs = right.item(rightIndex++);
  11026. if (helper.match(left, rhs))
  11027. {
  11028. matchedRight.replace(true, rightIndex-1);
  11029. matchedLeft = true;
  11030. if (!exclude)
  11031. {
  11032. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11033. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11034. if (thisSize)
  11035. {
  11036. rowSize = thisSize;
  11037. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11038. joinLimit--;
  11039. }
  11040. }
  11041. }
  11042. }
  11043. catch (IException *E)
  11044. {
  11045. throw makeWrappedException(E);
  11046. }
  11047. }
  11048. state = JSleftonly;
  11049. rightIndex = 0;
  11050. if (rowSize)
  11051. {
  11052. processed++;
  11053. return newLeft.getClear();
  11054. }
  11055. break;
  11056. }
  11057. case TAKdenormalizegroup:
  11058. {
  11059. filteredRight.kill();
  11060. while (right.isItem(rightIndex))
  11061. {
  11062. const void * rhs = right.item(rightIndex++);
  11063. if (helper.match(left, rhs))
  11064. {
  11065. matchedRight.replace(true, rightIndex-1);
  11066. filteredRight.append(rhs);
  11067. matchedLeft = true;
  11068. if (filteredRight.ordinality()==joinLimit)
  11069. break;
  11070. }
  11071. }
  11072. state = JSleftonly;
  11073. rightIndex = 0;
  11074. if (!exclude && filteredRight.ordinality())
  11075. {
  11076. const void * ret = denormalizeRecords(left, filteredRight);
  11077. filteredRight.kill();
  11078. if (ret)
  11079. {
  11080. processed++;
  11081. return ret;
  11082. }
  11083. }
  11084. break;
  11085. }
  11086. }
  11087. }
  11088. state = JSleftonly;
  11089. rightIndex = 0;
  11090. joinCounter = 0;
  11091. break;
  11092. }
  11093. }
  11094. }
  11095. };
  11096. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11097. {
  11098. unsigned input2;
  11099. unsigned input2idx;
  11100. public:
  11101. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11102. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11103. {
  11104. input2 = 0;
  11105. input2idx = 0;
  11106. }
  11107. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11108. {
  11109. return new CRoxieServerJoinActivity(this, _probeManager);
  11110. }
  11111. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11112. {
  11113. if (idx==1)
  11114. {
  11115. input2 = source;
  11116. input2idx = sourceidx;
  11117. }
  11118. else
  11119. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11120. }
  11121. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11122. {
  11123. switch (idx)
  11124. {
  11125. case 1:
  11126. sourceidx = input2idx;
  11127. return input2;
  11128. case 0:
  11129. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11130. default:
  11131. return (unsigned) -1;
  11132. }
  11133. }
  11134. virtual unsigned numInputs() const { return 2; }
  11135. virtual const StatisticsMapping &queryStatsMapping() const
  11136. {
  11137. return joinStatistics;
  11138. }
  11139. };
  11140. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11141. {
  11142. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11143. }
  11144. //=================================================================================
  11145. #define CONCAT_READAHEAD 1000
  11146. class CRoxieThreadedConcatReader : public CInterface, implements IRecordPullerCallback
  11147. {
  11148. public:
  11149. IMPLEMENT_IINTERFACE;
  11150. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11151. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11152. {
  11153. }
  11154. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11155. {
  11156. space.reinit(CONCAT_READAHEAD);
  11157. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11158. }
  11159. void stop(bool aborting)
  11160. {
  11161. space.interrupt();
  11162. puller.stop(aborting);
  11163. }
  11164. IRoxieInput *queryInput() const
  11165. {
  11166. return puller.queryInput();
  11167. }
  11168. void reset()
  11169. {
  11170. puller.reset();
  11171. ForEachItemIn(idx, buffer)
  11172. ReleaseRoxieRow(buffer.item(idx));
  11173. buffer.clear();
  11174. eof = false;
  11175. atEog = true;
  11176. }
  11177. void setInput(IRoxieInput *_in)
  11178. {
  11179. puller.setInput(this, _in);
  11180. }
  11181. virtual void processRow(const void *row)
  11182. {
  11183. buffer.enqueue(row);
  11184. ready.signal();
  11185. space.wait();
  11186. }
  11187. virtual void processGroup(const ConstPointerArray &rows)
  11188. {
  11189. // We use record-by-record input mode of the puller thread even in grouped mode.
  11190. throwUnexpected();
  11191. }
  11192. virtual void processEOG()
  11193. {
  11194. if (grouped)
  11195. processRow(NULL);
  11196. }
  11197. virtual void processDone()
  11198. {
  11199. processRow(NULL);
  11200. }
  11201. virtual bool fireException(IException *e)
  11202. {
  11203. // called from puller thread on failure
  11204. ready.interrupt(LINK(e));
  11205. space.interrupt(e);
  11206. return true;
  11207. }
  11208. bool peek(const void * &row, bool &anyActive)
  11209. {
  11210. if (!eof)
  11211. {
  11212. if (buffer.ordinality())
  11213. {
  11214. space.signal();
  11215. row = buffer.dequeue();
  11216. if (row==NULL)
  11217. {
  11218. if (atEog)
  11219. {
  11220. eof = true;
  11221. return false;
  11222. }
  11223. else
  11224. atEog = true;
  11225. }
  11226. else if (grouped)
  11227. atEog = false;
  11228. return true;
  11229. }
  11230. anyActive = true;
  11231. }
  11232. return false;
  11233. }
  11234. protected:
  11235. RecordPullerThread puller;
  11236. InterruptableSemaphore space;
  11237. InterruptableSemaphore &ready;
  11238. SafeQueueOf<const void, true> buffer;
  11239. bool atEog;
  11240. bool eof;
  11241. bool grouped;
  11242. };
  11243. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11244. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11245. {
  11246. InterruptableSemaphore ready;
  11247. ReaderArray pullers;
  11248. unsigned numInputs;
  11249. unsigned nextPuller; // for round robin
  11250. unsigned readyPending;
  11251. bool eof;
  11252. bool inGroup;
  11253. bool grouped;
  11254. public:
  11255. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11256. : CRoxieServerActivity(_factory, _probeManager), grouped(_grouped)
  11257. {
  11258. numInputs = _numInputs;
  11259. eof = (numInputs==0);
  11260. inGroup = false;
  11261. nextPuller = 0;
  11262. readyPending = 0;
  11263. for (unsigned i = 0; i < numInputs; i++)
  11264. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11265. }
  11266. ~CRoxieServerThreadedConcatActivity()
  11267. {
  11268. ForEachItemIn(idx, pullers)
  11269. delete &pullers.item(idx);
  11270. }
  11271. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11272. {
  11273. eof = (numInputs==0);
  11274. inGroup = false;
  11275. nextPuller = 0;
  11276. readyPending = 0;
  11277. ready.reinit();
  11278. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11279. ForEachItemIn(idx, pullers)
  11280. {
  11281. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11282. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11283. // in the part of the subgraph that the thread uses has been started.
  11284. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11285. }
  11286. }
  11287. virtual void stop(bool aborting)
  11288. {
  11289. ready.interrupt();
  11290. ForEachItemIn(idx, pullers)
  11291. pullers.item(idx).stop(aborting);
  11292. CRoxieServerActivity::stop(aborting);
  11293. }
  11294. virtual unsigned __int64 queryLocalCycles() const
  11295. {
  11296. return 0;
  11297. }
  11298. virtual IRoxieInput *queryInput(unsigned idx) const
  11299. {
  11300. if (pullers.isItem(idx))
  11301. return pullers.item(idx).queryInput();
  11302. else
  11303. return NULL;
  11304. }
  11305. virtual void reset()
  11306. {
  11307. CRoxieServerActivity::reset();
  11308. ForEachItemIn(idx, pullers)
  11309. pullers.item(idx).reset();
  11310. eof = false;
  11311. inGroup = false;
  11312. nextPuller = 0;
  11313. readyPending = 0;
  11314. }
  11315. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11316. {
  11317. if (pullers.isItem(idx))
  11318. pullers.item(idx).setInput(_in);
  11319. else
  11320. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11321. }
  11322. virtual const void * nextInGroup()
  11323. {
  11324. ActivityTimer t(totalCycles, timeActivities);
  11325. if (eof)
  11326. return NULL;
  11327. loop
  11328. {
  11329. if (readyPending && !inGroup)
  11330. {
  11331. if (readyPending > 1)
  11332. ready.signal(readyPending-1);
  11333. readyPending = 0;
  11334. }
  11335. else
  11336. ready.wait();
  11337. bool anyActive = false;
  11338. ForEachItemIn(unused_index, pullers)
  11339. {
  11340. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11341. const void *ret;
  11342. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11343. if (fetched)
  11344. {
  11345. inGroup = (ret != NULL);
  11346. return ret;
  11347. }
  11348. if (inGroup && grouped)
  11349. {
  11350. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11351. readyPending++;
  11352. anyActive = true;
  11353. break;
  11354. }
  11355. nextPuller++;
  11356. if (nextPuller==pullers.ordinality())
  11357. nextPuller = 0;
  11358. }
  11359. if (!anyActive)
  11360. break;
  11361. // A ready signal without anything being ready means someone reached end-of-file.
  11362. }
  11363. eof = true;
  11364. return NULL;
  11365. }
  11366. };
  11367. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11368. {
  11369. IRoxieInput *curInput;
  11370. bool eogSeen;
  11371. bool anyThisGroup;
  11372. bool grouped;
  11373. unsigned numInputs;
  11374. unsigned inputIdx;
  11375. IRoxieInput **inputArray;
  11376. public:
  11377. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11378. : CRoxieServerActivity(_factory, _probeManager)
  11379. {
  11380. eogSeen = false;
  11381. anyThisGroup = false;
  11382. grouped = _grouped;
  11383. numInputs = _numInputs;
  11384. inputIdx = 0;
  11385. inputArray = new IRoxieInput*[numInputs];
  11386. for (unsigned i = 0; i < numInputs; i++)
  11387. inputArray[i] = NULL;
  11388. curInput = NULL;
  11389. }
  11390. ~CRoxieServerOrderedConcatActivity()
  11391. {
  11392. delete [] inputArray;
  11393. }
  11394. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11395. {
  11396. inputIdx = 0;
  11397. curInput = inputArray[inputIdx];
  11398. eogSeen = false;
  11399. anyThisGroup = false;
  11400. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11401. for (unsigned i = 0; i < numInputs; i++)
  11402. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11403. }
  11404. virtual void stop(bool aborting)
  11405. {
  11406. for (unsigned i = 0; i < numInputs; i++)
  11407. inputArray[i]->stop(aborting);
  11408. CRoxieServerActivity::stop(aborting);
  11409. }
  11410. virtual unsigned __int64 queryLocalCycles() const
  11411. {
  11412. return 0;
  11413. }
  11414. virtual IRoxieInput *queryInput(unsigned idx) const
  11415. {
  11416. if (idx < numInputs)
  11417. return inputArray[idx];
  11418. else
  11419. return NULL;
  11420. }
  11421. virtual void reset()
  11422. {
  11423. CRoxieServerActivity::reset();
  11424. for (unsigned i = 0; i < numInputs; i++)
  11425. inputArray[i]->reset();
  11426. }
  11427. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11428. {
  11429. inputArray[idx] = _in;
  11430. }
  11431. virtual const void * nextInGroup()
  11432. {
  11433. ActivityTimer t(totalCycles, timeActivities);
  11434. if (!curInput)
  11435. return NULL; // eof
  11436. const void * next = curInput->nextInGroup();
  11437. if (next)
  11438. {
  11439. anyThisGroup = true;
  11440. eogSeen = false;
  11441. processed++;
  11442. return next;
  11443. }
  11444. else if (!eogSeen)
  11445. {
  11446. eogSeen = true;
  11447. if (grouped)
  11448. {
  11449. if (anyThisGroup)
  11450. {
  11451. anyThisGroup = false;
  11452. return NULL;
  11453. }
  11454. else
  11455. return nextInGroup();
  11456. }
  11457. else
  11458. return nextInGroup();
  11459. }
  11460. else if (inputIdx < numInputs-1)
  11461. {
  11462. inputIdx++;
  11463. curInput = inputArray[inputIdx];
  11464. eogSeen = false;
  11465. return nextInGroup();
  11466. }
  11467. else
  11468. {
  11469. curInput = NULL;
  11470. return NULL;
  11471. }
  11472. }
  11473. };
  11474. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11475. {
  11476. bool ordered;
  11477. bool grouped;
  11478. public:
  11479. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11480. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11481. {
  11482. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11483. ordered = helper->isOrdered();
  11484. grouped = helper->queryOutputMeta()->isGrouped();
  11485. }
  11486. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11487. {
  11488. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11489. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11490. else
  11491. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11492. }
  11493. };
  11494. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11495. {
  11496. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11497. }
  11498. //=================================================================================
  11499. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11500. {
  11501. IRoxieInput * selectedInput;
  11502. unsigned savedParentExtractSize;
  11503. const byte * savedParentExtract;
  11504. bool foundInput;
  11505. public:
  11506. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11507. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11508. {
  11509. foundInput = false;
  11510. selectedInput = NULL;
  11511. savedParentExtractSize = 0;;
  11512. savedParentExtract = NULL;
  11513. }
  11514. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11515. {
  11516. //Don't start the inputs yet so we can short-circuit...
  11517. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11518. savedParentExtractSize = parentExtractSize;
  11519. savedParentExtract = parentExtract;
  11520. }
  11521. virtual void stop(bool aborting)
  11522. {
  11523. if (foundInput)
  11524. {
  11525. if (selectedInput)
  11526. selectedInput->stop(aborting);
  11527. }
  11528. else
  11529. {
  11530. for (unsigned i = 0; i < numInputs; i++)
  11531. inputArray[i]->stop(aborting);
  11532. }
  11533. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11534. }
  11535. virtual void reset()
  11536. {
  11537. CRoxieServerMultiInputBaseActivity::reset();
  11538. foundInput = false;
  11539. selectedInput = NULL;
  11540. }
  11541. virtual unsigned __int64 queryLocalCycles() const
  11542. {
  11543. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11544. }
  11545. virtual const void * nextInGroup()
  11546. {
  11547. ActivityTimer t(totalCycles, timeActivities);
  11548. if (!foundInput)
  11549. {
  11550. foundInput = true;
  11551. //If we get an exception in this loop then stop() will stop any started inputs
  11552. for (unsigned i=0; i < numInputs; i++)
  11553. {
  11554. selectedInput = inputArray[i];
  11555. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11556. const void * next = selectedInput->nextInGroup();
  11557. if (next)
  11558. {
  11559. //Found a row so stop remaining
  11560. for (unsigned j=i+1; j < numInputs; j++)
  11561. inputArray[j]->stop(false);
  11562. processed++;
  11563. return next;
  11564. }
  11565. selectedInput->stop(false);
  11566. }
  11567. selectedInput = NULL;
  11568. return NULL;
  11569. }
  11570. if (!selectedInput)
  11571. return NULL;
  11572. const void * next = selectedInput->nextInGroup();
  11573. if (next)
  11574. processed++;
  11575. return next;
  11576. }
  11577. };
  11578. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11579. {
  11580. public:
  11581. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11582. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11583. {
  11584. }
  11585. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11586. {
  11587. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11588. }
  11589. };
  11590. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11591. {
  11592. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11593. }
  11594. //=================================================================================
  11595. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11596. {
  11597. IHThorMergeArg &helper;
  11598. unsigned *mergeheap;
  11599. unsigned activeInputs;
  11600. unsigned numInputs;
  11601. IRoxieInput **inputArray;
  11602. const void **pending;
  11603. bool first;
  11604. ICompare *compare;
  11605. bool dedup;
  11606. void permute()
  11607. {
  11608. assertex(activeInputs == 0);
  11609. for(unsigned i = 0; i < numInputs; i++)
  11610. if(pullInput(i))
  11611. mergeheap[activeInputs++] = i;
  11612. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11613. // the heap property: no element should be smaller than its parent
  11614. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11615. // 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
  11616. if (activeInputs >= 2)
  11617. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11618. siftDown(p);
  11619. if(dedup)
  11620. siftDownDedupTop();
  11621. else
  11622. siftDown(0);
  11623. }
  11624. void readNext()
  11625. {
  11626. if(!pullInput(mergeheap[0]))
  11627. if(!promote(0))
  11628. return;
  11629. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11630. if(dedup)
  11631. siftDownDedupTop();
  11632. else
  11633. siftDown(0);
  11634. }
  11635. bool pullInput(unsigned i)
  11636. {
  11637. const void *next = inputArray[i]->nextInGroup();
  11638. if (!next)
  11639. next = inputArray[i]->nextInGroup();
  11640. pending[i] = next;
  11641. return (next != NULL);
  11642. }
  11643. bool promote(unsigned p)
  11644. {
  11645. activeInputs--;
  11646. if(activeInputs == p)
  11647. return false;
  11648. mergeheap[p] = mergeheap[activeInputs];
  11649. return true;
  11650. }
  11651. bool siftDown(unsigned p)
  11652. {
  11653. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11654. bool nochange = true;
  11655. while(1)
  11656. {
  11657. unsigned c = p*2 + 1;
  11658. if(c >= activeInputs)
  11659. return nochange;
  11660. if(c+1 < activeInputs)
  11661. {
  11662. int childcmp = BuffCompare(c+1, c);
  11663. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11664. ++c;
  11665. }
  11666. int cmp = BuffCompare(c, p);
  11667. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11668. return nochange;
  11669. nochange = false;
  11670. unsigned r = mergeheap[c];
  11671. mergeheap[c] = mergeheap[p];
  11672. mergeheap[p] = r;
  11673. p = c;
  11674. }
  11675. }
  11676. void siftDownDedupTop()
  11677. {
  11678. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11679. if(activeInputs < 2)
  11680. return;
  11681. unsigned c = 1;
  11682. int childcmp = 1;
  11683. if(activeInputs >= 3)
  11684. {
  11685. childcmp = BuffCompare(2, 1);
  11686. if(childcmp < 0)
  11687. c = 2;
  11688. }
  11689. int cmp = BuffCompare(c, 0);
  11690. if(cmp > 0)
  11691. return;
  11692. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11693. while(cmp <= 0)
  11694. {
  11695. if(cmp == 0)
  11696. {
  11697. if(mergeheap[c] < mergeheap[0])
  11698. {
  11699. unsigned r = mergeheap[c];
  11700. mergeheap[c] = mergeheap[0];
  11701. mergeheap[0] = r;
  11702. }
  11703. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11704. if(!pullInput(mergeheap[c]))
  11705. if(!promote(c))
  11706. break;
  11707. siftDown(c);
  11708. }
  11709. else
  11710. {
  11711. unsigned r = mergeheap[c];
  11712. mergeheap[c] = mergeheap[0];
  11713. mergeheap[0] = r;
  11714. if(siftDown(c))
  11715. break;
  11716. }
  11717. cmp = BuffCompare(c, 0);
  11718. }
  11719. // the following loop ensures the uniqueness property holds on the other branch too
  11720. c = 3-c;
  11721. if(activeInputs <= c)
  11722. return;
  11723. while(childcmp == 0)
  11724. {
  11725. if(mergeheap[c] < mergeheap[0])
  11726. {
  11727. unsigned r = mergeheap[c];
  11728. mergeheap[c] = mergeheap[0];
  11729. mergeheap[0] = r;
  11730. }
  11731. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11732. if(!pullInput(mergeheap[c]))
  11733. if(!promote(c))
  11734. break;
  11735. siftDown(c);
  11736. childcmp = BuffCompare(c, 0);
  11737. }
  11738. }
  11739. inline int BuffCompare(unsigned a, unsigned b)
  11740. {
  11741. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11742. }
  11743. public:
  11744. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11745. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11746. {
  11747. activeInputs = 0;
  11748. first = true;
  11749. mergeheap = new unsigned[numInputs];
  11750. inputArray = new IRoxieInput*[numInputs];
  11751. pending = new const void *[numInputs];
  11752. compare = helper.queryCompare();
  11753. dedup = helper.dedup();
  11754. for (unsigned i = 0; i < numInputs; i++)
  11755. {
  11756. inputArray[i] = NULL;
  11757. pending[i] = NULL;
  11758. }
  11759. }
  11760. ~CRoxieServerMergeActivity()
  11761. {
  11762. delete [] mergeheap;
  11763. delete [] inputArray;
  11764. delete [] pending;
  11765. }
  11766. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11767. {
  11768. activeInputs = 0;
  11769. first = true;
  11770. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11771. for (unsigned i = 0; i < numInputs; i++)
  11772. {
  11773. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11774. }
  11775. }
  11776. virtual void stop(bool aborting)
  11777. {
  11778. for (unsigned i = 0; i < numInputs; i++)
  11779. {
  11780. inputArray[i]->stop(aborting);
  11781. }
  11782. CRoxieServerActivity::stop(aborting);
  11783. }
  11784. virtual void reset()
  11785. {
  11786. for (unsigned i = 0; i < numInputs; i++)
  11787. {
  11788. ReleaseClearRoxieRow(pending[i]);
  11789. inputArray[i]->reset();
  11790. }
  11791. CRoxieServerActivity::reset();
  11792. }
  11793. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11794. {
  11795. inputArray[idx] = _in;
  11796. }
  11797. virtual const void * nextInGroup()
  11798. {
  11799. ActivityTimer t(totalCycles, timeActivities);
  11800. if (first)
  11801. {
  11802. permute();
  11803. first = false;
  11804. }
  11805. if (activeInputs)
  11806. {
  11807. const void *next = pending[mergeheap[0]];
  11808. readNext();
  11809. if (next)
  11810. processed++;
  11811. return next;
  11812. }
  11813. else
  11814. return NULL;
  11815. }
  11816. };
  11817. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11818. {
  11819. public:
  11820. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11821. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11822. {
  11823. }
  11824. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11825. {
  11826. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11827. }
  11828. };
  11829. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11830. {
  11831. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11832. }
  11833. //=================================================================================
  11834. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11835. {
  11836. IHThorRegroupArg &helper;
  11837. unsigned inputIndex;
  11838. bool eof;
  11839. unsigned __int64 numProcessedLastGroup;
  11840. public:
  11841. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11842. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11843. {
  11844. inputIndex = 0;
  11845. eof = false;
  11846. numProcessedLastGroup = 0;
  11847. }
  11848. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11849. {
  11850. inputIndex = 0;
  11851. eof = false;
  11852. numProcessedLastGroup = processed;
  11853. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11854. }
  11855. const void * nextFromInputs()
  11856. {
  11857. unsigned initialInput = inputIndex;
  11858. while (inputIndex < numInputs)
  11859. {
  11860. const void * next = inputArray[inputIndex]->nextInGroup();
  11861. if (next)
  11862. {
  11863. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11864. {
  11865. ReleaseRoxieRow(next);
  11866. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11867. }
  11868. return next;
  11869. }
  11870. inputIndex++;
  11871. }
  11872. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11873. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11874. inputIndex = 0;
  11875. return NULL;
  11876. }
  11877. virtual const void * nextInGroup()
  11878. {
  11879. ActivityTimer t(totalCycles, timeActivities);
  11880. if (eof)
  11881. return NULL;
  11882. const void * ret = nextFromInputs();
  11883. if (ret)
  11884. {
  11885. processed++;
  11886. return ret;
  11887. }
  11888. if (numProcessedLastGroup != processed)
  11889. {
  11890. numProcessedLastGroup = processed;
  11891. return NULL;
  11892. }
  11893. eof = true;
  11894. return NULL;
  11895. }
  11896. #if 0
  11897. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11898. {
  11899. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11900. if (idx)
  11901. {
  11902. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11903. puller->setInput(0, _in);
  11904. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11905. }
  11906. else
  11907. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11908. }
  11909. #endif
  11910. };
  11911. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11912. {
  11913. public:
  11914. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11915. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11916. {
  11917. }
  11918. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11919. {
  11920. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11921. }
  11922. };
  11923. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11924. {
  11925. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11926. }
  11927. //=================================================================================
  11928. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11929. {
  11930. IHThorCombineArg &helper;
  11931. unsigned __int64 numProcessedLastGroup;
  11932. public:
  11933. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11934. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11935. {
  11936. numProcessedLastGroup = 0;
  11937. }
  11938. ~CRoxieServerCombineActivity()
  11939. {
  11940. }
  11941. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11942. {
  11943. numProcessedLastGroup = processed;
  11944. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11945. }
  11946. void nextInputs(ConstPointerArray & out)
  11947. {
  11948. for (unsigned i=0; i < numInputs; i++)
  11949. {
  11950. const void * next = inputArray[i]->nextInGroup();
  11951. if (next)
  11952. out.append(next);
  11953. }
  11954. }
  11955. virtual bool needsAllocator() const { return true; }
  11956. virtual const void * nextInGroup()
  11957. {
  11958. ActivityTimer t(totalCycles, timeActivities);
  11959. loop
  11960. {
  11961. ConstPointerArray group;
  11962. nextInputs(group);
  11963. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11964. nextInputs(group);
  11965. if (group.ordinality() == 0)
  11966. {
  11967. numProcessedLastGroup = processed;
  11968. return NULL;
  11969. }
  11970. else if (group.ordinality() != numInputs)
  11971. {
  11972. ReleaseRoxieRowSet(group);
  11973. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11974. }
  11975. try
  11976. {
  11977. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11978. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11979. ReleaseRoxieRowSet(group);
  11980. if (outSize)
  11981. {
  11982. processed++;
  11983. return rowBuilder.finalizeRowClear(outSize);
  11984. }
  11985. }
  11986. catch (IException *E)
  11987. {
  11988. ReleaseRoxieRowSet(group);
  11989. throw makeWrappedException(E);
  11990. }
  11991. }
  11992. }
  11993. };
  11994. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11995. {
  11996. public:
  11997. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11998. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11999. {
  12000. }
  12001. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12002. {
  12003. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  12004. }
  12005. };
  12006. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12007. {
  12008. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12009. }
  12010. //=================================================================================
  12011. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12012. {
  12013. IHThorCombineGroupArg &helper;
  12014. unsigned __int64 numProcessedLastGroup;
  12015. public:
  12016. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12017. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12018. {
  12019. numProcessedLastGroup = 0;
  12020. }
  12021. ~CRoxieServerCombineGroupActivity()
  12022. {
  12023. }
  12024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12025. {
  12026. numProcessedLastGroup = processed;
  12027. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12028. }
  12029. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12030. {
  12031. switch(idx)
  12032. {
  12033. case 0:
  12034. #if 0
  12035. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  12036. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  12037. puller->setInput(0, _in);
  12038. _in = puller;
  12039. #endif
  12040. input = _in;
  12041. break;
  12042. case 1:
  12043. input1 = _in;
  12044. break;
  12045. default:
  12046. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12047. }
  12048. }
  12049. virtual IRoxieInput *queryOutput(unsigned idx)
  12050. {
  12051. if (idx==(unsigned)-1)
  12052. idx = 0;
  12053. return idx ? NULL : this;
  12054. }
  12055. virtual bool needsAllocator() const { return true; }
  12056. virtual const void * nextInGroup()
  12057. {
  12058. ActivityTimer t(totalCycles, timeActivities);
  12059. loop
  12060. {
  12061. const void * left = input->nextInGroup();
  12062. if (!left && (numProcessedLastGroup == processed))
  12063. left = input->nextInGroup();
  12064. if (!left)
  12065. {
  12066. if (numProcessedLastGroup == processed)
  12067. {
  12068. const void * nextRight = input1->nextInGroup();
  12069. if (nextRight)
  12070. {
  12071. ReleaseRoxieRow(nextRight);
  12072. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12073. }
  12074. }
  12075. else
  12076. numProcessedLastGroup = processed;
  12077. return NULL;
  12078. }
  12079. ConstPointerArray group;
  12080. loop
  12081. {
  12082. const void * in = input1->nextInGroup();
  12083. if (!in)
  12084. break;
  12085. group.append(in);
  12086. }
  12087. if (group.ordinality() == 0)
  12088. {
  12089. ReleaseRoxieRow(left);
  12090. ReleaseRoxieRowSet(group);
  12091. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12092. }
  12093. try
  12094. {
  12095. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12096. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12097. ReleaseRoxieRow(left);
  12098. ReleaseRoxieRowSet(group);
  12099. if (outSize)
  12100. {
  12101. processed++;
  12102. return rowBuilder.finalizeRowClear(outSize);
  12103. }
  12104. }
  12105. catch (IException *E)
  12106. {
  12107. ReleaseRoxieRow(left);
  12108. ReleaseRoxieRowSet(group);
  12109. throw makeWrappedException(E);
  12110. }
  12111. }
  12112. }
  12113. };
  12114. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12115. {
  12116. unsigned input2;
  12117. unsigned input2idx;
  12118. public:
  12119. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12120. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12121. {
  12122. input2 = 0;
  12123. input2idx = 0;
  12124. }
  12125. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12126. {
  12127. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  12128. }
  12129. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12130. {
  12131. if (idx==1)
  12132. {
  12133. input2 = source;
  12134. input2idx = sourceidx;
  12135. }
  12136. else
  12137. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12138. }
  12139. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12140. {
  12141. switch (idx)
  12142. {
  12143. case 1:
  12144. sourceidx = input2idx;
  12145. return input2;
  12146. case 0:
  12147. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12148. default:
  12149. return (unsigned) -1;
  12150. }
  12151. }
  12152. virtual unsigned numInputs() const { return 2; }
  12153. };
  12154. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12155. {
  12156. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12157. }
  12158. //=================================================================================
  12159. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12160. {
  12161. IHThorRollupGroupArg &helper;
  12162. bool eof;
  12163. public:
  12164. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12165. : CRoxieServerActivity(_factory, _probeManager),
  12166. helper((IHThorRollupGroupArg &)basehelper)
  12167. {
  12168. eof = false;
  12169. }
  12170. ~CRoxieServerRollupGroupActivity()
  12171. {
  12172. }
  12173. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12174. {
  12175. eof = false;
  12176. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12177. }
  12178. virtual bool needsAllocator() const { return true; }
  12179. virtual const void * nextInGroup()
  12180. {
  12181. ActivityTimer t(totalCycles, timeActivities);
  12182. if (eof)
  12183. return NULL;
  12184. loop
  12185. {
  12186. ConstPointerArray group;
  12187. loop
  12188. {
  12189. const void * in = input->nextInGroup();
  12190. if (!in)
  12191. break;
  12192. group.append(in);
  12193. }
  12194. if (group.ordinality() == 0)
  12195. {
  12196. eof = true;
  12197. return NULL;
  12198. }
  12199. try
  12200. {
  12201. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12202. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12203. ReleaseRoxieRowSet(group);
  12204. if (outSize)
  12205. {
  12206. processed++;
  12207. return rowBuilder.finalizeRowClear(outSize);
  12208. }
  12209. }
  12210. catch (IException * E)
  12211. {
  12212. ReleaseRoxieRowSet(group);
  12213. throw makeWrappedException(E);
  12214. }
  12215. }
  12216. }
  12217. };
  12218. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12219. {
  12220. public:
  12221. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12222. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12223. {
  12224. }
  12225. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12226. {
  12227. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  12228. }
  12229. };
  12230. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12231. {
  12232. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12233. }
  12234. //=================================================================================
  12235. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12236. {
  12237. IHThorFilterProjectArg &helper;
  12238. unsigned numProcessedLastGroup;
  12239. unsigned __int64 recordCount;
  12240. public:
  12241. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12242. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12243. {
  12244. numProcessedLastGroup = 0;
  12245. recordCount = 0;
  12246. }
  12247. ~CRoxieServerFilterProjectActivity()
  12248. {
  12249. }
  12250. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12251. {
  12252. numProcessedLastGroup = 0;
  12253. recordCount = 0;
  12254. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12255. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12256. }
  12257. virtual bool needsAllocator() const { return true; }
  12258. virtual const void * nextInGroup()
  12259. {
  12260. ActivityTimer t(totalCycles, timeActivities);
  12261. if (eof)
  12262. return NULL;
  12263. loop
  12264. {
  12265. const void * in = input->nextInGroup();
  12266. if (!in)
  12267. {
  12268. recordCount = 0;
  12269. if (numProcessedLastGroup == processed)
  12270. in = input->nextInGroup();
  12271. if (!in)
  12272. {
  12273. numProcessedLastGroup = processed;
  12274. return NULL;
  12275. }
  12276. }
  12277. try
  12278. {
  12279. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12280. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12281. ReleaseRoxieRow(in);
  12282. if (outSize)
  12283. {
  12284. processed++;
  12285. return rowBuilder.finalizeRowClear(outSize);
  12286. }
  12287. }
  12288. catch (IException *E)
  12289. {
  12290. throw makeWrappedException(E);
  12291. }
  12292. }
  12293. }
  12294. };
  12295. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12296. {
  12297. public:
  12298. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12299. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12300. {
  12301. }
  12302. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12303. {
  12304. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  12305. }
  12306. };
  12307. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12308. {
  12309. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12310. }
  12311. //=================================================================================
  12312. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12313. {
  12314. unsigned numProcessedLastGroup;
  12315. bool count;
  12316. unsigned __int64 recordCount;
  12317. public:
  12318. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12319. : CRoxieServerActivity(_factory, _probeManager),
  12320. count(_count)
  12321. {
  12322. numProcessedLastGroup = 0;
  12323. recordCount = 0;
  12324. }
  12325. ~CRoxieServerProjectActivity()
  12326. {
  12327. }
  12328. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12329. {
  12330. numProcessedLastGroup = 0;
  12331. recordCount = 0;
  12332. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12333. }
  12334. virtual bool needsAllocator() const { return true; }
  12335. virtual const void * nextInGroup()
  12336. {
  12337. ActivityTimer t(totalCycles, timeActivities);
  12338. loop
  12339. {
  12340. OwnedConstRoxieRow in = input->nextInGroup();
  12341. if (!in)
  12342. {
  12343. recordCount = 0;
  12344. if (numProcessedLastGroup == processed)
  12345. in.setown(input->nextInGroup());
  12346. if (!in)
  12347. {
  12348. numProcessedLastGroup = processed;
  12349. return NULL;
  12350. }
  12351. }
  12352. try
  12353. {
  12354. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12355. size32_t outSize;
  12356. if (count)
  12357. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12358. else
  12359. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12360. if (outSize)
  12361. {
  12362. processed++;
  12363. return rowBuilder.finalizeRowClear(outSize);
  12364. }
  12365. }
  12366. catch (IException *E)
  12367. {
  12368. throw makeWrappedException(E);
  12369. }
  12370. }
  12371. }
  12372. };
  12373. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12374. {
  12375. protected:
  12376. bool count;
  12377. public:
  12378. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12379. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12380. {
  12381. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12382. }
  12383. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12384. {
  12385. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12386. }
  12387. };
  12388. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12389. {
  12390. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12391. }
  12392. //=================================================================================
  12393. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12394. {
  12395. unsigned numProcessedLastGroup;
  12396. bool count;
  12397. bool eof;
  12398. bool allPulled;
  12399. bool isThreaded;
  12400. unsigned preload;
  12401. unsigned __int64 recordCount;
  12402. IHThorPrefetchProjectArg &helper;
  12403. RecordPullerThread puller;
  12404. InterruptableSemaphore ready;
  12405. InterruptableSemaphore space;
  12406. class PrefetchInfo : public CInterface
  12407. {
  12408. public:
  12409. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12410. {
  12411. if (helper.preTransform(extract, _in, _recordCount))
  12412. {
  12413. in.setown(_in);
  12414. recordCount = _recordCount;
  12415. }
  12416. else
  12417. ReleaseRoxieRow(_in);
  12418. }
  12419. OwnedConstRoxieRow in;
  12420. unsigned __int64 recordCount;
  12421. rtlRowBuilder extract;
  12422. };
  12423. QueueOf<PrefetchInfo, true> pulled;
  12424. CriticalSection pulledCrit;
  12425. public:
  12426. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12427. : CRoxieServerActivity(_factory, _probeManager),
  12428. helper((IHThorPrefetchProjectArg &) basehelper),
  12429. puller(false),
  12430. count(_count)
  12431. {
  12432. numProcessedLastGroup = 0;
  12433. recordCount = 0;
  12434. eof = false;
  12435. allPulled = false;
  12436. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12437. preload = 0;
  12438. }
  12439. ~CRoxieServerPrefetchProjectActivity()
  12440. {
  12441. while (pulled.ordinality())
  12442. ::Release(pulled.dequeue());
  12443. }
  12444. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12445. {
  12446. if (idx)
  12447. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12448. puller.setInput(this, _in);
  12449. }
  12450. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12451. {
  12452. numProcessedLastGroup = 0;
  12453. recordCount = 0;
  12454. eof = false;
  12455. allPulled = false;
  12456. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12457. preload = helper.getLookahead();
  12458. if (!preload)
  12459. preload = ctx->queryOptions().prefetchProjectPreload;
  12460. space.reinit(preload);
  12461. ready.reinit();
  12462. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12463. }
  12464. virtual void stop(bool aborting)
  12465. {
  12466. space.interrupt();
  12467. ready.interrupt();
  12468. CRoxieServerActivity::stop(aborting);
  12469. puller.stop(aborting);
  12470. }
  12471. virtual void reset()
  12472. {
  12473. CRoxieServerActivity::reset();
  12474. puller.reset();
  12475. allPulled = false;
  12476. while (pulled.ordinality())
  12477. ::Release(pulled.dequeue());
  12478. }
  12479. virtual PrefetchInfo *readNextRecord()
  12480. {
  12481. if (!isThreaded)
  12482. {
  12483. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12484. puller.pullRecords(1);
  12485. }
  12486. else
  12487. ready.wait();
  12488. CriticalBlock b(pulledCrit);
  12489. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12490. space.signal();
  12491. return ret;
  12492. }
  12493. virtual bool needsAllocator() const { return true; }
  12494. virtual const void * nextInGroup()
  12495. {
  12496. ActivityTimer t(totalCycles, timeActivities);
  12497. if (eof)
  12498. return NULL;
  12499. loop
  12500. {
  12501. Owned<PrefetchInfo> in = readNextRecord();
  12502. if (!in)
  12503. {
  12504. recordCount = 0;
  12505. if (numProcessedLastGroup == processed)
  12506. in.setown(readNextRecord());
  12507. if (!in)
  12508. {
  12509. numProcessedLastGroup = processed;
  12510. eof = true;
  12511. return NULL;
  12512. }
  12513. }
  12514. try
  12515. {
  12516. if (in->in)
  12517. {
  12518. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12519. size32_t outSize;
  12520. IThorChildGraph *child = helper.queryChild();
  12521. Owned<IEclGraphResults> results;
  12522. if (child)
  12523. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12524. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12525. if (outSize)
  12526. {
  12527. processed++;
  12528. return rowBuilder.finalizeRowClear(outSize);
  12529. }
  12530. }
  12531. }
  12532. catch (IException *E)
  12533. {
  12534. throw makeWrappedException(E);
  12535. }
  12536. }
  12537. }
  12538. // interface IExceptionHandler
  12539. virtual bool fireException(IException *e)
  12540. {
  12541. // called from puller thread on failure
  12542. ready.interrupt(LINK(e));
  12543. space.interrupt(e);
  12544. return true;
  12545. }
  12546. // interface IRecordPullerCallback
  12547. virtual void processRow(const void *row)
  12548. {
  12549. {
  12550. CriticalBlock b(pulledCrit);
  12551. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12552. }
  12553. if (isThreaded)
  12554. {
  12555. ready.signal();
  12556. space.wait();
  12557. }
  12558. }
  12559. virtual void processEOG()
  12560. {
  12561. {
  12562. CriticalBlock b(pulledCrit);
  12563. pulled.enqueue(NULL);
  12564. }
  12565. if (isThreaded)
  12566. {
  12567. ready.signal();
  12568. space.wait();
  12569. }
  12570. }
  12571. virtual void processGroup(const ConstPointerArray &rows)
  12572. {
  12573. throwUnexpected();
  12574. }
  12575. virtual void processDone()
  12576. {
  12577. CriticalBlock b(pulledCrit);
  12578. allPulled = true;
  12579. if (isThreaded)
  12580. ready.signal();
  12581. }
  12582. };
  12583. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12584. {
  12585. public:
  12586. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12587. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12588. {
  12589. }
  12590. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12591. {
  12592. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12593. }
  12594. };
  12595. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12596. {
  12597. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12598. }
  12599. //=================================================================================
  12600. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12601. {
  12602. public:
  12603. CPointerArrayRoxieInput()
  12604. {
  12605. rowset = NULL;
  12606. rowcount = 0;
  12607. curRow = 0;
  12608. }
  12609. void init(size32_t _rowcount, byte **_rowset)
  12610. {
  12611. rowset = _rowset;
  12612. rowcount = _rowcount;
  12613. curRow = 0;
  12614. }
  12615. virtual const void * nextInGroup()
  12616. {
  12617. if (curRow < rowcount)
  12618. {
  12619. const void * ret = rowset[curRow];
  12620. if (ret)
  12621. LinkRoxieRow(ret);
  12622. curRow++;
  12623. return ret;
  12624. }
  12625. return NULL;
  12626. }
  12627. protected:
  12628. byte **rowset;
  12629. size32_t rowcount;
  12630. size32_t curRow;
  12631. };
  12632. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12633. {
  12634. protected:
  12635. IHThorLoopArg &helper;
  12636. ThorActivityKind activityKind;
  12637. unsigned maxIterations;
  12638. bool finishedLooping;
  12639. unsigned flags;
  12640. bool eof;
  12641. rtlRowBuilder loopExtractBuilder;
  12642. unsigned loopGraphId;
  12643. Linked<IOutputMetaData> counterMeta;
  12644. public:
  12645. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12646. : CRoxieServerActivity(_factory, _probeManager),
  12647. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12648. {
  12649. eof = false;
  12650. finishedLooping = false;
  12651. activityKind = factory->getKind();
  12652. flags = helper.getFlags();
  12653. maxIterations = 0;
  12654. }
  12655. virtual bool needsAllocator() const { return true; }
  12656. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12657. {
  12658. eof = false;
  12659. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12660. int iterations = (int) helper.numIterations();
  12661. maxIterations = (iterations >= 0) ? iterations : 0;
  12662. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12663. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12664. finishedLooping = true;
  12665. loopExtractBuilder.clear();
  12666. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12667. }
  12668. virtual void stop(bool aborting)
  12669. {
  12670. CRoxieServerActivity::stop(aborting);
  12671. loopExtractBuilder.clear();
  12672. }
  12673. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12674. {
  12675. if (flags & IHThorLoopArg::LFcounter)
  12676. {
  12677. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12678. *((thor_loop_counter_t *)counterRow) = counter;
  12679. RtlLinkedDatasetBuilder builder(rowAllocator);
  12680. builder.appendOwn(counterRow);
  12681. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12682. graph->setInputResult(2, counterResult);
  12683. }
  12684. }
  12685. };
  12686. //=================================================================================
  12687. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12688. {
  12689. Owned<IActivityGraph> loopQuery;
  12690. Owned<IRoxieServerChildGraph> loopGraph;
  12691. IRoxieInput * curInput;
  12692. RtlLinkedDatasetBuilder *loopInputBuilder;
  12693. CPointerArrayRoxieInput arrayInput;
  12694. Linked<IRoxieInput> resultInput;
  12695. unsigned loopCounter;
  12696. public:
  12697. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12698. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12699. {
  12700. curInput = NULL;
  12701. loopCounter = 0;
  12702. loopInputBuilder = NULL;
  12703. }
  12704. virtual bool needsAllocator() const { return true; }
  12705. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12706. {
  12707. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12708. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12709. }
  12710. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12711. {
  12712. curInput = input;
  12713. loopCounter = 1;
  12714. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12715. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12716. loopGraph.set(loopQuery->queryLoopGraph());
  12717. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12718. }
  12719. virtual void stop(bool aborting)
  12720. {
  12721. delete loopInputBuilder;
  12722. loopInputBuilder = NULL;
  12723. CRoxieServerLoopActivity::stop(aborting);
  12724. }
  12725. virtual const void * nextInGroup()
  12726. {
  12727. ActivityTimer t(totalCycles, timeActivities);
  12728. if (eof)
  12729. return NULL;
  12730. unsigned emptyIterations = 0;
  12731. loop
  12732. {
  12733. loop
  12734. {
  12735. const void * ret = curInput->nextInGroup();
  12736. if (!ret)
  12737. {
  12738. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12739. if (!ret)
  12740. {
  12741. if (finishedLooping)
  12742. {
  12743. eof = true;
  12744. return NULL;
  12745. }
  12746. break;
  12747. }
  12748. }
  12749. if (finishedLooping ||
  12750. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12751. {
  12752. processed++;
  12753. return ret;
  12754. }
  12755. loopInputBuilder->appendOwn(ret);
  12756. }
  12757. switch (activityKind)
  12758. {
  12759. case TAKloopdataset:
  12760. {
  12761. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12762. {
  12763. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12764. {
  12765. if (loopInputBuilder->getcount() == 0)
  12766. {
  12767. eof = true;
  12768. return NULL;
  12769. }
  12770. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12771. // MORE - should builder be cleared here?
  12772. curInput = &arrayInput;
  12773. finishedLooping = true;
  12774. continue; // back to the input loop again
  12775. }
  12776. }
  12777. break;
  12778. }
  12779. case TAKlooprow:
  12780. if (!loopInputBuilder->getcount())
  12781. {
  12782. finishedLooping = true;
  12783. eof = true;
  12784. return NULL;
  12785. }
  12786. break;
  12787. }
  12788. if (loopInputBuilder->getcount())
  12789. emptyIterations = 0;
  12790. else
  12791. {
  12792. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12793. emptyIterations++;
  12794. if (emptyIterations > maxEmptyLoopIterations)
  12795. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12796. if (emptyIterations % 32 == 0)
  12797. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12798. }
  12799. checkAbort();
  12800. try
  12801. {
  12802. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12803. resultInput.setown(results->createIterator(0));
  12804. if (flags & IHThorLoopArg::LFnewloopagain)
  12805. {
  12806. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12807. OwnedConstRoxieRow row = againResult->nextInGroup();
  12808. assertex(row);
  12809. //Result is a row which contains a single boolean field.
  12810. if (!((const bool *)row.get())[0])
  12811. finishedLooping = true;
  12812. }
  12813. }
  12814. catch (IException *E)
  12815. {
  12816. throw makeWrappedException(E);
  12817. }
  12818. curInput = resultInput.get();
  12819. loopCounter++;
  12820. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12821. finishedLooping = true;
  12822. }
  12823. }
  12824. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12825. {
  12826. try
  12827. {
  12828. loopGraph->beforeExecute();
  12829. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12830. loopInputBuilder->clear();
  12831. loopGraph->setInputResult(1, inputRowsResult);
  12832. createCounterResult(loopGraph, counter);
  12833. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12834. loopGraph->afterExecute();
  12835. return ret.getClear();
  12836. }
  12837. catch (...)
  12838. {
  12839. CTXLOG("Exception thrown in loop body - cleaning up");
  12840. loopGraph->afterExecute();
  12841. throw;
  12842. }
  12843. }
  12844. };
  12845. //=================================================================================
  12846. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12847. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12848. {
  12849. public:
  12850. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12851. input(_input)
  12852. {
  12853. eof = false;
  12854. }
  12855. virtual const void * nextInGroup()
  12856. {
  12857. if (eof)
  12858. return NULL;
  12859. const void * ret = input.dequeue();
  12860. if (!ret)
  12861. eof = true;
  12862. return ret;
  12863. }
  12864. protected:
  12865. SafeRowQueue & input;
  12866. bool eof;
  12867. };
  12868. class CRoxieServerParallelLoopActivity;
  12869. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12870. {
  12871. public:
  12872. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12873. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12874. {
  12875. }
  12876. virtual const void * nextInGroup();
  12877. protected:
  12878. CRoxieServerParallelLoopActivity * activity;
  12879. unsigned counter;
  12880. };
  12881. class LoopExecutorThread : public RestartableThread
  12882. {
  12883. protected:
  12884. Owned<IRoxieInput> safeInput;
  12885. CRoxieServerParallelLoopActivity * activity;
  12886. bool eof;
  12887. CriticalSection crit;
  12888. unsigned flags;
  12889. SafeRowQueue tempResults[2];
  12890. unsigned savedParentExtractSize;
  12891. const byte * savedParentExtract;
  12892. IArrayOf<IActivityGraph> cachedGraphs;
  12893. IRoxieSlaveContext *ctx;
  12894. public:
  12895. LoopExecutorThread()
  12896. : RestartableThread("LoopExecutorThread")
  12897. {
  12898. activity = NULL;
  12899. eof = false;
  12900. flags = 0;
  12901. ctx = NULL;
  12902. savedParentExtract = NULL;
  12903. savedParentExtractSize = 0;
  12904. }
  12905. virtual IRoxieInput *queryInput(unsigned idx) const
  12906. {
  12907. return safeInput->queryInput(idx);
  12908. }
  12909. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12910. {
  12911. activity = _activity;
  12912. flags = _flags;
  12913. // 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-nextInGroup etc etc.
  12914. safeInput.setown(new CSafeRoxieInput(_input));
  12915. }
  12916. IRoxieInput *queryInput() const
  12917. {
  12918. return safeInput;
  12919. }
  12920. void onCreate(IRoxieSlaveContext * _ctx);
  12921. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12922. void stop(bool aborting);
  12923. void reset();
  12924. virtual int run();
  12925. protected:
  12926. void executeLoop();
  12927. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12928. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12929. };
  12930. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12931. {
  12932. friend class LoopFilterPseudoInput;
  12933. friend class LoopExecutorThread;
  12934. QueueOf<const void, true> ready;
  12935. CriticalSection helperCS;
  12936. CriticalSection cs;
  12937. size32_t sizeNumParallel;
  12938. rtlDataAttr listNumParallel;
  12939. unsigned defaultNumParallel;
  12940. LoopExecutorThread executor;
  12941. IProbeManager* probeManager;
  12942. CriticalSection canAccess;
  12943. CriticalSection scrit;
  12944. InterruptableSemaphore readySpace;
  12945. InterruptableSemaphore recordsReady;
  12946. protected:
  12947. bool includeInLoop(unsigned counter, const void * row)
  12948. {
  12949. CriticalBlock b(helperCS);
  12950. return helper.sendToLoop(counter, row);
  12951. }
  12952. public:
  12953. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12954. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12955. readySpace(parallelLoopFlowLimit)
  12956. {
  12957. probeManager = _probeManager;
  12958. defaultNumParallel = 0;
  12959. sizeNumParallel = 0;
  12960. }
  12961. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12962. {
  12963. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12964. executor.onCreate(_ctx);
  12965. }
  12966. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12967. {
  12968. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12969. readySpace.reinit(parallelLoopFlowLimit);
  12970. recordsReady.reinit();
  12971. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12972. defaultNumParallel = helper.defaultParallelIterations();
  12973. if (!defaultNumParallel)
  12974. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12975. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12976. //MORE: If numIterations <= number of parallel iterations[1],
  12977. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12978. //being transferred via a queue
  12979. executor.start(parentExtractSize, parentExtract, paused);
  12980. }
  12981. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12982. {
  12983. if (idx)
  12984. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12985. executor.setInput(this, _in, flags);
  12986. }
  12987. virtual void stop(bool aborting)
  12988. {
  12989. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12990. readySpace.interrupt();
  12991. recordsReady.interrupt();
  12992. executor.join(); // MORE - may not be needed given stop/reset split
  12993. CRoxieServerLoopActivity::stop(aborting);
  12994. }
  12995. virtual void reset()
  12996. {
  12997. while (ready.ordinality())
  12998. ReleaseRoxieRow(ready.dequeue());
  12999. executor.reset();
  13000. CRoxieServerActivity::reset();
  13001. }
  13002. virtual const void * nextInGroup()
  13003. {
  13004. ActivityTimer t(totalCycles, timeActivities);
  13005. loop
  13006. {
  13007. if (eof)
  13008. return NULL;
  13009. recordsReady.wait();
  13010. CriticalBlock procedure(canAccess);
  13011. if (ready.ordinality())
  13012. {
  13013. const void *result = ready.dequeue();
  13014. readySpace.signal();
  13015. if (result)
  13016. processed++;
  13017. return result;
  13018. }
  13019. else
  13020. eof = true;
  13021. }
  13022. }
  13023. unsigned getNumParallel(unsigned iter)
  13024. {
  13025. if (iter * sizeof(unsigned) >= sizeNumParallel)
  13026. return defaultNumParallel;
  13027. return ((unsigned *)listNumParallel.getdata())[iter];
  13028. }
  13029. inline void enqueueResult(const void * row)
  13030. {
  13031. try
  13032. {
  13033. while(!readySpace.wait(1000))
  13034. {
  13035. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13036. }
  13037. }
  13038. catch (...)
  13039. {
  13040. ReleaseRoxieRow(row);
  13041. throw;
  13042. }
  13043. CriticalBlock b2(canAccess);
  13044. ready.enqueue(row);
  13045. recordsReady.signal();
  13046. }
  13047. inline void finishResults()
  13048. {
  13049. recordsReady.signal();
  13050. }
  13051. virtual bool fireException(IException *e)
  13052. {
  13053. readySpace.interrupt(LINK(e));
  13054. recordsReady.interrupt(e);
  13055. return true;
  13056. }
  13057. IActivityGraph * createChildGraphInstance()
  13058. {
  13059. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13060. }
  13061. IActivityGraph * queryChildGraph()
  13062. {
  13063. return ctx->queryChildGraph(loopGraphId);
  13064. }
  13065. };
  13066. //=================================================================================
  13067. const void * LoopFilterPseudoInput::nextInGroup()
  13068. {
  13069. loop
  13070. {
  13071. const void * next = input->nextInGroup();
  13072. if (!next || activity->includeInLoop(counter, next))
  13073. return next;
  13074. activity->enqueueResult(next);
  13075. }
  13076. }
  13077. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13078. {
  13079. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13080. ctx = _ctx;
  13081. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13082. }
  13083. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13084. {
  13085. savedParentExtractSize = parentExtractSize;
  13086. savedParentExtract = parentExtract;
  13087. eof = false;
  13088. StringBuffer logPrefix("[");
  13089. ctx->getLogPrefix(logPrefix).append("] ");
  13090. RestartableThread::start(logPrefix);
  13091. }
  13092. int LoopExecutorThread::run()
  13093. {
  13094. try
  13095. {
  13096. executeLoop();
  13097. }
  13098. catch (IException *e)
  13099. {
  13100. activity->fireException(e);
  13101. }
  13102. catch (...)
  13103. {
  13104. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13105. }
  13106. return 0;
  13107. }
  13108. void LoopExecutorThread::stop(bool aborting)
  13109. {
  13110. safeInput->stop(aborting);
  13111. RestartableThread::join();
  13112. }
  13113. void LoopExecutorThread::reset()
  13114. {
  13115. safeInput->reset();
  13116. }
  13117. void LoopExecutorThread::executeLoop()
  13118. {
  13119. unsigned iterations = 0;
  13120. unsigned counter = 0;
  13121. unsigned outputIndex = 0;
  13122. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13123. loop
  13124. {
  13125. if (activity->activityKind == TAKloopcount)
  13126. {
  13127. if (counter == activity->maxIterations)
  13128. break;
  13129. }
  13130. else
  13131. {
  13132. //This condition isn't quite right because it needs to be whether the filtered
  13133. //input is empty. May be ok if we include that in the semantics,
  13134. if (tempResults[1-outputIndex].ordinality() == 0)
  13135. break;
  13136. }
  13137. unsigned numParallel = activity->getNumParallel(iterations);
  13138. Linked<IRoxieInput> curInput;
  13139. if (iterations == 0)
  13140. curInput.set(safeInput);
  13141. else
  13142. {
  13143. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13144. inputQueue.enqueue(NULL);
  13145. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  13146. }
  13147. SafeRowQueue * curOutput = NULL;
  13148. if (counter+numParallel > activity->maxIterations)
  13149. numParallel = activity->maxIterations - counter;
  13150. else if (counter+numParallel < activity->maxIterations)
  13151. curOutput = &tempResults[outputIndex];
  13152. executeLoopInstance(counter, numParallel, curInput, curOutput);
  13153. outputIndex = 1-outputIndex;
  13154. counter += numParallel;
  13155. iterations++;
  13156. }
  13157. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13158. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13159. while (inputQueue.ordinality())
  13160. {
  13161. const void * next = inputQueue.dequeue();
  13162. activity->enqueueResult(next);
  13163. }
  13164. activity->finishResults();
  13165. }
  13166. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  13167. {
  13168. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13169. Linked<IRoxieInput> curInput = input;
  13170. unsigned i;
  13171. for (i= 0; i != numIterations; i++)
  13172. {
  13173. unsigned thisCounter = counter+i+1;
  13174. IRoxieInput * filtered = curInput;
  13175. if (flags & IHThorLoopArg::LFfiltered)
  13176. {
  13177. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  13178. savedInputs.append(*filtered);
  13179. }
  13180. //graph is kept, so new curInput will be guaranteed to exist
  13181. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  13182. }
  13183. try
  13184. {
  13185. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13186. if (spillOutput)
  13187. {
  13188. loop
  13189. {
  13190. const void * next = curInput->nextInGroup();
  13191. if (!next)
  13192. break;
  13193. spillOutput->enqueue(next);
  13194. }
  13195. }
  13196. else
  13197. {
  13198. loop
  13199. {
  13200. const void * next = curInput->nextInGroup();
  13201. if (!next)
  13202. break;
  13203. activity->enqueueResult(next);
  13204. }
  13205. }
  13206. }
  13207. catch (IException *E)
  13208. {
  13209. ctx->notifyAbort(E);
  13210. for (i= 0; i != numIterations; i++)
  13211. {
  13212. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13213. }
  13214. curInput->stop(true);
  13215. curInput->reset();
  13216. throw;
  13217. }
  13218. for (i= 0; i != numIterations; i++)
  13219. {
  13220. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13221. }
  13222. curInput->stop(false);
  13223. curInput->reset();
  13224. }
  13225. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  13226. {
  13227. if (!cachedGraphs.isItem(i))
  13228. cachedGraphs.append(*activity->createChildGraphInstance());
  13229. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13230. loopGraph->beforeExecute();
  13231. if (!loopGraph->querySetInputResult(1, input))
  13232. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13233. activity->createCounterResult(loopGraph, counter);
  13234. return loopGraph->selectOutput(0);
  13235. }
  13236. //=================================================================================
  13237. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  13238. {
  13239. public:
  13240. IMPLEMENT_IINTERFACE
  13241. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13242. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13243. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13244. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13245. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13246. virtual unsigned getMetaFlags() { return 0; }
  13247. virtual void destruct(byte * self) {}
  13248. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13249. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13250. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13251. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13252. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13253. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13254. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13255. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13256. };
  13257. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13258. {
  13259. unsigned loopGraphId;
  13260. unsigned flags;
  13261. Linked<IOutputMetaData> counterMeta;
  13262. public:
  13263. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13264. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13265. {
  13266. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13267. flags = helper->getFlags();
  13268. counterMeta.setown(new CCounterRowMetaData);
  13269. }
  13270. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13271. {
  13272. if (flags & IHThorLoopArg::LFparallel)
  13273. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13274. else
  13275. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13276. }
  13277. };
  13278. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13279. {
  13280. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13281. }
  13282. //=================================================================================
  13283. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13284. {
  13285. protected:
  13286. IHThorGraphLoopArg &helper;
  13287. unsigned maxIterations;
  13288. unsigned flags;
  13289. rtlRowBuilder GraphExtractBuilder;
  13290. unsigned loopGraphId;
  13291. Linked<IOutputMetaData> counterMeta;
  13292. public:
  13293. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13294. : CRoxieServerActivity(_factory, _probeManager),
  13295. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13296. {
  13297. flags = helper.getFlags();
  13298. maxIterations = 0;
  13299. }
  13300. virtual bool needsAllocator() const { return true; }
  13301. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13302. {
  13303. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13304. int iterations = (int) helper.numIterations();
  13305. maxIterations = (iterations >= 0) ? iterations : 0;
  13306. if (maxIterations > maxGraphLoopIterations)
  13307. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13308. if (maxIterations != 0)
  13309. {
  13310. GraphExtractBuilder.clear();
  13311. helper.createParentExtract(GraphExtractBuilder);
  13312. }
  13313. }
  13314. virtual void stop(bool aborting)
  13315. {
  13316. CRoxieServerActivity::stop(aborting);
  13317. GraphExtractBuilder.clear();
  13318. }
  13319. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13320. {
  13321. if (flags & IHThorGraphLoopArg::GLFcounter)
  13322. {
  13323. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13324. *((thor_loop_counter_t *)counterRow) = counter;
  13325. RtlLinkedDatasetBuilder builder(rowAllocator);
  13326. builder.appendOwn(counterRow);
  13327. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13328. graph->setInputResult(0, counterResult);
  13329. }
  13330. }
  13331. };
  13332. //=================================================================================
  13333. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13334. {
  13335. Owned<IActivityGraph> GraphQuery;
  13336. Owned<IRoxieServerChildGraph> loopGraph;
  13337. Linked<IRoxieInput> resultInput;
  13338. bool evaluated;
  13339. public:
  13340. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13341. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13342. {
  13343. evaluated = false;
  13344. }
  13345. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13346. {
  13347. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13348. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13349. }
  13350. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13351. {
  13352. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13353. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13354. loopGraph.set(GraphQuery->queryLoopGraph());
  13355. evaluated = false;
  13356. }
  13357. virtual void stop(bool aborting)
  13358. {
  13359. if (loopGraph)
  13360. loopGraph->clearGraphLoopResults();
  13361. CRoxieServerGraphLoopActivity::stop(aborting);
  13362. }
  13363. virtual const void * nextInGroup()
  13364. {
  13365. ActivityTimer t(totalCycles, timeActivities);
  13366. if (!evaluated)
  13367. {
  13368. executeEntireGraph();
  13369. evaluated = true;
  13370. }
  13371. const void * ret = resultInput->nextInGroup();
  13372. if (ret)
  13373. processed++;
  13374. return ret;
  13375. }
  13376. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13377. {
  13378. try
  13379. {
  13380. loopGraph->beforeExecute();
  13381. createCounterResult(loopGraph, counter);
  13382. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13383. loopGraph->afterExecute();
  13384. }
  13385. catch (...)
  13386. {
  13387. CTXLOG("Exception thrown in graph body - cleaning up");
  13388. loopGraph->afterExecute();
  13389. throw;
  13390. }
  13391. }
  13392. void createInitialGraphInput()
  13393. {
  13394. loopGraph->clearGraphLoopResults();
  13395. RtlLinkedDatasetBuilder builder(rowAllocator);
  13396. input->readAll(builder);
  13397. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13398. loopGraph->setGraphLoopResult(0, result);
  13399. }
  13400. void executeEntireGraph()
  13401. {
  13402. createInitialGraphInput();
  13403. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13404. {
  13405. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13406. }
  13407. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13408. }
  13409. };
  13410. //=================================================================================
  13411. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13412. {
  13413. public:
  13414. virtual unsigned numBranches()
  13415. {
  13416. return 0;
  13417. }
  13418. virtual IOutputMetaData * queryOutputMeta()
  13419. {
  13420. return NULL;// get it from the parent..
  13421. }
  13422. };
  13423. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13424. class CGraphIterationInfo : public CInterface
  13425. {
  13426. private:
  13427. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13428. unsigned sourceIdx;
  13429. Linked<IRoxieServerActivity> sourceAct;
  13430. Linked<IRoxieInput> sourceInput;
  13431. unsigned numUses;
  13432. unsigned iteration;
  13433. public:
  13434. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13435. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13436. {
  13437. numUses = 0;
  13438. }
  13439. inline void noteUsed()
  13440. {
  13441. numUses++;
  13442. }
  13443. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13444. {
  13445. if (numUses > 1)
  13446. {
  13447. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13448. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13449. splitter->onCreate(ctx, NULL);
  13450. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13451. if (probeManager)
  13452. {
  13453. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13454. input = static_cast<IRoxieInput*>(inputBase);
  13455. // MORE - shouldn't this be added to probes?
  13456. }
  13457. sourceAct.setown(splitter);
  13458. sourceAct->setInput(0, input);
  13459. sourceIdx = 0;
  13460. sourceInput.clear();
  13461. }
  13462. }
  13463. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13464. {
  13465. // MORE - not really necessary to create splitters in separate pass, is it?
  13466. if (factory) // we created a splitter....
  13467. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13468. IRoxieInput *ret = sourceInput;
  13469. if (probeManager)
  13470. {
  13471. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13472. ret = static_cast<IRoxieInput *>(inputBase);
  13473. probes.append(*LINK(ret));
  13474. }
  13475. if (factory) // we created a splitter....
  13476. sourceIdx++;
  13477. return ret;
  13478. }
  13479. };
  13480. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13481. {
  13482. Owned<IActivityGraph> childGraph;
  13483. IRoxieInput * resultInput;
  13484. CIArrayOf<CGraphIterationInfo> outputs;
  13485. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13486. Owned<CExtractMapperInput> inputExtractMapper;
  13487. IProbeManager *probeManager;
  13488. unsigned createLoopCounter;
  13489. IArrayOf<IRoxieInput> probes;
  13490. public:
  13491. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13492. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13493. {
  13494. inputExtractMapper.setown(new CExtractMapperInput);
  13495. resultInput = NULL;
  13496. createLoopCounter = 0;
  13497. }
  13498. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13499. {
  13500. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13501. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13502. }
  13503. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13504. {
  13505. //Input needs to be handled very carefully.....
  13506. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13507. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13508. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13509. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13510. assertex(idx == 0);
  13511. inputExtractMapper->setInput(_in);
  13512. }
  13513. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13514. {
  13515. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13516. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13517. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13518. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13519. }
  13520. virtual void stop(bool aborting)
  13521. {
  13522. if (resultInput)
  13523. resultInput->stop(aborting);
  13524. CRoxieServerGraphLoopActivity::stop(aborting);
  13525. }
  13526. virtual void reset()
  13527. {
  13528. if (resultInput)
  13529. resultInput->reset();
  13530. resultInput = NULL;
  13531. outputs.kill();
  13532. iterationGraphs.kill(); // must be done after all activities killed
  13533. if (probeManager)
  13534. {
  13535. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13536. probes.kill();
  13537. }
  13538. CRoxieServerGraphLoopActivity::reset();
  13539. }
  13540. virtual const void * nextInGroup()
  13541. {
  13542. ActivityTimer t(totalCycles, timeActivities);
  13543. const void * ret = resultInput->nextInGroup();
  13544. if (ret)
  13545. processed++;
  13546. return ret;
  13547. }
  13548. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13549. {
  13550. //result(0) is the input to the graph.
  13551. resultInput = inputExtractMapper;
  13552. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13553. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13554. {
  13555. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13556. graph->beforeExecute();
  13557. iterationGraphs.append(*graph);
  13558. graph->gatherIterationUsage(*this);
  13559. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13560. outputs.append(*iteration);
  13561. }
  13562. createLoopCounter = 0;
  13563. createSplitters(probeManager);
  13564. ForEachItemIn(i2, iterationGraphs)
  13565. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13566. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13567. }
  13568. void createSplitters(IProbeManager *probeManager)
  13569. {
  13570. ForEachItemIn(i, outputs)
  13571. {
  13572. CGraphIterationInfo & next = outputs.item(i);
  13573. next.createSplitter(ctx, probeManager);
  13574. }
  13575. }
  13576. //IRoxieServerLoopResultProcessor
  13577. virtual void noteUseIteration(unsigned _whichIteration)
  13578. {
  13579. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13580. if (whichIteration >= 0)
  13581. {
  13582. if (!outputs.isItem(whichIteration))
  13583. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13584. outputs.item(whichIteration).noteUsed();
  13585. }
  13586. }
  13587. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13588. {
  13589. if (outputs.isItem(whichIteration))
  13590. {
  13591. CGraphIterationInfo & next = outputs.item(whichIteration);
  13592. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13593. }
  13594. return NULL;
  13595. }
  13596. };
  13597. //=================================================================================
  13598. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13599. {
  13600. unsigned loopGraphId;
  13601. unsigned flags;
  13602. Linked<IOutputMetaData> counterMeta;
  13603. public:
  13604. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13605. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13606. {
  13607. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13608. flags = helper->getFlags();
  13609. counterMeta.setown(new CCounterRowMetaData);
  13610. }
  13611. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13612. {
  13613. if (kind == TAKparallelgraphloop)
  13614. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13615. else
  13616. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13617. }
  13618. };
  13619. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13620. {
  13621. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13622. }
  13623. //=====================================================================================================
  13624. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13625. {
  13626. class OutputAdaptor : public CExtractMapperInput
  13627. {
  13628. bool stopped;
  13629. public:
  13630. CRoxieServerLibraryCallActivity *parent;
  13631. unsigned oid;
  13632. unsigned processed;
  13633. public:
  13634. IMPLEMENT_IINTERFACE;
  13635. OutputAdaptor() : CExtractMapperInput(NULL)
  13636. {
  13637. parent = NULL;
  13638. oid = 0;
  13639. init();
  13640. }
  13641. ~OutputAdaptor()
  13642. {
  13643. if (traceStartStop)
  13644. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  13645. if (processed && parent && parent->factory)
  13646. {
  13647. parent->factory->noteProcessed(oid, processed);
  13648. if (parent->ctx)
  13649. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  13650. }
  13651. }
  13652. void init()
  13653. {
  13654. processed = 0;
  13655. stopped = false;
  13656. }
  13657. virtual unsigned queryId() const
  13658. {
  13659. return parent->queryId();
  13660. }
  13661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13662. {
  13663. parent->start(oid, parentExtractSize, parentExtract, paused);
  13664. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13665. }
  13666. virtual void stop(bool aborting)
  13667. {
  13668. if (!stopped)
  13669. {
  13670. stopped = true;
  13671. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13672. CExtractMapperInput::stop(aborting);
  13673. }
  13674. };
  13675. virtual void reset()
  13676. {
  13677. parent->reset(oid);
  13678. CExtractMapperInput::reset();
  13679. init();
  13680. };
  13681. virtual void checkAbort()
  13682. {
  13683. parent->checkAbort();
  13684. }
  13685. };
  13686. IHThorLibraryCallArg &helper;
  13687. unsigned numInputs;
  13688. unsigned numOutputs;
  13689. unsigned numActiveOutputs;
  13690. bool started;
  13691. OutputAdaptor* outputAdaptors;
  13692. CExtractMapperInput * * inputAdaptors;
  13693. bool * inputUsed;
  13694. bool * outputUsed;
  13695. Owned<IException> error;
  13696. CriticalSection crit;
  13697. rtlRowBuilder libraryExtractBuilder;
  13698. Owned<IActivityGraph> libraryGraph;
  13699. const LibraryCallFactoryExtra & extra;
  13700. public:
  13701. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13702. : CRoxieServerActivity(_factory, _probeManager),
  13703. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13704. {
  13705. numInputs = _numInputs;
  13706. numOutputs = _numOutputs;
  13707. numActiveOutputs = numOutputs;
  13708. inputAdaptors = new CExtractMapperInput*[numInputs];
  13709. inputUsed = new bool[numInputs];
  13710. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13711. {
  13712. inputAdaptors[i1] = new CExtractMapperInput;
  13713. inputUsed[i1] = false;
  13714. }
  13715. outputAdaptors = new OutputAdaptor[numOutputs];
  13716. outputUsed = new bool[numOutputs];
  13717. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13718. {
  13719. outputAdaptors[i2].parent = this;
  13720. outputAdaptors[i2].oid = i2;
  13721. outputUsed[i2] = false;
  13722. }
  13723. started = false;
  13724. }
  13725. ~CRoxieServerLibraryCallActivity()
  13726. {
  13727. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13728. ::Release(inputAdaptors[i1]);
  13729. delete [] inputAdaptors;
  13730. delete [] inputUsed;
  13731. delete [] outputAdaptors;
  13732. delete [] outputUsed;
  13733. }
  13734. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13735. {
  13736. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13737. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13738. libraryGraph->onCreate(_ctx, _colocalParent);
  13739. //Now map the inputs and outputs to the adapters
  13740. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13741. for (unsigned i1=0; i1<numInputs; i1++)
  13742. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13743. for (unsigned i2=0; i2<numOutputs; i2++)
  13744. {
  13745. unsigned outputIndex = extra.outputs.item(i2);
  13746. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13747. outputAdaptors[i2].setInput(output);
  13748. }
  13749. }
  13750. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13751. {
  13752. CriticalBlock b(crit);
  13753. if (error)
  13754. throw error.getLink();
  13755. if (factory)
  13756. factory->noteStarted(oid);
  13757. if (!started)
  13758. {
  13759. // even though it is not complete, we don't want to run this again if it fails.
  13760. started = true;
  13761. //see notes on splitter above
  13762. try
  13763. {
  13764. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13765. }
  13766. catch (IException *E)
  13767. {
  13768. #ifdef TRACE_SPLIT
  13769. CTXLOG("spill %d caught exception in start", activityId);
  13770. #endif
  13771. error.set(E);
  13772. throw;
  13773. }
  13774. catch (...)
  13775. {
  13776. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13777. error.set(E);
  13778. throw E;
  13779. }
  13780. //recreate the parent extract, and use it to reinitialize the graphs...
  13781. libraryExtractBuilder.clear();
  13782. helper.createParentExtract(libraryExtractBuilder);
  13783. // 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
  13784. // some inputs before we see start on others.
  13785. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13786. {
  13787. if (inputUsed[i1])
  13788. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13789. else
  13790. inputAdaptors[i1]->stop(false);
  13791. }
  13792. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13793. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13794. //call stop on all the unused inputs.
  13795. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13796. graph->beforeExecute();
  13797. ForEachItemIn(i3, extra.unusedOutputs)
  13798. {
  13799. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13800. output->stop(false);
  13801. }
  13802. }
  13803. }
  13804. virtual void stop(unsigned oid, bool aborting)
  13805. {
  13806. CriticalBlock b(crit);
  13807. if (--numActiveOutputs == 0)
  13808. {
  13809. //call stop on all the unused inputs.
  13810. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13811. graph->beforeExecute();
  13812. ForEachItemIn(i3, extra.unusedOutputs)
  13813. {
  13814. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13815. output->stop(false);
  13816. }
  13817. CRoxieServerActivity::stop(aborting);
  13818. }
  13819. }
  13820. void reset(unsigned oid)
  13821. {
  13822. started = false;
  13823. error.clear();
  13824. numActiveOutputs = numOutputs;
  13825. if (state != STATEreset) // make sure input is only reset once
  13826. {
  13827. CRoxieServerActivity::reset();
  13828. libraryGraph->reset();
  13829. //Call reset on all unused inputs/outputs from the graph - no one else will.
  13830. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13831. {
  13832. if (!inputUsed[i1])
  13833. inputAdaptors[i1]->reset();
  13834. }
  13835. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13836. ForEachItemIn(i3, extra.unusedOutputs)
  13837. {
  13838. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13839. output->reset();
  13840. }
  13841. }
  13842. };
  13843. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13844. {
  13845. inputAdaptors[idx]->setInput(_in);
  13846. }
  13847. public:
  13848. virtual const void *nextInGroup()
  13849. {
  13850. throwUnexpected(); // Internal logic error - we are not anybody's input
  13851. }
  13852. virtual IOutputMetaData * queryOutputMeta() const
  13853. {
  13854. throwUnexpected(); // should be called on outputs instead
  13855. }
  13856. virtual IRoxieInput *queryOutput(unsigned idx)
  13857. {
  13858. assertex(idx!=(unsigned)-1);
  13859. assertex(!outputUsed[idx]);
  13860. outputUsed[idx] = true;
  13861. return &outputAdaptors[idx];
  13862. }
  13863. };
  13864. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13865. {
  13866. ForEachItemIn(i1, _other.outputs)
  13867. outputs.append(_other.outputs.item(i1));
  13868. ForEachItemIn(i2, _other.unusedOutputs)
  13869. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13870. maxOutputs = _other.maxOutputs;
  13871. graphid = _other.graphid;
  13872. libraryName.set(_other.libraryName);
  13873. embeddedGraphName.set(_other.embeddedGraphName);
  13874. interfaceHash = _other.interfaceHash;
  13875. embedded = _other.embedded;
  13876. }
  13877. void LibraryCallFactoryExtra::calcUnused()
  13878. {
  13879. for (unsigned i=0; i < maxOutputs; i++)
  13880. if (!outputs.contains(i))
  13881. unusedOutputs.append(i);
  13882. }
  13883. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13884. {
  13885. private:
  13886. CRoxieServerMultiInputInfo inputs;
  13887. LibraryCallFactoryExtra extra;
  13888. public:
  13889. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13890. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13891. {
  13892. extra.set(_extra);
  13893. extra.calcUnused();
  13894. setNumOutputs(extra.outputs.ordinality());
  13895. }
  13896. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13897. {
  13898. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13899. }
  13900. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13901. {
  13902. inputs.set(idx, source, sourceidx);
  13903. }
  13904. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13905. {
  13906. return inputs.get(idx, sourceidx);
  13907. }
  13908. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13909. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13910. {
  13911. addXrefLibraryInfo(reply, extra.libraryName);
  13912. }
  13913. };
  13914. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13915. {
  13916. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13917. }
  13918. //=====================================================================================================
  13919. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13920. {
  13921. IHThorNWayInputArg & helper;
  13922. IRoxieInput ** inputs;
  13923. PointerArrayOf<IRoxieInput> selectedInputs;
  13924. unsigned numInputs;
  13925. public:
  13926. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13927. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13928. {
  13929. inputs = new IRoxieInput*[numInputs];
  13930. for (unsigned i = 0; i < numInputs; i++)
  13931. inputs[i] = NULL;
  13932. }
  13933. ~CRoxieServerNWayInputActivity()
  13934. {
  13935. delete [] inputs;
  13936. }
  13937. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13938. {
  13939. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13940. bool selectionIsAll;
  13941. size32_t selectionLen;
  13942. rtlDataAttr selection;
  13943. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13944. selectedInputs.kill();
  13945. if (selectionIsAll)
  13946. {
  13947. for (unsigned i=0; i < numInputs; i++)
  13948. selectedInputs.append(inputs[i]);
  13949. }
  13950. else
  13951. {
  13952. const size32_t * selections = (const size32_t *)selection.getdata();
  13953. unsigned max = selectionLen/sizeof(size32_t);
  13954. for (unsigned i = 0; i < max; i++)
  13955. {
  13956. unsigned nextIndex = selections[i];
  13957. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13958. for (unsigned j=i+1; j < max; j++)
  13959. {
  13960. if (nextIndex == selections[j])
  13961. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13962. }
  13963. if (nextIndex > numInputs)
  13964. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13965. selectedInputs.append(inputs[nextIndex-1]);
  13966. }
  13967. }
  13968. ForEachItemIn(i2, selectedInputs)
  13969. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13970. }
  13971. virtual void stop(bool aborting)
  13972. {
  13973. ForEachItemIn(i2, selectedInputs)
  13974. selectedInputs.item(i2)->stop(aborting);
  13975. CRoxieServerActivity::stop(aborting);
  13976. }
  13977. virtual unsigned __int64 queryLocalCycles() const
  13978. {
  13979. __int64 localCycles = totalCycles.totalCycles;
  13980. ForEachItemIn(i, selectedInputs)
  13981. {
  13982. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13983. }
  13984. if (localCycles < 0)
  13985. localCycles = 0;
  13986. return localCycles;
  13987. }
  13988. virtual IRoxieInput *queryInput(unsigned idx) const
  13989. {
  13990. if (selectedInputs.isItem(idx))
  13991. return selectedInputs.item(idx);
  13992. else
  13993. return NULL;
  13994. }
  13995. virtual void reset()
  13996. {
  13997. ForEachItemIn(i, selectedInputs)
  13998. selectedInputs.item(i)->reset();
  13999. selectedInputs.kill();
  14000. CRoxieServerActivity::reset();
  14001. }
  14002. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14003. {
  14004. assertex(idx < numInputs);
  14005. inputs[idx] = _in;
  14006. }
  14007. virtual const void * nextInGroup()
  14008. {
  14009. throwUnexpected();
  14010. }
  14011. virtual unsigned numConcreteOutputs() const
  14012. {
  14013. return selectedInputs.ordinality();
  14014. }
  14015. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  14016. {
  14017. if (selectedInputs.isItem(idx))
  14018. return selectedInputs.item(idx);
  14019. return NULL;
  14020. }
  14021. };
  14022. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14023. {
  14024. // bool ordered;
  14025. public:
  14026. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14027. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14028. {
  14029. }
  14030. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14031. {
  14032. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  14033. }
  14034. };
  14035. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14036. {
  14037. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14038. }
  14039. //=====================================================================================================
  14040. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  14041. {
  14042. IHThorNWayGraphLoopResultReadArg & helper;
  14043. CIArrayOf<CRoxieServerActivity> resultReaders;
  14044. PointerArrayOf<IRoxieInput> inputs;
  14045. unsigned graphId;
  14046. bool grouped;
  14047. bool selectionIsAll;
  14048. size32_t selectionLen;
  14049. rtlDataAttr selection;
  14050. public:
  14051. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14052. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14053. {
  14054. grouped = helper.isGrouped();
  14055. graphId = _graphId;
  14056. selectionIsAll = false;
  14057. selectionLen = 0;
  14058. }
  14059. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14060. {
  14061. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14062. if (inputs.ordinality() == 0)
  14063. {
  14064. initInputSelection();
  14065. unsigned max = selectionLen / sizeof(size32_t);
  14066. const size32_t * selections = (const size32_t *)selection.getdata();
  14067. IProbeManager * probeManager = NULL; // MORE!!
  14068. for (unsigned i = 0; i < max; i++)
  14069. {
  14070. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  14071. resultReaders.append(*resultInput);
  14072. inputs.append(resultInput->queryOutput(0));
  14073. resultInput->onCreate(ctx, colocalParent);
  14074. resultInput->start(parentExtractSize, parentExtract, paused);
  14075. }
  14076. }
  14077. else
  14078. {
  14079. ForEachItemIn(i, inputs)
  14080. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  14081. }
  14082. }
  14083. virtual void stop(bool aborting)
  14084. {
  14085. ForEachItemIn(i, inputs)
  14086. inputs.item(i)->stop(aborting);
  14087. CRoxieServerActivity::stop(aborting);
  14088. }
  14089. virtual void reset()
  14090. {
  14091. ForEachItemIn(i, inputs)
  14092. inputs.item(i)->reset();
  14093. inputs.kill();
  14094. resultReaders.kill();
  14095. CRoxieServerActivity::reset();
  14096. }
  14097. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14098. {
  14099. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  14100. }
  14101. virtual const void * nextInGroup()
  14102. {
  14103. throwUnexpected();
  14104. }
  14105. virtual unsigned numConcreteOutputs() const
  14106. {
  14107. return inputs.ordinality();
  14108. }
  14109. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  14110. {
  14111. if (inputs.isItem(idx))
  14112. return inputs.item(idx);
  14113. return NULL;
  14114. }
  14115. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14116. {
  14117. ensureCreated();
  14118. basehelper.onStart(parentExtract, NULL);
  14119. initInputSelection();
  14120. unsigned max = selectionLen / sizeof(size32_t);
  14121. const size32_t * selections = (const size32_t *)selection.getdata();
  14122. for (unsigned i = 0; i < max; i++)
  14123. processor.noteUseIteration(selections[i]);
  14124. }
  14125. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  14126. {
  14127. //selection etc. already initialised from the gratherIterationUsage() call.
  14128. unsigned max = selectionLen / sizeof(size32_t);
  14129. const size32_t * selections = (const size32_t *)selection.getdata();
  14130. for (unsigned i = 0; i < max; i++)
  14131. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  14132. }
  14133. protected:
  14134. void initInputSelection()
  14135. {
  14136. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14137. if (selectionIsAll)
  14138. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14139. }
  14140. };
  14141. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14142. {
  14143. unsigned graphId;
  14144. public:
  14145. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  14146. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  14147. {
  14148. }
  14149. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14150. {
  14151. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  14152. }
  14153. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14154. {
  14155. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14156. }
  14157. };
  14158. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  14159. {
  14160. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  14161. }
  14162. //=================================================================================
  14163. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  14164. {
  14165. public:
  14166. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  14167. IMPLEMENT_IINTERFACE
  14168. protected:
  14169. virtual const void * nextInputRow()
  14170. {
  14171. #ifdef TRACE_SEEK_REQUESTS
  14172. IRoxieContextLogger * logger = input->queryActivity();
  14173. const void * ret = doNextInputRow();
  14174. {
  14175. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14176. if (!ret)
  14177. xmlwrite.outputBool(true,"eof");
  14178. else if (input->queryOutputMeta()->hasXML())
  14179. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14180. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14181. }
  14182. return ret;
  14183. #else
  14184. return doNextInputRow();
  14185. #endif
  14186. }
  14187. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14188. {
  14189. #ifdef TRACE_SEEK_REQUESTS
  14190. IRoxieContextLogger * logger = input->queryActivity();
  14191. {
  14192. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14193. if (input->queryOutputMeta()->hasXML())
  14194. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14195. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14196. numFields,
  14197. stepExtra.readAheadManyResults() ? "readahead " : "",
  14198. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14199. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14200. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14201. xmlwrite.str());
  14202. }
  14203. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14204. {
  14205. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14206. if (!ret)
  14207. xmlwrite.outputBool(true,"eof");
  14208. else if (input->queryOutputMeta()->hasXML())
  14209. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14210. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14211. numFields,
  14212. stepExtra.readAheadManyResults() ? "readahead " : "",
  14213. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14214. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14215. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14216. xmlwrite.str());
  14217. }
  14218. return ret;
  14219. #else
  14220. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14221. #endif
  14222. }
  14223. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14224. {
  14225. return input->gatherConjunctions(collector);
  14226. }
  14227. virtual void resetEOF()
  14228. {
  14229. input->resetEOF();
  14230. }
  14231. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14232. {
  14233. return input->querySteppingMeta();
  14234. }
  14235. inline const void * doNextInputRow()
  14236. {
  14237. const void * ret = input->nextInGroup();
  14238. if (!ret)
  14239. ret = input->nextInGroup();
  14240. return ret;
  14241. }
  14242. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14243. {
  14244. assertex(wasCompleteMatch);
  14245. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14246. }
  14247. protected:
  14248. IRoxieInput * input;
  14249. };
  14250. //=================================================================================
  14251. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  14252. {
  14253. public:
  14254. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14255. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  14256. {
  14257. }
  14258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14259. {
  14260. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14261. for (unsigned i=0; i < numInputs; i++)
  14262. {
  14263. IRoxieInput * cur = inputArray[i];
  14264. unsigned numRealInputs = cur->numConcreteOutputs();
  14265. for (unsigned j = 0; j < numRealInputs; j++)
  14266. {
  14267. IRoxieInput * curReal = cur->queryConcreteInput(j);
  14268. expandedInputs.append(curReal);
  14269. }
  14270. }
  14271. }
  14272. virtual void reset()
  14273. {
  14274. expandedInputs.kill();
  14275. CRoxieServerMultiInputActivity::reset();
  14276. }
  14277. protected:
  14278. PointerArrayOf<IRoxieInput> expandedInputs;
  14279. };
  14280. //=================================================================================
  14281. class CRoxieStreamMerger : public CStreamMerger
  14282. {
  14283. public:
  14284. CRoxieStreamMerger() : CStreamMerger(true)
  14285. {
  14286. inputArray = NULL;
  14287. }
  14288. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  14289. {
  14290. CStreamMerger::initInputs(_numInputs);
  14291. inputArray = _inputArray;
  14292. }
  14293. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14294. {
  14295. const void * next;
  14296. bool matches = true;
  14297. if (seek)
  14298. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  14299. else
  14300. next = nextUngrouped(inputArray[i]);
  14301. pending[i] = next;
  14302. pendingMatches[i] = matches;
  14303. return (next != NULL);
  14304. }
  14305. virtual void releaseRow(const void * row)
  14306. {
  14307. ReleaseRoxieRow(row);
  14308. }
  14309. protected:
  14310. IRoxieInput **inputArray;
  14311. };
  14312. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14313. {
  14314. public:
  14315. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14316. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  14317. helper((IHThorNWayMergeArg &)basehelper)
  14318. {
  14319. initializedMeta = false;
  14320. }
  14321. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14322. {
  14323. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14324. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14325. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  14326. }
  14327. virtual void stop(bool aborting)
  14328. {
  14329. merger.done();
  14330. CRoxieServerNaryActivity::stop(aborting);
  14331. }
  14332. virtual void reset()
  14333. {
  14334. merger.cleanup();
  14335. CRoxieServerNaryActivity::reset();
  14336. initializedMeta = false;
  14337. }
  14338. virtual const void * nextInGroup()
  14339. {
  14340. ActivityTimer t(totalCycles, timeActivities);
  14341. const void * next = merger.nextRow();
  14342. if (next)
  14343. processed++;
  14344. return next;
  14345. }
  14346. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14347. {
  14348. ActivityTimer t(totalCycles, timeActivities);
  14349. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14350. if (next)
  14351. processed++;
  14352. return next;
  14353. }
  14354. virtual IInputSteppingMeta * querySteppingMeta()
  14355. {
  14356. if (expandedInputs.ordinality() == 0)
  14357. return NULL;
  14358. if (!initializedMeta)
  14359. {
  14360. meta.init(helper.querySteppingMeta(), false);
  14361. ForEachItemIn(i, expandedInputs)
  14362. {
  14363. if (meta.getNumFields() == 0)
  14364. break;
  14365. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14366. meta.intersect(inputMeta);
  14367. }
  14368. initializedMeta = true;
  14369. }
  14370. if (meta.getNumFields() == 0)
  14371. return NULL;
  14372. return &meta;
  14373. }
  14374. protected:
  14375. IHThorNWayMergeArg &helper;
  14376. CRoxieStreamMerger merger;
  14377. CSteppingMeta meta;
  14378. bool initializedMeta;
  14379. };
  14380. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14381. {
  14382. public:
  14383. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14384. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14385. {
  14386. }
  14387. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14388. {
  14389. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14390. }
  14391. };
  14392. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14393. {
  14394. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14395. }
  14396. //=================================================================================
  14397. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14398. {
  14399. public:
  14400. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14401. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14402. helper((IHThorNWayMergeJoinArg &)basehelper)
  14403. {
  14404. }
  14405. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14406. {
  14407. CRoxieServerNaryActivity::onCreate(_ctx, _colocalParent);
  14408. ICodeContext * codectx = ctx->queryCodeContext();
  14409. inputAllocator.setown(codectx->getRowAllocator(helper.queryInputMeta(), activityId));
  14410. outputAllocator.setown(codectx->getRowAllocator(helper.queryOutputMeta(), activityId));
  14411. }
  14412. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14413. {
  14414. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14415. ForEachItemIn(i1, expandedInputs)
  14416. {
  14417. IRoxieInput * cur = expandedInputs.item(i1);
  14418. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14419. processor.addInput(stepInput);
  14420. }
  14421. processor.beforeProcessing(inputAllocator, outputAllocator);
  14422. }
  14423. virtual void stop(bool aborting)
  14424. {
  14425. processor.afterProcessing();
  14426. CRoxieServerNaryActivity::stop(aborting);
  14427. }
  14428. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14429. {
  14430. return processor.gatherConjunctions(collector);
  14431. }
  14432. virtual void resetEOF()
  14433. {
  14434. processor.queryResetEOF();
  14435. }
  14436. virtual const void * nextInGroup()
  14437. {
  14438. ActivityTimer t(totalCycles, timeActivities);
  14439. const void * next = processor.nextInGroup();
  14440. if (next)
  14441. processed++;
  14442. return next;
  14443. }
  14444. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14445. {
  14446. ActivityTimer t(totalCycles, timeActivities);
  14447. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14448. if (next)
  14449. processed++;
  14450. return next;
  14451. }
  14452. virtual IInputSteppingMeta * querySteppingMeta()
  14453. {
  14454. return processor.queryInputSteppingMeta();
  14455. }
  14456. protected:
  14457. IHThorNWayMergeJoinArg & helper;
  14458. CMergeJoinProcessor & processor;
  14459. Owned<IEngineRowAllocator> inputAllocator;
  14460. Owned<IEngineRowAllocator> outputAllocator;
  14461. };
  14462. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14463. {
  14464. public:
  14465. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14466. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14467. {
  14468. }
  14469. protected:
  14470. CAndMergeJoinProcessor andProcessor;
  14471. };
  14472. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14473. {
  14474. public:
  14475. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14476. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14477. {
  14478. }
  14479. protected:
  14480. CAndLeftMergeJoinProcessor andLeftProcessor;
  14481. };
  14482. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14483. {
  14484. public:
  14485. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14486. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14487. {
  14488. }
  14489. protected:
  14490. CMofNMergeJoinProcessor mofnProcessor;
  14491. };
  14492. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14493. {
  14494. public:
  14495. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14496. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14497. {
  14498. }
  14499. protected:
  14500. CProximityJoinProcessor proximityProcessor;
  14501. };
  14502. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14503. {
  14504. unsigned flags;
  14505. public:
  14506. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14507. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14508. {
  14509. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14510. flags = helper->getJoinFlags();
  14511. }
  14512. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14513. {
  14514. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14515. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14516. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14517. {
  14518. case IHThorNWayMergeJoinArg::MJFinner:
  14519. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14520. case IHThorNWayMergeJoinArg::MJFleftonly:
  14521. case IHThorNWayMergeJoinArg::MJFleftouter:
  14522. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14523. case IHThorNWayMergeJoinArg::MJFmofn:
  14524. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14525. default:
  14526. throwUnexpected();
  14527. }
  14528. }
  14529. };
  14530. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14531. {
  14532. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14533. }
  14534. //=================================================================================
  14535. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14536. {
  14537. IHThorNWaySelectArg &helper;
  14538. public:
  14539. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14540. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14541. helper((IHThorNWaySelectArg &)basehelper)
  14542. {
  14543. selectedInput = NULL;
  14544. }
  14545. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14546. {
  14547. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14548. unsigned whichInput = helper.getInputIndex();
  14549. selectedInput = NULL;
  14550. if (whichInput--)
  14551. {
  14552. for (unsigned i=0; i < numInputs; i++)
  14553. {
  14554. IRoxieInput * cur = inputArray[i];
  14555. unsigned numRealInputs = cur->numConcreteOutputs();
  14556. if (whichInput < numRealInputs)
  14557. {
  14558. selectedInput = cur->queryConcreteInput(whichInput);
  14559. break;
  14560. }
  14561. whichInput -= numRealInputs;
  14562. }
  14563. }
  14564. }
  14565. virtual void reset()
  14566. {
  14567. selectedInput = NULL;
  14568. CRoxieServerMultiInputActivity::reset();
  14569. }
  14570. const void * nextInGroup()
  14571. {
  14572. ActivityTimer t(totalCycles, timeActivities);
  14573. if (!selectedInput)
  14574. return NULL;
  14575. return selectedInput->nextInGroup();
  14576. }
  14577. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14578. {
  14579. if (!selectedInput)
  14580. return false;
  14581. return selectedInput->gatherConjunctions(collector);
  14582. }
  14583. virtual void resetEOF()
  14584. {
  14585. if (selectedInput)
  14586. selectedInput->resetEOF();
  14587. }
  14588. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14589. {
  14590. ActivityTimer t(totalCycles, timeActivities);
  14591. if (!selectedInput)
  14592. return NULL;
  14593. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14594. }
  14595. IInputSteppingMeta * querySteppingMeta()
  14596. {
  14597. if (selectedInput)
  14598. return selectedInput->querySteppingMeta();
  14599. return NULL;
  14600. }
  14601. protected:
  14602. IRoxieInput * selectedInput;
  14603. };
  14604. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14605. {
  14606. public:
  14607. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14608. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14609. {
  14610. }
  14611. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14612. {
  14613. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14614. }
  14615. };
  14616. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14617. {
  14618. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14619. }
  14620. //=================================================================================
  14621. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14622. {
  14623. protected:
  14624. IHThorRemoteArg &helper;
  14625. CRemoteResultAdaptor remote;
  14626. public:
  14627. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14628. : CRoxieServerActivity(_factory, _probeManager),
  14629. helper((IHThorRemoteArg &)basehelper),
  14630. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14631. {
  14632. }
  14633. virtual const IResolvedFile *queryVarFileInfo() const
  14634. {
  14635. return NULL;
  14636. }
  14637. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14638. {
  14639. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14640. remote.onCreate(this, this, _ctx, _colocalParent);
  14641. }
  14642. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14643. {
  14644. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14645. remote.onStart(parentExtractSize, parentExtract);
  14646. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14647. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14648. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14649. remote.flush();
  14650. remote.senddone();
  14651. }
  14652. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14653. {
  14654. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14655. }
  14656. virtual IRoxieInput *queryOutput(unsigned idx)
  14657. {
  14658. if (idx==(unsigned)-1)
  14659. idx = 0;
  14660. return idx ? NULL: &remote;
  14661. }
  14662. virtual void reset()
  14663. {
  14664. processed = remote.processed;
  14665. remote.processed = 0;
  14666. CRoxieServerActivity::reset();
  14667. }
  14668. virtual void onLimitExceeded(bool isKeyed)
  14669. {
  14670. if (traceLevel > 4)
  14671. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14672. helper.onLimitExceeded();
  14673. }
  14674. virtual const void *createLimitFailRow(bool isKeyed)
  14675. {
  14676. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14677. }
  14678. virtual const void *nextInGroup()
  14679. {
  14680. throwUnexpected(); // I am nobody's input
  14681. }
  14682. };
  14683. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14684. {
  14685. public:
  14686. RemoteActivityId remoteId;
  14687. bool isRoot;
  14688. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14689. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14690. {
  14691. }
  14692. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14693. {
  14694. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14695. }
  14696. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14697. {
  14698. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14699. }
  14700. virtual bool isSink() const
  14701. {
  14702. //I don't think the action version of this is implemented - but this would be the code
  14703. return isRoot && !meta.queryOriginal();
  14704. }
  14705. virtual const StatisticsMapping &queryStatsMapping() const
  14706. {
  14707. return allStatistics; // Child queries...
  14708. }
  14709. };
  14710. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14711. {
  14712. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14713. }
  14714. //=================================================================================
  14715. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14716. {
  14717. IHThorIterateArg &helper;
  14718. OwnedConstRoxieRow defaultRecord;
  14719. OwnedConstRoxieRow left;
  14720. OwnedConstRoxieRow right;
  14721. unsigned counter;
  14722. public:
  14723. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14724. : CRoxieServerActivity(_factory, _probeManager),
  14725. helper((IHThorIterateArg &)basehelper)
  14726. {
  14727. counter = 0;
  14728. }
  14729. virtual bool needsAllocator() const { return true; }
  14730. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14731. {
  14732. counter = 0;
  14733. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14734. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14735. size32_t thisSize = helper.createDefault(rowBuilder);
  14736. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14737. }
  14738. virtual void reset()
  14739. {
  14740. defaultRecord.clear();
  14741. right.clear();
  14742. left.clear();
  14743. CRoxieServerActivity::reset();
  14744. }
  14745. virtual const void * nextInGroup()
  14746. {
  14747. ActivityTimer t(totalCycles, timeActivities);
  14748. loop
  14749. {
  14750. right.setown(input->nextInGroup());
  14751. if (!right)
  14752. {
  14753. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14754. left.clear();
  14755. counter = 0;
  14756. if (skippedGroup) continue;
  14757. return NULL;
  14758. }
  14759. try
  14760. {
  14761. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14762. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14763. if (outSize)
  14764. {
  14765. left.setown(rowBuilder.finalizeRowClear(outSize));
  14766. processed++;
  14767. return left.getLink();
  14768. }
  14769. }
  14770. catch (IException *E)
  14771. {
  14772. throw makeWrappedException(E);
  14773. }
  14774. }
  14775. }
  14776. };
  14777. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14778. {
  14779. public:
  14780. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14781. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14782. {
  14783. }
  14784. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14785. {
  14786. return new CRoxieServerIterateActivity(this, _probeManager);
  14787. }
  14788. };
  14789. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14790. {
  14791. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14792. }
  14793. //=================================================================================
  14794. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14795. {
  14796. IHThorProcessArg &helper;
  14797. OwnedConstRoxieRow curRight;
  14798. OwnedConstRoxieRow initialRight;
  14799. unsigned counter;
  14800. Owned<IEngineRowAllocator> rightRowAllocator;
  14801. public:
  14802. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14803. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14804. {
  14805. counter = 0;
  14806. }
  14807. virtual bool needsAllocator() const { return true; }
  14808. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14809. {
  14810. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14811. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14812. }
  14813. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14814. {
  14815. counter = 0;
  14816. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14817. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14818. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14819. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14820. curRight.set(initialRight);
  14821. }
  14822. virtual const void * nextInGroup()
  14823. {
  14824. ActivityTimer t(totalCycles, timeActivities);
  14825. try
  14826. {
  14827. loop
  14828. {
  14829. const void * in = input->nextInGroup();
  14830. if (!in)
  14831. {
  14832. bool eog = (curRight != initialRight); // processed any records?
  14833. counter = 0;
  14834. curRight.set(initialRight);
  14835. if (eog)
  14836. return NULL;
  14837. in = input->nextInGroup();
  14838. if (!in)
  14839. return NULL;
  14840. }
  14841. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14842. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14843. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14844. ReleaseRoxieRow(in);
  14845. if (outSize)
  14846. {
  14847. //MORE: This should be returned...
  14848. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14849. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14850. processed++;
  14851. return rowBuilder.finalizeRowClear(outSize);
  14852. }
  14853. }
  14854. }
  14855. catch (IException *E)
  14856. {
  14857. throw makeWrappedException(E);
  14858. }
  14859. }
  14860. };
  14861. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14862. {
  14863. public:
  14864. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14865. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14866. {
  14867. }
  14868. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14869. {
  14870. return new CRoxieServerProcessActivity(this, _probeManager);
  14871. }
  14872. };
  14873. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14874. {
  14875. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14876. }
  14877. //=================================================================================
  14878. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14879. {
  14880. IHThorGroupArg &helper;
  14881. bool endPending;
  14882. bool eof;
  14883. bool first;
  14884. const void *next;
  14885. public:
  14886. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14887. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14888. {
  14889. next = NULL;
  14890. endPending = false;
  14891. eof = false;
  14892. first = true;
  14893. }
  14894. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14895. {
  14896. endPending = false;
  14897. eof = false;
  14898. first = true;
  14899. assertex(next == NULL);
  14900. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14901. }
  14902. virtual void reset()
  14903. {
  14904. ReleaseClearRoxieRow(next);
  14905. CRoxieServerActivity::reset();
  14906. }
  14907. virtual const void * nextInGroup()
  14908. {
  14909. ActivityTimer t(totalCycles, timeActivities);
  14910. if (first)
  14911. {
  14912. next = input->nextInGroup();
  14913. first = false;
  14914. }
  14915. if (eof || endPending)
  14916. {
  14917. endPending = false;
  14918. return NULL;
  14919. }
  14920. const void * prev = next;
  14921. next = input->nextInGroup();
  14922. if (!next)
  14923. next = input->nextInGroup();
  14924. if (next)
  14925. {
  14926. assertex(prev);
  14927. if (!helper.isSameGroup(prev, next))
  14928. endPending = true;
  14929. }
  14930. else
  14931. eof = true;
  14932. if (prev)
  14933. processed++;
  14934. return prev;
  14935. }
  14936. };
  14937. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14938. {
  14939. public:
  14940. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14941. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14942. {
  14943. }
  14944. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14945. {
  14946. return new CRoxieServerGroupActivity(this, _probeManager);
  14947. }
  14948. };
  14949. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14950. {
  14951. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14952. }
  14953. //=================================================================================
  14954. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14955. {
  14956. unsigned __int64 limit;
  14957. unsigned __int64 skip;
  14958. unsigned doneThisGroup;
  14959. IHThorFirstNArg &helper;
  14960. public:
  14961. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14962. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14963. {
  14964. doneThisGroup = 0;
  14965. limit = 0;
  14966. skip = 0;
  14967. }
  14968. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14969. {
  14970. doneThisGroup = 0;
  14971. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14972. limit = helper.getLimit();
  14973. skip = helper.numToSkip();
  14974. lateStart(parentExtractSize, parentExtract, limit > 0);
  14975. if (limit + skip >= limit)
  14976. limit += skip;
  14977. }
  14978. const void * nextInGroup()
  14979. {
  14980. ActivityTimer t(totalCycles, timeActivities);
  14981. if (eof)
  14982. return NULL;
  14983. const void *ret;
  14984. loop
  14985. {
  14986. ret = input->nextInGroup();
  14987. if (!ret)
  14988. {
  14989. if (meta.isGrouped())
  14990. {
  14991. if (doneThisGroup > skip)
  14992. {
  14993. doneThisGroup = 0;
  14994. return NULL;
  14995. }
  14996. doneThisGroup = 0;
  14997. }
  14998. ret = input->nextInGroup();
  14999. if (!ret)
  15000. {
  15001. eof = true;
  15002. return NULL;
  15003. }
  15004. }
  15005. doneThisGroup++;
  15006. if (doneThisGroup > skip)
  15007. break;
  15008. ReleaseRoxieRow(ret);
  15009. }
  15010. if (doneThisGroup <= limit)
  15011. {
  15012. processed++;
  15013. return ret;
  15014. }
  15015. ReleaseRoxieRow(ret);
  15016. if (meta.isGrouped())
  15017. {
  15018. while ((ret = input->nextInGroup()) != NULL)
  15019. ReleaseRoxieRow(ret);
  15020. doneThisGroup = 0;
  15021. }
  15022. else
  15023. eof = true;
  15024. return NULL;
  15025. }
  15026. };
  15027. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15028. {
  15029. public:
  15030. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15031. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15032. {
  15033. }
  15034. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15035. {
  15036. return new CRoxieServerFirstNActivity(this, _probeManager);
  15037. }
  15038. };
  15039. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15040. {
  15041. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15042. }
  15043. //=================================================================================
  15044. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15045. {
  15046. bool done;
  15047. IHThorSelectNArg &helper;
  15048. public:
  15049. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15050. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15051. {
  15052. done = false;
  15053. }
  15054. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15055. {
  15056. done = false;
  15057. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15058. }
  15059. const void *defaultRow()
  15060. {
  15061. if (!rowAllocator)
  15062. createRowAllocator(); // We delay as often not needed...
  15063. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15064. size32_t thisSize = helper.createDefault(rowBuilder);
  15065. return rowBuilder.finalizeRowClear(thisSize);
  15066. }
  15067. virtual const void * nextInGroup()
  15068. {
  15069. ActivityTimer t(totalCycles, timeActivities);
  15070. if (done)
  15071. return NULL;
  15072. done = true;
  15073. processed++; // always going to return a row!
  15074. unsigned __int64 index = helper.getRowToSelect();
  15075. while (--index)
  15076. {
  15077. const void * next = input->nextInGroup();
  15078. if (!next)
  15079. next = input->nextInGroup();
  15080. if (!next)
  15081. return defaultRow();
  15082. ReleaseRoxieRow(next);
  15083. }
  15084. const void * next = input->nextInGroup();
  15085. if (!next)
  15086. next = input->nextInGroup();
  15087. if (!next)
  15088. next = defaultRow();
  15089. return next;
  15090. }
  15091. };
  15092. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15093. {
  15094. public:
  15095. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15096. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15097. {
  15098. }
  15099. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15100. {
  15101. return new CRoxieServerSelectNActivity(this, _probeManager);
  15102. }
  15103. };
  15104. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15105. {
  15106. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15107. }
  15108. //=================================================================================
  15109. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15110. {
  15111. IHThorJoinArg &helper;
  15112. ICompare *collate;
  15113. OwnedRowArray group;
  15114. bool matchedLeft;
  15115. BoolArray matchedRight;
  15116. bool eof;
  15117. bool first;
  15118. unsigned leftIndex;
  15119. unsigned rightIndex;
  15120. unsigned rightOuterIndex;
  15121. unsigned joinLimit;
  15122. unsigned atmostLimit;
  15123. unsigned atmostsTriggered;
  15124. unsigned abortLimit;
  15125. unsigned keepLimit;
  15126. unsigned joinCounter;
  15127. bool leftOuterJoin;
  15128. bool rightOuterJoin;
  15129. bool exclude;
  15130. bool limitFail;
  15131. bool limitOnFail;
  15132. bool cloneLeft;
  15133. OwnedConstRoxieRow defaultLeft;
  15134. OwnedConstRoxieRow defaultRight;
  15135. OwnedConstRoxieRow lhs;
  15136. Owned<IException> failingLimit;
  15137. bool failingOuterAtmost;
  15138. Owned<IEngineRowAllocator> defaultAllocator;
  15139. Owned<IRHLimitedCompareHelper> limitedhelper;
  15140. Owned<CRHDualCache> dualcache;
  15141. IInputBase *dualCacheInput;
  15142. bool fillGroup()
  15143. {
  15144. group.clear();
  15145. matchedLeft = false;
  15146. matchedRight.kill();
  15147. failingOuterAtmost = false;
  15148. const void * next;
  15149. unsigned groupCount = 0;
  15150. while((next = input->nextInGroup()) != NULL)
  15151. {
  15152. if(groupCount==abortLimit)
  15153. {
  15154. if(limitFail)
  15155. failLimit(next);
  15156. if (ctx->queryDebugContext())
  15157. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15158. if(limitOnFail)
  15159. {
  15160. assertex(!failingLimit);
  15161. try
  15162. {
  15163. failLimit(next);
  15164. }
  15165. catch(IException * except)
  15166. {
  15167. failingLimit.setown(except);
  15168. }
  15169. assertex(failingLimit != NULL);
  15170. group.append(next);
  15171. groupCount++;
  15172. break;
  15173. }
  15174. group.clear();
  15175. groupCount = 0;
  15176. while(next)
  15177. {
  15178. ReleaseRoxieRow(next);
  15179. next = input->nextInGroup();
  15180. }
  15181. }
  15182. else if(groupCount==atmostLimit)
  15183. {
  15184. atmostsTriggered++;
  15185. if(leftOuterJoin)
  15186. {
  15187. group.append(next);
  15188. groupCount++;
  15189. failingOuterAtmost = true;
  15190. break;
  15191. }
  15192. else
  15193. {
  15194. group.clear();
  15195. groupCount = 0;
  15196. while (next)
  15197. {
  15198. ReleaseRoxieRow(next);
  15199. next = input->nextInGroup();
  15200. }
  15201. }
  15202. }
  15203. else
  15204. {
  15205. group.append(next);
  15206. groupCount++;
  15207. }
  15208. }
  15209. if(group.ordinality()==0)
  15210. {
  15211. eof = true;
  15212. return false;
  15213. }
  15214. leftIndex = 0;
  15215. rightIndex = 0;
  15216. rightOuterIndex = 0;
  15217. joinCounter = 0;
  15218. joinLimit = keepLimit;
  15219. ForEachItemIn(idx, group)
  15220. matchedRight.append(false);
  15221. return true;
  15222. }
  15223. void failLimit(const void * next)
  15224. {
  15225. helper.onMatchAbortLimitExceeded();
  15226. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15227. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15228. {
  15229. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15230. }
  15231. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15232. }
  15233. virtual bool needsAllocator() const { return true; }
  15234. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15235. {
  15236. try
  15237. {
  15238. if (cloneLeft && !except)
  15239. {
  15240. LinkRoxieRow(curLeft);
  15241. return curLeft;
  15242. }
  15243. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15244. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15245. if (outsize)
  15246. return rowBuilder.finalizeRowClear(outsize);
  15247. else
  15248. return NULL;
  15249. }
  15250. catch (IException *E)
  15251. {
  15252. throw makeWrappedException(E);
  15253. }
  15254. }
  15255. void createDefaultLeft()
  15256. {
  15257. if (!defaultLeft)
  15258. {
  15259. if (!defaultAllocator)
  15260. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15261. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15262. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15263. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15264. }
  15265. }
  15266. void createDefaultRight()
  15267. {
  15268. if (!defaultRight)
  15269. {
  15270. if (!defaultAllocator)
  15271. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15272. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15273. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15274. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15275. }
  15276. }
  15277. public:
  15278. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15279. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  15280. {
  15281. collate = helper.queryCompareLeftRight();
  15282. eof = false;
  15283. first = true;
  15284. keepLimit = 0;
  15285. atmostLimit = 0;
  15286. atmostsTriggered = 0;
  15287. unsigned joinFlags = helper.getJoinFlags();
  15288. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15289. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15290. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15291. exclude = (joinFlags & JFexclude) != 0;
  15292. abortLimit = 0;
  15293. joinLimit = 0;
  15294. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15295. getLimitType(joinFlags, limitFail, limitOnFail);
  15296. if((joinFlags & JFslidingmatch) != 0)
  15297. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15298. failingOuterAtmost = false;
  15299. matchedLeft = false;
  15300. leftIndex = 0;
  15301. rightIndex = 0;
  15302. rightOuterIndex = 0;
  15303. joinCounter = 0;
  15304. dualCacheInput = NULL;
  15305. }
  15306. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15307. {
  15308. eof = false;
  15309. first = true;
  15310. failingLimit.clear();
  15311. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15312. keepLimit = helper.getKeepLimit();
  15313. if(keepLimit == 0)
  15314. keepLimit = (unsigned)-1;
  15315. atmostsTriggered = 0;
  15316. atmostLimit = helper.getJoinLimit();
  15317. if(atmostLimit == 0)
  15318. atmostLimit = (unsigned)-1;
  15319. else
  15320. assertex(!rightOuterJoin);
  15321. abortLimit = helper.getMatchAbortLimit();
  15322. if (abortLimit == 0)
  15323. abortLimit = (unsigned)-1;
  15324. if (rightOuterJoin)
  15325. createDefaultLeft();
  15326. if (leftOuterJoin || limitOnFail)
  15327. createDefaultRight();
  15328. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15329. { //limited match join (s[1..n])
  15330. dualcache.setown(new CRHDualCache());
  15331. dualcache->init(CRoxieServerActivity::input);
  15332. dualCacheInput = dualcache->queryOut1();
  15333. failingOuterAtmost = false;
  15334. matchedLeft = false;
  15335. leftIndex = 0;
  15336. rightOuterIndex = 0;
  15337. joinCounter = 0;
  15338. limitedhelper.setown(createRHLimitedCompareHelper());
  15339. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15340. }
  15341. }
  15342. virtual void reset()
  15343. {
  15344. if (atmostsTriggered)
  15345. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15346. group.clear();
  15347. CRoxieServerActivity::reset();
  15348. defaultLeft.clear();
  15349. defaultRight.clear();
  15350. }
  15351. virtual const void * nextInGroup()
  15352. {
  15353. ActivityTimer t(totalCycles, timeActivities);
  15354. if (limitedhelper)
  15355. {
  15356. while(!eof) //limited match join
  15357. {
  15358. if (!group.isItem(rightIndex))
  15359. {
  15360. lhs.setown(dualCacheInput->nextInGroup());
  15361. if (lhs)
  15362. {
  15363. rightIndex = 0;
  15364. joinCounter = 0;
  15365. group.clear();
  15366. limitedhelper->getGroup(group,lhs);
  15367. }
  15368. else
  15369. {
  15370. eof = true;
  15371. }
  15372. }
  15373. if (group.isItem(rightIndex))
  15374. {
  15375. const void * rhs = group.item(rightIndex++);
  15376. if(helper.match(lhs, rhs))
  15377. {
  15378. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15379. return ret;
  15380. }
  15381. }
  15382. }
  15383. return NULL;
  15384. }
  15385. else
  15386. {
  15387. if (first)
  15388. {
  15389. first = false;
  15390. fillGroup();
  15391. }
  15392. while(!eof)
  15393. {
  15394. if(failingOuterAtmost)
  15395. while(group.isItem(leftIndex))
  15396. {
  15397. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  15398. if(ret)
  15399. {
  15400. processed++;
  15401. return ret;
  15402. }
  15403. }
  15404. if((joinLimit == 0) || !group.isItem(rightIndex))
  15405. {
  15406. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15407. {
  15408. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  15409. if(ret)
  15410. {
  15411. matchedLeft = true;
  15412. processed++;
  15413. return ret;
  15414. }
  15415. }
  15416. leftIndex++;
  15417. matchedLeft = false;
  15418. rightIndex = 0;
  15419. joinCounter = 0;
  15420. joinLimit = keepLimit;
  15421. }
  15422. if(!group.isItem(leftIndex))
  15423. {
  15424. if(failingLimit || failingOuterAtmost)
  15425. {
  15426. const void * lhs;
  15427. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15428. {
  15429. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15430. ReleaseRoxieRow(lhs);
  15431. if(ret)
  15432. {
  15433. processed++;
  15434. return ret;
  15435. }
  15436. }
  15437. failingLimit.clear();
  15438. }
  15439. if(rightOuterJoin && !failingLimit)
  15440. while(group.isItem(rightOuterIndex))
  15441. if(!matchedRight.item(rightOuterIndex++))
  15442. {
  15443. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  15444. if(ret)
  15445. {
  15446. processed++;
  15447. return ret;
  15448. }
  15449. }
  15450. if(!fillGroup())
  15451. return NULL;
  15452. continue;
  15453. }
  15454. const void * lhs = group.item(leftIndex);
  15455. if(failingLimit)
  15456. {
  15457. leftIndex++;
  15458. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15459. if(ret)
  15460. {
  15461. processed++;
  15462. return ret;
  15463. }
  15464. }
  15465. else
  15466. {
  15467. const void * rhs = group.item(rightIndex++);
  15468. if(helper.match(lhs, rhs))
  15469. {
  15470. matchedLeft = true;
  15471. matchedRight.replace(true, rightIndex-1);
  15472. if(!exclude)
  15473. {
  15474. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15475. if(ret)
  15476. {
  15477. processed++;
  15478. joinLimit--;
  15479. return ret;
  15480. }
  15481. }
  15482. }
  15483. }
  15484. }
  15485. return NULL;
  15486. }
  15487. }
  15488. };
  15489. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15490. {
  15491. public:
  15492. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15493. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15494. {
  15495. }
  15496. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15497. {
  15498. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15499. }
  15500. virtual const StatisticsMapping &queryStatsMapping() const
  15501. {
  15502. return joinStatistics;
  15503. }
  15504. };
  15505. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15506. {
  15507. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15508. }
  15509. //=====================================================================================================
  15510. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15511. {
  15512. private:
  15513. class LookupTable : public CInterface
  15514. {
  15515. public:
  15516. LookupTable(IHThorHashJoinArg &helper)
  15517. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  15518. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  15519. {
  15520. size = 0;
  15521. }
  15522. virtual const void *find(const void * left) const = 0;
  15523. virtual const void *findNext(const void * left) const = 0;
  15524. protected:
  15525. ICompare * leftRightCompare;
  15526. ICompare * rightCompare;
  15527. IHash * leftHash;
  15528. IHash * rightHash;
  15529. unsigned size;
  15530. };
  15531. class DedupLookupTable : public LookupTable
  15532. {
  15533. public:
  15534. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15535. : LookupTable(helper)
  15536. {
  15537. size = (4*rightRows.length())/3 + 1;
  15538. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  15539. ForEachItemIn(idx, rightRows)
  15540. add(rightRows.item(idx));
  15541. }
  15542. ~DedupLookupTable()
  15543. {
  15544. unsigned i;
  15545. for(i=0; i<size; i++)
  15546. ReleaseRoxieRow(table[i]);
  15547. free(table);
  15548. }
  15549. virtual const void *find(const void * left) const
  15550. {
  15551. unsigned index = leftHash->hash(left) % size;
  15552. unsigned start = index;
  15553. while (table[index])
  15554. {
  15555. if(leftRightCompare->docompare(left, table[index]) == 0)
  15556. return table[index];
  15557. index++;
  15558. if (index==size)
  15559. index = 0;
  15560. if (index==start)
  15561. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15562. }
  15563. return NULL;
  15564. }
  15565. virtual const void *findNext(const void * left) const
  15566. {
  15567. return NULL;
  15568. }
  15569. protected:
  15570. void add(const void * right)
  15571. {
  15572. unsigned index = rightHash->hash(right) % size;
  15573. unsigned start = index;
  15574. while (table[index])
  15575. {
  15576. if (rightCompare->docompare(table[index], right) == 0)
  15577. {
  15578. ReleaseRoxieRow(right);
  15579. return;
  15580. }
  15581. index++;
  15582. if (index==size)
  15583. index = 0;
  15584. if (index==start)
  15585. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  15586. }
  15587. table[index] = right;
  15588. }
  15589. const void * * table;
  15590. };
  15591. class FewLookupTable : public LookupTable
  15592. {
  15593. public:
  15594. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15595. : LookupTable(helper)
  15596. {
  15597. size = (4*rightRows.length())/3 + 1;
  15598. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  15599. findex = fstart = BadIndex;
  15600. ForEachItemIn(idx, rightRows)
  15601. add(rightRows.item(idx));
  15602. }
  15603. ~FewLookupTable()
  15604. {
  15605. unsigned i;
  15606. for(i=0; i<size; i++)
  15607. ReleaseRoxieRow(table[i]);
  15608. free(table);
  15609. }
  15610. virtual const void *find(const void * left) const
  15611. {
  15612. fstart = leftHash->hash(left) % size;
  15613. findex = fstart;
  15614. return doFind(left);
  15615. }
  15616. virtual const void *findNext(const void * left) const
  15617. {
  15618. if (findex == BadIndex)
  15619. return NULL;
  15620. advance();
  15621. return doFind(left);
  15622. }
  15623. protected:
  15624. void add(const void * right)
  15625. {
  15626. unsigned start = rightHash->hash(right) % size;
  15627. unsigned index = start;
  15628. while (table[index])
  15629. {
  15630. index++;
  15631. if (index==size)
  15632. index = 0;
  15633. if (index==start)
  15634. throwUnexpected(); //table is full, should never happen
  15635. }
  15636. table[index] = right;
  15637. }
  15638. void advance() const
  15639. {
  15640. findex++;
  15641. if(findex==size)
  15642. findex = 0;
  15643. if(findex==fstart)
  15644. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15645. }
  15646. const void *doFind(const void * left) const
  15647. {
  15648. while(table[findex])
  15649. {
  15650. if (leftRightCompare->docompare(left, table[findex]) == 0)
  15651. return table[findex];
  15652. advance();
  15653. }
  15654. findex = BadIndex;
  15655. return NULL;
  15656. }
  15657. const void * * table;
  15658. unsigned mutable fstart;
  15659. unsigned mutable findex;
  15660. static unsigned const BadIndex;
  15661. };
  15662. class ManyLookupTable : public LookupTable
  15663. {
  15664. public:
  15665. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15666. : LookupTable(helper)
  15667. {
  15668. rightRows.swapWith(rowtable);
  15669. UInt64Array groups;
  15670. unsigned numRows = rowtable.length();
  15671. if (numRows)
  15672. {
  15673. unsigned groupStart = 0;
  15674. const void *groupStartRow = rowtable.item(0);
  15675. for (unsigned i=1; i < numRows; i++)
  15676. {
  15677. const void *thisRow = rowtable.item(i);
  15678. if (rightCompare->docompare(groupStartRow, thisRow))
  15679. {
  15680. groups.append(makeint64(groupStart, i-groupStart));
  15681. groupStart = i;
  15682. groupStartRow = thisRow;
  15683. }
  15684. }
  15685. groups.append(makeint64(groupStart, numRows-groupStart));
  15686. }
  15687. size = (4*groups.length())/3 + 1;
  15688. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  15689. ForEachItemIn(idx, groups)
  15690. {
  15691. unsigned __int64 group = groups.item(idx);
  15692. unsigned groupstart = high(group);
  15693. const void *row = rowtable.item(groupstart);
  15694. add(row, group);
  15695. }
  15696. }
  15697. ~ManyLookupTable()
  15698. {
  15699. ForEachItemIn(idx, rowtable)
  15700. {
  15701. ReleaseRoxieRow(rowtable.item(idx));
  15702. }
  15703. free(table);
  15704. }
  15705. void add(const void *row, unsigned __int64 group)
  15706. {
  15707. unsigned start = rightHash->hash(row) % size;
  15708. unsigned index = start;
  15709. while (table[index])
  15710. {
  15711. index++;
  15712. if (index==size)
  15713. index = 0;
  15714. if (index==start)
  15715. throwUnexpected(); //table is full, should never happen
  15716. }
  15717. table[index] = group;
  15718. }
  15719. virtual const void *find(const void * left) const
  15720. {
  15721. unsigned index = leftHash->hash(left) % size;
  15722. unsigned start = index;
  15723. while (table[index])
  15724. {
  15725. __uint64 group = table[index];
  15726. currentMatch = high(group);
  15727. const void *right = rowtable.item(currentMatch);
  15728. if (leftRightCompare->docompare(left, right) == 0)
  15729. {
  15730. currentMatch++;
  15731. matchCount = low(group) - 1;
  15732. return right;
  15733. }
  15734. index++;
  15735. if (index==size)
  15736. index = 0;
  15737. if (index==start)
  15738. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15739. }
  15740. matchCount = 0;
  15741. return NULL;
  15742. }
  15743. virtual const void *findNext(const void * left) const
  15744. {
  15745. if (!matchCount)
  15746. return NULL;
  15747. matchCount--;
  15748. return rowtable.item(currentMatch++);
  15749. }
  15750. protected:
  15751. __uint64 *table;
  15752. ConstPointerArray rowtable;
  15753. mutable unsigned currentMatch;
  15754. mutable unsigned matchCount;
  15755. };
  15756. IHThorHashJoinArg &helper;
  15757. bool leftOuterJoin;
  15758. bool exclude;
  15759. bool eog;
  15760. bool many;
  15761. bool dedupRHS;
  15762. bool useFewTable;
  15763. bool matchedGroup;
  15764. const void *left;
  15765. OwnedConstRoxieRow defaultRight;
  15766. Owned<LookupTable> table;
  15767. unsigned keepLimit;
  15768. unsigned atmostLimit;
  15769. unsigned atmostsTriggered;
  15770. unsigned limitLimit;
  15771. unsigned joinCounter;
  15772. bool limitFail;
  15773. bool limitOnFail;
  15774. bool hasGroupLimit;
  15775. bool isSmartJoin;
  15776. unsigned keepCount;
  15777. bool gotMatch;
  15778. bool cloneLeft;
  15779. ConstPointerArray rightGroup;
  15780. aindex_t rightGroupIndex;
  15781. Owned<IException> failingLimit;
  15782. ConstPointerArray filteredRight;
  15783. ThorActivityKind activityKind;
  15784. Owned<IEngineRowAllocator> defaultRightAllocator;
  15785. void createDefaultRight()
  15786. {
  15787. if (!defaultRight)
  15788. {
  15789. if (!defaultRightAllocator)
  15790. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15791. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15792. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15793. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15794. }
  15795. }
  15796. public:
  15797. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  15798. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  15799. {
  15800. unsigned joinFlags = helper.getJoinFlags();
  15801. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15802. assertex((joinFlags & JFrightouter) == 0);
  15803. exclude = (joinFlags & JFexclude) != 0;
  15804. many = (joinFlags & JFmanylookup) != 0;
  15805. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15806. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15807. left = NULL;
  15808. activityKind = factory->getKind();
  15809. eog = false;
  15810. matchedGroup = false;
  15811. gotMatch = false;
  15812. keepLimit = 0;
  15813. keepCount = 0;
  15814. joinCounter = 0;
  15815. atmostLimit = 0;
  15816. atmostsTriggered = 0;
  15817. limitLimit = 0;
  15818. rightGroupIndex = 0;
  15819. hasGroupLimit = false;
  15820. isSmartJoin = (joinFlags & JFsmart) != 0;
  15821. getLimitType(joinFlags, limitFail, limitOnFail);
  15822. }
  15823. void loadRight()
  15824. {
  15825. ConstPointerArray rightset;
  15826. try
  15827. {
  15828. const void * next;
  15829. while(true)
  15830. {
  15831. next = input1->nextInGroup();
  15832. if(!next)
  15833. next = input1->nextInGroup();
  15834. if(!next)
  15835. break;
  15836. rightset.append(next);
  15837. }
  15838. if (!dedupRHS)
  15839. {
  15840. if (useFewTable)
  15841. {
  15842. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15843. }
  15844. else
  15845. {
  15846. if (!helper.isRightAlreadySorted())
  15847. {
  15848. if (helper.getJoinFlags() & JFunstable)
  15849. {
  15850. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  15851. }
  15852. else
  15853. {
  15854. unsigned rightord = rightset.ordinality();
  15855. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  15856. void **temp = (void **) tempAttr.bufferBase();
  15857. void **_rows = const_cast<void * *>(rightset.getArray());
  15858. qsortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  15859. }
  15860. }
  15861. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15862. }
  15863. }
  15864. else
  15865. {
  15866. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15867. }
  15868. }
  15869. catch (...)
  15870. {
  15871. ForEachItemIn(idx, rightset)
  15872. ReleaseRoxieRow(rightset.item(idx));
  15873. throw;
  15874. }
  15875. };
  15876. virtual void reset()
  15877. {
  15878. if (atmostsTriggered)
  15879. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15880. CRoxieServerTwoInputActivity::reset();
  15881. ReleaseClearRoxieRow(left);
  15882. defaultRight.clear();
  15883. table.clear();
  15884. }
  15885. virtual bool needsAllocator() const { return true; }
  15886. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15887. {
  15888. eog = false;
  15889. matchedGroup = false;
  15890. left = NULL;
  15891. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15892. keepLimit = helper.getKeepLimit();
  15893. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15894. atmostsTriggered = 0;
  15895. atmostLimit = helper.getJoinLimit();
  15896. limitLimit = helper.getMatchAbortLimit();
  15897. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15898. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15899. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15900. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15901. switch (activityKind)
  15902. {
  15903. case TAKlookupjoin:
  15904. case TAKlookupdenormalizegroup:
  15905. case TAKsmartjoin:
  15906. case TAKsmartdenormalizegroup:
  15907. if (leftOuterJoin)
  15908. createDefaultRight();
  15909. break;
  15910. }
  15911. if (limitOnFail)
  15912. createDefaultRight();
  15913. }
  15914. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15915. {
  15916. if (idx==1)
  15917. input1 = _in;
  15918. else
  15919. {
  15920. if ((helper.getJoinFlags() & JFparallel) != 0)
  15921. {
  15922. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15923. puller->setInput(0, _in);
  15924. _in = puller;
  15925. }
  15926. CRoxieServerActivity::setInput(idx, _in);
  15927. }
  15928. }
  15929. virtual const void * nextInGroup()
  15930. {
  15931. ActivityTimer t(totalCycles, timeActivities);
  15932. if(!table)
  15933. loadRight();
  15934. switch (activityKind)
  15935. {
  15936. case TAKlookupjoin:
  15937. case TAKsmartjoin:
  15938. return nextInGroupJoin();
  15939. case TAKlookupdenormalize:
  15940. case TAKlookupdenormalizegroup:
  15941. case TAKsmartdenormalize:
  15942. case TAKsmartdenormalizegroup:
  15943. return nextInGroupDenormalize();
  15944. }
  15945. throwUnexpected();
  15946. }
  15947. private:
  15948. const void * nextInGroupJoin()
  15949. {
  15950. if(!table)
  15951. loadRight();
  15952. while(true)
  15953. {
  15954. const void * right = NULL;
  15955. if(!left)
  15956. {
  15957. left = input->nextInGroup();
  15958. keepCount = keepLimit;
  15959. joinCounter = 0;
  15960. if(!left)
  15961. {
  15962. if (isSmartJoin)
  15963. left = input->nextInGroup();
  15964. if (!left)
  15965. {
  15966. if(matchedGroup || eog)
  15967. {
  15968. matchedGroup = false;
  15969. eog = true;
  15970. return NULL;
  15971. }
  15972. eog = true;
  15973. continue;
  15974. }
  15975. }
  15976. eog = false;
  15977. gotMatch = false;
  15978. right = getRightFirst();
  15979. }
  15980. else
  15981. right = getRightNext();
  15982. const void * ret = NULL;
  15983. if(failingLimit)
  15984. {
  15985. ret = joinException(left, failingLimit);
  15986. }
  15987. else
  15988. {
  15989. while(right)
  15990. {
  15991. if(helper.match(left, right))
  15992. {
  15993. gotMatch = true;
  15994. if(exclude)
  15995. break;
  15996. ret = joinRecords(left, right, ++joinCounter);
  15997. if(ret)
  15998. break;
  15999. }
  16000. right = getRightNext();
  16001. ret = NULL;
  16002. }
  16003. if(leftOuterJoin && !gotMatch)
  16004. {
  16005. ret = joinRecords(left, defaultRight, 0);
  16006. gotMatch = true;
  16007. }
  16008. }
  16009. if(ret)
  16010. {
  16011. matchedGroup = true;
  16012. processed++;
  16013. if(!many || (--keepCount == 0) || failingLimit)
  16014. {
  16015. ReleaseClearRoxieRow(left);
  16016. failingLimit.clear();
  16017. }
  16018. return ret;
  16019. }
  16020. ReleaseClearRoxieRow(left);
  16021. }
  16022. }
  16023. const void * nextInGroupDenormalize()
  16024. {
  16025. while(true)
  16026. {
  16027. left = input->nextInGroup();
  16028. if(!left)
  16029. {
  16030. if (!matchedGroup || isSmartJoin)
  16031. left = input->nextInGroup();
  16032. if (!left)
  16033. {
  16034. matchedGroup = false;
  16035. return NULL;
  16036. }
  16037. }
  16038. gotMatch = false;
  16039. const void * right = getRightFirst();
  16040. const void * ret = NULL;
  16041. if (failingLimit)
  16042. ret = joinException(left, failingLimit);
  16043. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16044. {
  16045. OwnedConstRoxieRow newLeft;
  16046. newLeft.set(left);
  16047. unsigned rowSize = 0;
  16048. unsigned leftCount = 0;
  16049. keepCount = keepLimit;
  16050. while (right)
  16051. {
  16052. try
  16053. {
  16054. if (helper.match(left, right))
  16055. {
  16056. gotMatch = true;
  16057. if (exclude)
  16058. break;
  16059. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16060. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16061. if (thisSize)
  16062. {
  16063. rowSize = thisSize;
  16064. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16065. }
  16066. if(!many || (--keepCount == 0))
  16067. break;
  16068. }
  16069. right = getRightNext();
  16070. }
  16071. catch (IException *E)
  16072. {
  16073. throw makeWrappedException(E);
  16074. }
  16075. }
  16076. if (rowSize)
  16077. ret = newLeft.getClear();
  16078. else if (leftOuterJoin && !gotMatch)
  16079. {
  16080. ret = left;
  16081. left = NULL;
  16082. }
  16083. }
  16084. else
  16085. {
  16086. filteredRight.kill();
  16087. keepCount = keepLimit;
  16088. while (right)
  16089. {
  16090. if (helper.match(left, right))
  16091. {
  16092. gotMatch = true;
  16093. if(exclude)
  16094. break;
  16095. filteredRight.append(right);
  16096. if(!many || (--keepCount == 0))
  16097. break;
  16098. }
  16099. right = getRightNext();
  16100. }
  16101. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16102. ret = denormalizeRecords(left, filteredRight);
  16103. filteredRight.kill();
  16104. }
  16105. ReleaseRoxieRow(left);
  16106. left = NULL;
  16107. failingLimit.clear();
  16108. if(ret)
  16109. {
  16110. matchedGroup = true;
  16111. processed++;
  16112. return ret;
  16113. }
  16114. }
  16115. }
  16116. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16117. {
  16118. if (cloneLeft)
  16119. {
  16120. LinkRoxieRow(left);
  16121. return left;
  16122. }
  16123. try
  16124. {
  16125. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16126. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16127. if (outSize)
  16128. return rowBuilder.finalizeRowClear(outSize);
  16129. else
  16130. return NULL;
  16131. }
  16132. catch (IException *E)
  16133. {
  16134. throw makeWrappedException(E);
  16135. }
  16136. }
  16137. const void * joinException(const void * left, IException * except)
  16138. {
  16139. try
  16140. {
  16141. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16142. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16143. if (outSize)
  16144. return rowBuilder.finalizeRowClear(outSize);
  16145. else
  16146. return NULL;
  16147. }
  16148. catch (IException *E)
  16149. {
  16150. throw makeWrappedException(E);
  16151. }
  16152. }
  16153. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16154. {
  16155. try
  16156. {
  16157. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16158. unsigned numRows = rows.ordinality();
  16159. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16160. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16161. if (outSize)
  16162. return rowBuilder.finalizeRowClear(outSize);
  16163. else
  16164. return NULL;
  16165. }
  16166. catch (IException *E)
  16167. {
  16168. throw makeWrappedException(E);
  16169. }
  16170. }
  16171. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16172. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16173. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16174. const void *fillRightGroup()
  16175. {
  16176. rightGroup.kill();
  16177. for(const void * right = table->find(left); right; right = table->findNext(left))
  16178. {
  16179. rightGroup.append(right);
  16180. if(rightGroup.ordinality() > limitLimit)
  16181. {
  16182. if(limitFail)
  16183. failLimit();
  16184. gotMatch = true;
  16185. if (ctx->queryDebugContext())
  16186. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16187. if(limitOnFail)
  16188. {
  16189. assertex(!failingLimit);
  16190. try
  16191. {
  16192. failLimit();
  16193. }
  16194. catch(IException * e)
  16195. {
  16196. failingLimit.setown(e);
  16197. }
  16198. assertex(failingLimit != NULL);
  16199. }
  16200. else
  16201. {
  16202. rightGroup.kill();
  16203. }
  16204. break;
  16205. }
  16206. if(rightGroup.ordinality() > atmostLimit)
  16207. {
  16208. atmostsTriggered++;
  16209. rightGroup.kill();
  16210. break;
  16211. }
  16212. }
  16213. rightGroupIndex = 0;
  16214. return readRightGroup();
  16215. }
  16216. void failLimit()
  16217. {
  16218. helper.onMatchAbortLimitExceeded();
  16219. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16220. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16221. {
  16222. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16223. }
  16224. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16225. }
  16226. };
  16227. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16228. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16229. {
  16230. public:
  16231. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16232. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16233. {
  16234. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16235. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16236. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16237. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16238. }
  16239. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16240. {
  16241. return new CRoxieServerLookupJoinActivity(this, _probeManager, useFewTable);
  16242. }
  16243. virtual const StatisticsMapping &queryStatsMapping() const
  16244. {
  16245. return joinStatistics;
  16246. }
  16247. protected:
  16248. bool useFewTable;
  16249. };
  16250. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16251. {
  16252. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16253. }
  16254. //=====================================================================================================
  16255. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16256. {
  16257. private:
  16258. IHThorAllJoinArg &helper;
  16259. bool leftOuterJoin;
  16260. bool rightOuterJoin;
  16261. bool exclude;
  16262. OwnedConstRoxieRow defaultRight;
  16263. OwnedConstRoxieRow defaultLeft;
  16264. Owned<IEngineRowAllocator> defaultRightAllocator;
  16265. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16266. const void *left;
  16267. unsigned countForLeft;
  16268. ConstPointerArray rightset;
  16269. BoolArray matchedRight; // MORE - could use a bitset...
  16270. unsigned keepLimit;
  16271. bool started;
  16272. bool eog;
  16273. bool eos;
  16274. bool matchedLeft;
  16275. bool matchedGroup;
  16276. bool leftIsGrouped;
  16277. bool cloneLeft;
  16278. unsigned rightIndex;
  16279. unsigned joinCounter;
  16280. unsigned rightOrdinality;
  16281. ThorActivityKind activityKind;
  16282. ConstPointerArray filteredRight;
  16283. void createDefaultLeft()
  16284. {
  16285. if (!defaultLeft)
  16286. {
  16287. if (!defaultLeftAllocator)
  16288. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  16289. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16290. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16291. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16292. }
  16293. }
  16294. void createDefaultRight()
  16295. {
  16296. if (!defaultRight)
  16297. {
  16298. if (!defaultRightAllocator)
  16299. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  16300. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16301. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16302. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16303. }
  16304. }
  16305. public:
  16306. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16307. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16308. {
  16309. unsigned joinFlags = helper.getJoinFlags();
  16310. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16311. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16312. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16313. keepLimit = (unsigned) -1;
  16314. exclude = (joinFlags & JFexclude) != 0;
  16315. left = NULL;
  16316. started = true;
  16317. eog = false;
  16318. eos = false;
  16319. matchedLeft = false;
  16320. matchedGroup = false;
  16321. activityKind = factory->getKind();
  16322. rightIndex = 0;
  16323. rightOrdinality = 0;
  16324. leftIsGrouped = false;
  16325. countForLeft = 0;
  16326. joinCounter = 0;
  16327. }
  16328. virtual void reset()
  16329. {
  16330. defaultRight.clear();
  16331. defaultLeft.clear();
  16332. ReleaseRoxieRowSet(rightset);
  16333. matchedRight.kill();
  16334. CRoxieServerTwoInputActivity::reset();
  16335. }
  16336. virtual bool needsAllocator() const { return true; }
  16337. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16338. {
  16339. eog = false;
  16340. eos = false;
  16341. matchedLeft = false;
  16342. matchedGroup = false;
  16343. started = false;
  16344. left = NULL;
  16345. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16346. keepLimit = helper.getKeepLimit();
  16347. if(keepLimit==0)
  16348. keepLimit = (unsigned) -1;
  16349. countForLeft = keepLimit;
  16350. joinCounter = 0;
  16351. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16352. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16353. createDefaultRight();
  16354. if(rightOuterJoin)
  16355. createDefaultLeft();
  16356. }
  16357. void loadRight()
  16358. {
  16359. const void * next;
  16360. while(true)
  16361. {
  16362. next = input1->nextInGroup();
  16363. if(!next)
  16364. next = input1->nextInGroup();
  16365. if(!next)
  16366. break;
  16367. rightset.append(next);
  16368. matchedRight.append(false);
  16369. }
  16370. rightIndex = 0;
  16371. joinCounter = 0;
  16372. rightOrdinality = rightset.ordinality();
  16373. }
  16374. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16375. {
  16376. if (idx==1)
  16377. input1 = _in;
  16378. else
  16379. {
  16380. if ((helper.getJoinFlags() & JFparallel) != 0)
  16381. {
  16382. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  16383. puller->setInput(0, _in);
  16384. _in = puller;
  16385. }
  16386. CRoxieServerActivity::setInput(idx, _in);
  16387. }
  16388. }
  16389. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16390. {
  16391. // MORE - could share some code with lookup join
  16392. if (cloneLeft)
  16393. {
  16394. LinkRoxieRow(left);
  16395. return left;
  16396. }
  16397. try
  16398. {
  16399. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16400. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16401. if (outSize)
  16402. return rowBuilder.finalizeRowClear(outSize);
  16403. else
  16404. return NULL;
  16405. }
  16406. catch (IException *E)
  16407. {
  16408. throw makeWrappedException(E);
  16409. }
  16410. }
  16411. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  16412. {
  16413. try
  16414. {
  16415. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16416. unsigned numRows = rows.ordinality();
  16417. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16418. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  16419. if (outSize)
  16420. return rowBuilder.finalizeRowClear(outSize);
  16421. else
  16422. return NULL;
  16423. }
  16424. catch (IException *E)
  16425. {
  16426. throw makeWrappedException(E);
  16427. }
  16428. }
  16429. virtual const void *nextInGroup()
  16430. {
  16431. ActivityTimer t(totalCycles, timeActivities);
  16432. if(!started)
  16433. {
  16434. started = true;
  16435. left = input->nextInGroup();
  16436. matchedLeft = false;
  16437. countForLeft = keepLimit;
  16438. joinCounter = 0;
  16439. if(left == NULL)
  16440. {
  16441. eos = true;
  16442. return NULL;
  16443. }
  16444. loadRight();
  16445. }
  16446. const void * ret;
  16447. const void * right;
  16448. if(eos)
  16449. return NULL;
  16450. while(true)
  16451. {
  16452. ret = NULL;
  16453. if((rightIndex == rightOrdinality) || (countForLeft==0))
  16454. {
  16455. if(leftOuterJoin && left && !matchedLeft)
  16456. {
  16457. switch(activityKind)
  16458. {
  16459. case TAKalljoin:
  16460. ret = joinRecords(left, defaultRight, 0);
  16461. break;
  16462. case TAKalldenormalize:
  16463. ret = left;
  16464. left = NULL;
  16465. break;
  16466. case TAKalldenormalizegroup:
  16467. filteredRight.kill();
  16468. ret = denormalizeRecords(left, filteredRight);
  16469. break;
  16470. default:
  16471. throwUnexpected();
  16472. }
  16473. }
  16474. rightIndex = 0;
  16475. joinCounter = 0;
  16476. ReleaseRoxieRow(left);
  16477. left = NULL;
  16478. if(ret)
  16479. {
  16480. matchedGroup = true;
  16481. processed++;
  16482. return ret;
  16483. }
  16484. }
  16485. if(!left)
  16486. {
  16487. left = input->nextInGroup();
  16488. matchedLeft = false;
  16489. countForLeft = keepLimit;
  16490. joinCounter = 0;
  16491. }
  16492. if(!left)
  16493. {
  16494. if(eog)
  16495. {
  16496. eos = true;
  16497. matchedGroup = false;
  16498. return NULL;
  16499. }
  16500. eog = true;
  16501. if (matchedGroup && leftIsGrouped)
  16502. {
  16503. matchedGroup = false;
  16504. return NULL;
  16505. }
  16506. matchedGroup = false;
  16507. continue;
  16508. }
  16509. eog = false;
  16510. switch(activityKind)
  16511. {
  16512. case TAKalljoin:
  16513. while(rightIndex < rightOrdinality)
  16514. {
  16515. right = rightset.item(rightIndex);
  16516. if(helper.match(left, right))
  16517. {
  16518. matchedLeft = true;
  16519. matchedRight.replace(true, rightIndex);
  16520. if(!exclude)
  16521. ret = joinRecords(left, right, ++joinCounter);
  16522. }
  16523. rightIndex++;
  16524. if(ret)
  16525. {
  16526. countForLeft--;
  16527. matchedGroup = true;
  16528. processed++;
  16529. return ret;
  16530. }
  16531. }
  16532. break;
  16533. case TAKalldenormalize:
  16534. {
  16535. OwnedConstRoxieRow newLeft;
  16536. newLeft.set(left);
  16537. unsigned rowSize = 0;
  16538. unsigned leftCount = 0;
  16539. while((rightIndex < rightOrdinality) && countForLeft)
  16540. {
  16541. right = rightset.item(rightIndex);
  16542. if(helper.match(left, right))
  16543. {
  16544. matchedLeft = true;
  16545. matchedRight.replace(true, rightIndex);
  16546. if(!exclude)
  16547. {
  16548. try
  16549. {
  16550. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16551. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16552. if(thisSize)
  16553. {
  16554. rowSize = thisSize;
  16555. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16556. --countForLeft;
  16557. }
  16558. }
  16559. catch (IException *e)
  16560. {
  16561. throw makeWrappedException(e);
  16562. }
  16563. }
  16564. }
  16565. rightIndex++;
  16566. }
  16567. if(rowSize)
  16568. {
  16569. processed++;
  16570. return newLeft.getClear();
  16571. }
  16572. }
  16573. break;
  16574. case TAKalldenormalizegroup:
  16575. filteredRight.kill();
  16576. while((rightIndex < rightOrdinality) && countForLeft)
  16577. {
  16578. right = rightset.item(rightIndex);
  16579. if(helper.match(left, right))
  16580. {
  16581. matchedLeft = true;
  16582. matchedRight.replace(true, rightIndex);
  16583. filteredRight.append(right);
  16584. --countForLeft;
  16585. }
  16586. ++rightIndex;
  16587. }
  16588. if(!exclude && filteredRight.ordinality())
  16589. {
  16590. ret = denormalizeRecords(left, filteredRight);
  16591. filteredRight.kill();
  16592. if(ret)
  16593. {
  16594. processed++;
  16595. return ret;
  16596. }
  16597. }
  16598. break;
  16599. default:
  16600. throwUnexpected();
  16601. }
  16602. }
  16603. }
  16604. };
  16605. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16606. {
  16607. public:
  16608. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16609. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16610. {
  16611. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16612. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16613. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16614. }
  16615. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16616. {
  16617. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16618. }
  16619. virtual const StatisticsMapping &queryStatsMapping() const
  16620. {
  16621. return joinStatistics;
  16622. }
  16623. };
  16624. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16625. {
  16626. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16627. }
  16628. //=====================================================================================================
  16629. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16630. {
  16631. unsigned limit;
  16632. bool hasBest;
  16633. bool eoi;
  16634. const void **sorted;
  16635. unsigned sortedCount;
  16636. unsigned curIndex;
  16637. IHThorTopNArg &helper;
  16638. ICompare &compare;
  16639. public:
  16640. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16641. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16642. {
  16643. sorted = NULL;
  16644. sortedCount = 0;
  16645. curIndex = 0;
  16646. limit = 0;
  16647. eoi = false;
  16648. hasBest = false;
  16649. }
  16650. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16651. {
  16652. assertex(sorted == NULL);
  16653. sortedCount = 0;
  16654. curIndex = 0;
  16655. eoi = false;
  16656. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16657. limit = (unsigned) helper.getLimit();
  16658. hasBest = helper.hasBest();
  16659. lateStart(parentExtractSize, parentExtract, limit > 0);
  16660. // MORE - should we use an expanding array instead?
  16661. if (limit > 0)
  16662. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16663. }
  16664. virtual void reset()
  16665. {
  16666. if (sorted)
  16667. {
  16668. while(curIndex < sortedCount)
  16669. ReleaseRoxieRow(sorted[curIndex++]);
  16670. ReleaseRoxieRow(sorted);
  16671. }
  16672. sorted = NULL;
  16673. CRoxieServerLateStartActivity::reset();
  16674. }
  16675. bool abortEarly()
  16676. {
  16677. if (hasBest && (sortedCount == limit))
  16678. {
  16679. int compare = helper.compareBest(sorted[sortedCount-1]);
  16680. if (compare == 0)
  16681. {
  16682. if (meta.isGrouped())
  16683. {
  16684. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16685. const void * next;
  16686. while ((next = input->nextInGroup()) != NULL)
  16687. ReleaseRoxieRow(next);
  16688. }
  16689. else
  16690. eoi = true;
  16691. return true;
  16692. }
  16693. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16694. if (compare < 0)
  16695. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16696. }
  16697. return false;
  16698. }
  16699. void getSorted()
  16700. {
  16701. curIndex = 0;
  16702. sortedCount = 0;
  16703. if(eoi)
  16704. return;
  16705. const void * next;
  16706. while ((next = input->nextInGroup()) != NULL)
  16707. {
  16708. if (sortedCount < limit)
  16709. {
  16710. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16711. sortedCount++;
  16712. if(abortEarly())
  16713. return;
  16714. }
  16715. else
  16716. {
  16717. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16718. {
  16719. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16720. ReleaseRoxieRow(sorted[sortedCount]);
  16721. if(abortEarly())
  16722. return;
  16723. }
  16724. else
  16725. {
  16726. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16727. }
  16728. }
  16729. }
  16730. }
  16731. virtual const void * nextInGroup()
  16732. {
  16733. ActivityTimer t(totalCycles, timeActivities);
  16734. if (eof)
  16735. return NULL;
  16736. if (curIndex >= sortedCount)
  16737. {
  16738. bool eog = sortedCount != 0;
  16739. getSorted();
  16740. if(sortedCount == 0)
  16741. {
  16742. eof = true;
  16743. return NULL;
  16744. }
  16745. if (eog)
  16746. return NULL;
  16747. }
  16748. processed++;
  16749. return sorted[curIndex++];
  16750. }
  16751. };
  16752. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16753. {
  16754. public:
  16755. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16756. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16757. {
  16758. }
  16759. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16760. {
  16761. return new CRoxieServerTopNActivity(this, _probeManager);
  16762. }
  16763. };
  16764. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16765. {
  16766. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16767. }
  16768. //=================================================================================
  16769. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16770. {
  16771. protected:
  16772. unsigned __int64 rowLimit;
  16773. IHThorLimitArg &helper;
  16774. public:
  16775. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16776. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16777. {
  16778. rowLimit = 0;
  16779. }
  16780. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16781. {
  16782. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16783. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16784. }
  16785. virtual const void *nextInGroup()
  16786. {
  16787. ActivityTimer t(totalCycles, timeActivities);
  16788. const void * ret = input->nextInGroup();
  16789. if (ret)
  16790. {
  16791. processed++;
  16792. if (processed > rowLimit)
  16793. {
  16794. ReleaseRoxieRow(ret);
  16795. if (traceLevel > 4)
  16796. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16797. helper.onLimitExceeded();
  16798. }
  16799. }
  16800. return ret;
  16801. }
  16802. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16803. {
  16804. ActivityTimer t(totalCycles, timeActivities);
  16805. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16806. if (ret)
  16807. {
  16808. if (wasCompleteMatch)
  16809. processed++;
  16810. if (processed > rowLimit)
  16811. {
  16812. ReleaseRoxieRow(ret);
  16813. if (traceLevel > 4)
  16814. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16815. helper.onLimitExceeded();
  16816. }
  16817. }
  16818. return ret;
  16819. }
  16820. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16821. {
  16822. return input->gatherConjunctions(collector);
  16823. }
  16824. virtual void resetEOF()
  16825. {
  16826. //Do not reset the rowLimit
  16827. input->resetEOF();
  16828. }
  16829. IInputSteppingMeta * querySteppingMeta()
  16830. {
  16831. return input->querySteppingMeta();
  16832. }
  16833. };
  16834. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16835. {
  16836. public:
  16837. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16838. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16839. {
  16840. }
  16841. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16842. {
  16843. return new CRoxieServerLimitActivity(this, _probeManager);
  16844. }
  16845. };
  16846. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16847. {
  16848. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16849. }
  16850. //=====================================================================================================
  16851. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16852. {
  16853. ConstPointerArray buff;
  16854. bool started;
  16855. unsigned index;
  16856. IHThorLimitTransformExtra * transformExtra;
  16857. public:
  16858. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16859. : CRoxieServerLimitActivity(_factory, _probeManager)
  16860. {
  16861. transformExtra = NULL;
  16862. started = false;
  16863. index = 0;
  16864. if (_onFail)
  16865. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16866. }
  16867. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16868. {
  16869. started = false;
  16870. index = 0;
  16871. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16872. }
  16873. virtual void reset()
  16874. {
  16875. while (buff.isItem(index))
  16876. ReleaseRoxieRow(buff.item(index++));
  16877. buff.kill();
  16878. started = false;
  16879. CRoxieServerLimitActivity::reset();
  16880. }
  16881. virtual const void *nextInGroup()
  16882. {
  16883. ActivityTimer t(totalCycles, timeActivities);
  16884. if (!started)
  16885. pullInput();
  16886. if (buff.isItem(index))
  16887. {
  16888. const void * next = buff.item(index++);
  16889. if(next)
  16890. processed++;
  16891. return next;
  16892. }
  16893. return NULL;
  16894. }
  16895. protected:
  16896. void pullInput()
  16897. {
  16898. unsigned count = 0;
  16899. loop
  16900. {
  16901. const void * next = input->nextInGroup();
  16902. if (next == NULL)
  16903. {
  16904. next = input->nextInGroup();
  16905. if(next == NULL)
  16906. break;
  16907. buff.append(NULL);
  16908. }
  16909. count++;
  16910. if (count > rowLimit)
  16911. {
  16912. ReleaseRoxieRow(next);
  16913. ReleaseRoxieRowSet(buff);
  16914. if (ctx->queryDebugContext())
  16915. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16916. if (transformExtra)
  16917. {
  16918. createRowAllocator();
  16919. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16920. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16921. if (outSize)
  16922. buff.append(rowBuilder.finalizeRowClear(outSize));
  16923. }
  16924. break;
  16925. }
  16926. buff.append(next);
  16927. }
  16928. started = true;
  16929. }
  16930. };
  16931. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16932. {
  16933. public:
  16934. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16935. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16936. {
  16937. }
  16938. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16939. {
  16940. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16941. }
  16942. };
  16943. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16944. {
  16945. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16946. }
  16947. //=================================================================================
  16948. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16949. {
  16950. IHThorCatchArg &helper;
  16951. public:
  16952. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16953. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16954. {
  16955. }
  16956. virtual const void *nextInGroup()
  16957. {
  16958. ActivityTimer t(totalCycles, timeActivities);
  16959. try
  16960. {
  16961. const void *ret = input->nextInGroup();
  16962. if (ret)
  16963. processed++;
  16964. return ret;
  16965. }
  16966. catch (IException *E)
  16967. {
  16968. E->Release();
  16969. helper.onExceptionCaught();
  16970. }
  16971. catch (...)
  16972. {
  16973. helper.onExceptionCaught();
  16974. }
  16975. throwUnexpected(); // onExceptionCaught should have thrown something
  16976. }
  16977. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16978. {
  16979. try
  16980. {
  16981. ActivityTimer t(totalCycles, timeActivities);
  16982. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16983. if (ret && wasCompleteMatch)
  16984. processed++;
  16985. return ret;
  16986. }
  16987. catch (IException *E)
  16988. {
  16989. E->Release();
  16990. helper.onExceptionCaught();
  16991. }
  16992. catch (...)
  16993. {
  16994. helper.onExceptionCaught();
  16995. }
  16996. throwUnexpected(); // onExceptionCaught should have thrown something
  16997. }
  16998. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16999. {
  17000. return input->gatherConjunctions(collector);
  17001. }
  17002. virtual void resetEOF()
  17003. {
  17004. input->resetEOF(); // MORE - why not in base class?
  17005. }
  17006. IInputSteppingMeta * querySteppingMeta()
  17007. {
  17008. return input->querySteppingMeta();
  17009. }
  17010. };
  17011. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17012. {
  17013. ConstPointerArray buff;
  17014. bool started;
  17015. unsigned index;
  17016. IHThorCatchArg &helper;
  17017. bool createRow;
  17018. public:
  17019. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17020. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17021. {
  17022. started = false;
  17023. index = 0;
  17024. }
  17025. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17026. {
  17027. started = false;
  17028. index = 0;
  17029. try
  17030. {
  17031. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17032. }
  17033. catch (IException *E)
  17034. {
  17035. onException(E);
  17036. started = true;
  17037. }
  17038. catch (...)
  17039. {
  17040. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17041. started = true;
  17042. }
  17043. }
  17044. virtual void reset()
  17045. {
  17046. while (buff.isItem(index))
  17047. ReleaseRoxieRow(buff.item(index++));
  17048. buff.kill();
  17049. started = false;
  17050. CRoxieServerActivity::reset();
  17051. }
  17052. virtual const void *nextInGroup()
  17053. {
  17054. ActivityTimer t(totalCycles, timeActivities);
  17055. if (!started)
  17056. pullInput();
  17057. if (buff.isItem(index))
  17058. {
  17059. const void * next = buff.item(index++);
  17060. if(next)
  17061. processed++;
  17062. return next;
  17063. }
  17064. return NULL;
  17065. }
  17066. protected:
  17067. void onException(IException *E)
  17068. {
  17069. input->stop(true);
  17070. ReleaseRoxieRowSet(buff);
  17071. if (createRow)
  17072. {
  17073. createRowAllocator();
  17074. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17075. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17076. if (outSize)
  17077. buff.append(rowBuilder.finalizeRowClear(outSize));
  17078. }
  17079. E->Release();
  17080. }
  17081. void pullInput()
  17082. {
  17083. try
  17084. {
  17085. bool EOGseen = false;
  17086. loop
  17087. {
  17088. const void * next = input->nextInGroup();
  17089. buff.append(next);
  17090. if (next == NULL)
  17091. {
  17092. if (EOGseen)
  17093. break;
  17094. EOGseen = true;
  17095. }
  17096. else
  17097. EOGseen = false;
  17098. }
  17099. }
  17100. catch (IException *E)
  17101. {
  17102. onException(E);
  17103. }
  17104. catch (...)
  17105. {
  17106. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17107. }
  17108. started = true;
  17109. }
  17110. };
  17111. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17112. {
  17113. public:
  17114. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17115. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17116. {
  17117. }
  17118. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17119. {
  17120. switch (kind)
  17121. {
  17122. case TAKcatch:
  17123. return new CRoxieServerCatchActivity(this, _probeManager);
  17124. case TAKskipcatch:
  17125. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  17126. case TAKcreaterowcatch:
  17127. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  17128. default:
  17129. throwUnexpected();
  17130. }
  17131. }
  17132. };
  17133. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17134. {
  17135. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17136. }
  17137. //=================================================================================
  17138. class CRoxieServerCaseActivity : public CRoxieServerActivity
  17139. {
  17140. IHThorCaseArg &helper;
  17141. IRoxieInput **inputs;
  17142. unsigned cond;
  17143. bool unusedStopped;
  17144. IRoxieInput *in;
  17145. unsigned numInputs;
  17146. public:
  17147. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17148. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  17149. {
  17150. unusedStopped = false;
  17151. cond = 0;
  17152. inputs = new IRoxieInput*[numInputs];
  17153. for (unsigned i = 0; i < numInputs; i++)
  17154. inputs[i] = NULL;
  17155. in = NULL;
  17156. }
  17157. ~CRoxieServerCaseActivity()
  17158. {
  17159. delete [] inputs;
  17160. }
  17161. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17162. {
  17163. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17164. cond = helper.getBranch();
  17165. //CHOOSE defaults to the last argument if out of range.
  17166. if (cond >= numInputs)
  17167. cond = numInputs - 1;
  17168. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  17169. for (unsigned idx = 0; idx < numInputs; idx++)
  17170. {
  17171. if (idx!=cond)
  17172. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17173. }
  17174. in = inputs[cond];
  17175. unusedStopped = true;
  17176. }
  17177. virtual void stop(bool aborting)
  17178. {
  17179. for (unsigned idx = 0; idx < numInputs; idx++)
  17180. {
  17181. if (idx==cond || !unusedStopped)
  17182. inputs[idx]->stop(aborting);
  17183. }
  17184. CRoxieServerActivity::stop(aborting);
  17185. }
  17186. virtual void reset()
  17187. {
  17188. for (unsigned idx = 0; idx < numInputs; idx++)
  17189. {
  17190. inputs[idx]->reset();
  17191. }
  17192. unusedStopped = false;
  17193. in = NULL;
  17194. CRoxieServerActivity::reset();
  17195. }
  17196. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17197. {
  17198. assertex(idx < numInputs);
  17199. inputs[idx] = _in;
  17200. }
  17201. virtual const void *nextInGroup()
  17202. {
  17203. ActivityTimer t(totalCycles, timeActivities);
  17204. if (in)
  17205. {
  17206. const void *ret = in->nextInGroup();
  17207. if (ret)
  17208. processed++;
  17209. return ret;
  17210. }
  17211. return NULL;
  17212. }
  17213. };
  17214. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17215. {
  17216. bool graphInvariant;
  17217. public:
  17218. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17219. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17220. {
  17221. graphInvariant = _graphInvariant;
  17222. }
  17223. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17224. {
  17225. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  17226. }
  17227. virtual bool isGraphInvariant() const
  17228. {
  17229. return graphInvariant;
  17230. }
  17231. };
  17232. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17233. {
  17234. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17235. }
  17236. //=================================================================================
  17237. class CRoxieServerIfActivity : public CRoxieServerActivity
  17238. {
  17239. IHThorIfArg &helper;
  17240. IRoxieInput *inputTrue;
  17241. IRoxieInput *inputFalse;
  17242. bool cond;
  17243. bool unusedStopped;
  17244. public:
  17245. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17246. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17247. {
  17248. inputFalse = NULL;
  17249. inputTrue = NULL;
  17250. unusedStopped = false;
  17251. cond = false;
  17252. }
  17253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17254. {
  17255. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17256. cond = helper.getCondition();
  17257. if (cond)
  17258. {
  17259. inputTrue->start(parentExtractSize, parentExtract, paused);
  17260. if (inputFalse)
  17261. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17262. }
  17263. else
  17264. {
  17265. if (inputFalse)
  17266. inputFalse->start(parentExtractSize, parentExtract, paused);
  17267. inputTrue->stop(false);
  17268. }
  17269. unusedStopped = true;
  17270. }
  17271. virtual void stop(bool aborting)
  17272. {
  17273. if (!unusedStopped || cond)
  17274. inputTrue->stop(aborting);
  17275. if (inputFalse && (!unusedStopped || !cond))
  17276. inputFalse->stop(aborting);
  17277. CRoxieServerActivity::stop(aborting);
  17278. }
  17279. virtual unsigned __int64 queryLocalCycles() const
  17280. {
  17281. __int64 localCycles = totalCycles.totalCycles;
  17282. localCycles -= inputTrue->queryTotalCycles();
  17283. if (inputFalse)
  17284. localCycles -= inputFalse->queryTotalCycles();
  17285. if (localCycles < 0)
  17286. localCycles = 0;
  17287. return localCycles;
  17288. }
  17289. virtual IRoxieInput *queryInput(unsigned idx) const
  17290. {
  17291. switch (idx)
  17292. {
  17293. case 0:
  17294. return inputTrue;
  17295. case 1:
  17296. return inputFalse;
  17297. default:
  17298. return NULL;
  17299. }
  17300. }
  17301. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  17302. {
  17303. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17304. if (in)
  17305. return in->queryIndexReadActivity();
  17306. return NULL;
  17307. }
  17308. virtual void reset()
  17309. {
  17310. CRoxieServerActivity::reset();
  17311. inputTrue->reset();
  17312. if (inputFalse)
  17313. inputFalse->reset();
  17314. unusedStopped = false;
  17315. }
  17316. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17317. {
  17318. if (idx==1)
  17319. inputFalse = _in;
  17320. else
  17321. {
  17322. assertex(!idx);
  17323. inputTrue = _in;
  17324. }
  17325. }
  17326. virtual const void *nextInGroup()
  17327. {
  17328. ActivityTimer t(totalCycles, timeActivities);
  17329. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17330. if (in)
  17331. {
  17332. const void * ret;
  17333. if ((ret = in->nextInGroup()) != NULL)
  17334. processed++;
  17335. return ret;
  17336. }
  17337. return NULL;
  17338. }
  17339. };
  17340. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  17341. {
  17342. unsigned input2;
  17343. unsigned input2idx;
  17344. bool graphInvariant;
  17345. public:
  17346. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17347. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17348. {
  17349. graphInvariant = _graphInvariant;
  17350. input2 = (unsigned)-1;
  17351. input2idx = (unsigned)-1;
  17352. }
  17353. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17354. {
  17355. return new CRoxieServerIfActivity(this, _probeManager);
  17356. }
  17357. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  17358. {
  17359. if (idx==1)
  17360. {
  17361. input2 = source;
  17362. input2idx = sourceidx;
  17363. }
  17364. else
  17365. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  17366. }
  17367. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  17368. {
  17369. switch (idx)
  17370. {
  17371. case 1:
  17372. sourceidx = input2idx;
  17373. return input2;
  17374. case 0:
  17375. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  17376. default:
  17377. return (unsigned) -1;
  17378. }
  17379. }
  17380. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  17381. virtual bool isGraphInvariant() const
  17382. {
  17383. return graphInvariant;
  17384. }
  17385. };
  17386. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17387. {
  17388. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17389. }
  17390. //=================================================================================
  17391. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  17392. {
  17393. CriticalSection ecrit;
  17394. Owned<IException> exception;
  17395. bool executed;
  17396. public:
  17397. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17398. : CRoxieServerActivity(_factory, _probeManager)
  17399. {
  17400. executed = false;
  17401. }
  17402. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  17403. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  17404. {
  17405. CriticalBlock b(ecrit);
  17406. if (exception)
  17407. throw(exception.getLink());
  17408. if (!executed)
  17409. {
  17410. try
  17411. {
  17412. executed = true;
  17413. start(parentExtractSize, parentExtract, false);
  17414. doExecuteAction(parentExtractSize, parentExtract);
  17415. stop(false);
  17416. }
  17417. catch (IException * E)
  17418. {
  17419. ctx->notifyAbort(E);
  17420. stop(true);
  17421. exception.set(E);
  17422. throw;
  17423. }
  17424. }
  17425. }
  17426. virtual void reset()
  17427. {
  17428. executed = false;
  17429. exception.clear();
  17430. CRoxieServerActivity::reset();
  17431. }
  17432. virtual const void *nextInGroup()
  17433. {
  17434. throwUnexpected(); // I am nobody's input
  17435. }
  17436. virtual IRoxieInput *queryInput(unsigned idx) const
  17437. {
  17438. throwUnexpected(); // I am nobody's input
  17439. }
  17440. };
  17441. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  17442. {
  17443. IHThorIfArg &helper;
  17444. public:
  17445. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17446. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17447. {
  17448. }
  17449. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17450. {
  17451. bool cond;
  17452. {
  17453. ActivityTimer t(totalCycles, timeActivities);
  17454. cond = helper.getCondition();
  17455. }
  17456. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  17457. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  17458. }
  17459. };
  17460. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  17461. {
  17462. bool isRoot;
  17463. public:
  17464. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17465. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17466. {
  17467. }
  17468. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17469. {
  17470. return new CRoxieServerIfActionActivity(this, _probeManager);
  17471. }
  17472. virtual bool isSink() const
  17473. {
  17474. return isRoot;
  17475. }
  17476. };
  17477. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17478. {
  17479. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17480. }
  17481. //=================================================================================
  17482. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  17483. {
  17484. public:
  17485. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17486. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17487. {
  17488. }
  17489. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17490. {
  17491. #ifdef PARALLEL_EXECUTE
  17492. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  17493. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  17494. #else
  17495. ForEachItemIn(idx, dependencies)
  17496. {
  17497. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  17498. }
  17499. #endif
  17500. }
  17501. };
  17502. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  17503. {
  17504. bool isRoot;
  17505. public:
  17506. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17507. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17508. {
  17509. assertex(!isRoot); // non-internal should be expanded out..
  17510. }
  17511. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17512. {
  17513. return new CRoxieServerParallelActionActivity(this, _probeManager);
  17514. }
  17515. virtual bool isSink() const
  17516. {
  17517. return isRoot;
  17518. }
  17519. };
  17520. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17521. {
  17522. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17523. }
  17524. //=================================================================================
  17525. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  17526. {
  17527. IHThorSequentialArg &helper;
  17528. public:
  17529. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17530. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  17531. {
  17532. }
  17533. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17534. {
  17535. unsigned numBranches = helper.numBranches();
  17536. for (unsigned branch=1; branch <= numBranches; branch++)
  17537. executeDependencies(parentExtractSize, parentExtract, branch);
  17538. }
  17539. };
  17540. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  17541. {
  17542. bool isRoot;
  17543. public:
  17544. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17545. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17546. {
  17547. }
  17548. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17549. {
  17550. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  17551. }
  17552. virtual bool isSink() const
  17553. {
  17554. return isRoot;
  17555. }
  17556. };
  17557. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17558. {
  17559. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17560. }
  17561. //=================================================================================
  17562. class CRoxieServerWhenActivity : public CRoxieServerActivity
  17563. {
  17564. public:
  17565. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17566. : CRoxieServerActivity(_factory, _probeManager)
  17567. {
  17568. savedExtractSize = 0;
  17569. savedExtract = NULL;
  17570. }
  17571. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17572. {
  17573. savedExtractSize = parentExtractSize;
  17574. savedExtract = parentExtract;
  17575. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17576. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17577. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17578. }
  17579. virtual void stop(bool aborting)
  17580. {
  17581. if (state == STATEreset)
  17582. {
  17583. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  17584. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  17585. }
  17586. else if (state != STATEstopped)
  17587. {
  17588. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  17589. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId); // These ones do
  17590. }
  17591. CRoxieServerActivity::stop(aborting);
  17592. }
  17593. virtual const void *nextInGroup()
  17594. {
  17595. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  17596. return input->nextInGroup();
  17597. }
  17598. protected:
  17599. unsigned savedExtractSize;
  17600. const byte *savedExtract;
  17601. };
  17602. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17603. {
  17604. public:
  17605. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17606. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17607. {
  17608. }
  17609. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17610. {
  17611. return new CRoxieServerWhenActivity(this, _probeManager);
  17612. }
  17613. };
  17614. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17615. {
  17616. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17617. }
  17618. //=================================================================================
  17619. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17620. {
  17621. public:
  17622. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17623. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17624. {
  17625. savedExtractSize = 0;
  17626. savedExtract = NULL;
  17627. }
  17628. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17629. {
  17630. savedExtractSize = parentExtractSize;
  17631. savedExtract = parentExtract;
  17632. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17633. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17634. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17635. }
  17636. virtual void stop(bool aborting)
  17637. {
  17638. if (state != STATEstopped)
  17639. {
  17640. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  17641. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17642. }
  17643. CRoxieServerActionBaseActivity::stop(aborting);
  17644. }
  17645. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17646. {
  17647. executeDependencies(parentExtractSize, parentExtract, 1);
  17648. }
  17649. protected:
  17650. unsigned savedExtractSize;
  17651. const byte *savedExtract;
  17652. };
  17653. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17654. {
  17655. public:
  17656. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17657. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17658. {
  17659. }
  17660. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17661. {
  17662. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17663. }
  17664. virtual bool isSink() const
  17665. {
  17666. return isRoot;
  17667. }
  17668. private:
  17669. bool isRoot;
  17670. };
  17671. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17672. {
  17673. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17674. }
  17675. //=================================================================================
  17676. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17677. {
  17678. IHThorParseArg &helper;
  17679. INlpParser * parser;
  17680. INlpResultIterator * rowIter;
  17681. const void * in;
  17682. char * curSearchText;
  17683. INlpParseAlgorithm * algorithm;
  17684. size32_t curSearchTextLen;
  17685. bool anyThisGroup;
  17686. bool processRecord(const void * inRec)
  17687. {
  17688. if (helper.searchTextNeedsFree())
  17689. rtlFree(curSearchText);
  17690. curSearchTextLen = 0;
  17691. curSearchText = NULL;
  17692. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17693. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17694. }
  17695. public:
  17696. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17697. : CRoxieServerActivity(_factory, _probeManager),
  17698. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17699. {
  17700. parser = NULL;
  17701. rowIter = NULL;
  17702. in = NULL;
  17703. curSearchText = NULL;
  17704. anyThisGroup = false;
  17705. curSearchTextLen = 0;
  17706. }
  17707. ~CRoxieServerParseActivity()
  17708. {
  17709. ::Release(parser);
  17710. }
  17711. virtual bool needsAllocator() const { return true; }
  17712. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17713. {
  17714. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17715. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17716. rowIter = parser->queryResultIter();
  17717. }
  17718. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17719. {
  17720. anyThisGroup = false;
  17721. curSearchTextLen = 0;
  17722. curSearchText = NULL;
  17723. in = NULL;
  17724. parser->reset();
  17725. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17726. }
  17727. virtual void reset()
  17728. {
  17729. if (helper.searchTextNeedsFree())
  17730. rtlFree(curSearchText);
  17731. curSearchText = NULL;
  17732. ReleaseClearRoxieRow(in);
  17733. CRoxieServerActivity::reset();
  17734. }
  17735. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17736. {
  17737. try
  17738. {
  17739. return helper.transform(self, curRecord, results, walker);
  17740. }
  17741. catch (IException *E)
  17742. {
  17743. throw makeWrappedException(E);
  17744. }
  17745. }
  17746. virtual const void * nextInGroup()
  17747. {
  17748. ActivityTimer t(totalCycles, timeActivities);
  17749. loop
  17750. {
  17751. if (rowIter->isValid())
  17752. {
  17753. anyThisGroup = true;
  17754. OwnedConstRoxieRow out = rowIter->getRow();
  17755. rowIter->next();
  17756. processed++;
  17757. return out.getClear();
  17758. }
  17759. ReleaseClearRoxieRow(in);
  17760. in = input->nextInGroup();
  17761. if (!in)
  17762. {
  17763. if (anyThisGroup)
  17764. {
  17765. anyThisGroup = false;
  17766. return NULL;
  17767. }
  17768. in = input->nextInGroup();
  17769. if (!in)
  17770. return NULL;
  17771. }
  17772. processRecord(in);
  17773. rowIter->first();
  17774. }
  17775. }
  17776. };
  17777. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17778. {
  17779. Owned<INlpParseAlgorithm> algorithm;
  17780. Owned<IHThorParseArg> helper;
  17781. public:
  17782. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17783. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17784. {
  17785. helper.setown((IHThorParseArg *) helperFactory());
  17786. algorithm.setown(createThorParser(rc, *helper));
  17787. }
  17788. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17789. {
  17790. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17791. }
  17792. };
  17793. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17794. {
  17795. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17796. }
  17797. //=====================================================================================================
  17798. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17799. {
  17800. IHThorWorkUnitWriteArg &helper;
  17801. bool isReread;
  17802. bool grouped;
  17803. IRoxieServerContext *serverContext;
  17804. public:
  17805. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  17806. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17807. {
  17808. grouped = (helper.getFlags() & POFgrouped) != 0;
  17809. serverContext = NULL;
  17810. }
  17811. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17812. {
  17813. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17814. serverContext = ctx->queryServerContext();
  17815. if (!serverContext)
  17816. {
  17817. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17818. }
  17819. }
  17820. virtual bool needsAllocator() const { return true; }
  17821. virtual void onExecute()
  17822. {
  17823. int sequence = helper.getSequence();
  17824. const char *storedName = helper.queryName();
  17825. if (!storedName)
  17826. storedName = "Dataset";
  17827. MemoryBuffer result;
  17828. FlushingStringBuffer *response = NULL;
  17829. bool saveInContext = (int) sequence < 0 || isReread;
  17830. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17831. meta.set(input->queryOutputMeta());
  17832. Owned<IOutputRowSerializer> rowSerializer;
  17833. Owned<IXmlWriter> writer;
  17834. if ((int) sequence >= 0)
  17835. {
  17836. response = serverContext->queryResult(sequence);
  17837. if (response)
  17838. {
  17839. const IProperties *xmlns = serverContext->queryXmlns(sequence);
  17840. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0, xmlns);
  17841. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17842. {
  17843. unsigned int writeFlags = serverContext->getXmlFlags();
  17844. if (response->mlFmt==MarkupFmt_JSON)
  17845. writeFlags |= XWFnoindent;
  17846. writer.setown(createIXmlWriterExt(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17847. writer->outputBeginArray(DEFAULTXMLROWTAG);
  17848. }
  17849. }
  17850. }
  17851. size32_t outputLimitBytes = 0;
  17852. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  17853. if (workunit)
  17854. {
  17855. size32_t outputLimit;
  17856. if (helper.getFlags() & POFmaxsize)
  17857. outputLimit = helper.getMaxSize();
  17858. else
  17859. {
  17860. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  17861. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  17862. }
  17863. if (outputLimit>defaultDaliResultOutputMax)
  17864. 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);
  17865. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  17866. outputLimitBytes = outputLimit * 0x100000;
  17867. }
  17868. if (workunit != NULL || (response && response->isRaw))
  17869. {
  17870. createRowAllocator();
  17871. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17872. }
  17873. __int64 initialProcessed = processed;
  17874. RtlLinkedDatasetBuilder builder(rowAllocator);
  17875. loop
  17876. {
  17877. const void *row = input->nextInGroup();
  17878. if (saveInContext)
  17879. {
  17880. if (row || grouped)
  17881. builder.append(row);
  17882. }
  17883. if (grouped && (processed != initialProcessed))
  17884. {
  17885. if (workunit)
  17886. result.append(row == NULL);
  17887. if (response)
  17888. {
  17889. if (response->isRaw)
  17890. response->append((char)(row == NULL));
  17891. else
  17892. {
  17893. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17894. }
  17895. }
  17896. }
  17897. if (!row)
  17898. {
  17899. row = input->nextInGroup();
  17900. if (!row)
  17901. break;
  17902. if (saveInContext)
  17903. builder.append(row);
  17904. }
  17905. processed++;
  17906. if (workunit)
  17907. {
  17908. CThorDemoRowSerializer serializerTarget(result);
  17909. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17910. }
  17911. if (response)
  17912. {
  17913. if (response->isRaw)
  17914. {
  17915. // MORE - should be able to serialize straight to the response...
  17916. MemoryBuffer rowbuff;
  17917. CThorDemoRowSerializer serializerTarget(rowbuff);
  17918. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17919. response->append(rowbuff.length(), rowbuff.toByteArray());
  17920. }
  17921. else if (writer)
  17922. {
  17923. writer->outputBeginNested(DEFAULTXMLROWTAG, false);
  17924. helper.serializeXml((byte *) row, *writer);
  17925. writer->outputEndNested(DEFAULTXMLROWTAG);
  17926. }
  17927. else
  17928. {
  17929. SimpleOutputWriter x;
  17930. helper.serializeXml((byte *) row, x);
  17931. x.newline();
  17932. response->append(x.str());
  17933. }
  17934. response->incrementRowCount();
  17935. response->flush(false);
  17936. }
  17937. ReleaseRoxieRow(row);
  17938. if (outputLimitBytes && result.length() > outputLimitBytes)
  17939. {
  17940. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  17941. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  17942. const char *name = helper.queryName();
  17943. if (name)
  17944. errMsg.append("name=").append(name);
  17945. else
  17946. errMsg.append("sequence=").append(helper.getSequence());
  17947. errMsg.append(")");
  17948. throw MakeStringExceptionDirect(0, errMsg.str());
  17949. }
  17950. }
  17951. if (writer)
  17952. writer->outputEndArray(DEFAULTXMLROWTAG);
  17953. if (saveInContext)
  17954. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17955. if (workunit)
  17956. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17957. }
  17958. };
  17959. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17960. {
  17961. bool isReread;
  17962. public:
  17963. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17964. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17965. {
  17966. isReread = usageCount > 0;
  17967. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17968. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17969. }
  17970. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17971. {
  17972. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread, usageCount);
  17973. }
  17974. };
  17975. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17976. {
  17977. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17978. }
  17979. //=====================================================================================================
  17980. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17981. {
  17982. IHThorDictionaryWorkUnitWriteArg &helper;
  17983. IRoxieServerContext *serverContext;
  17984. public:
  17985. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  17986. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17987. {
  17988. serverContext = NULL;
  17989. }
  17990. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17991. {
  17992. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17993. serverContext = ctx->queryServerContext();
  17994. if (!serverContext)
  17995. {
  17996. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17997. }
  17998. }
  17999. virtual bool needsAllocator() const { return true; }
  18000. virtual void onExecute()
  18001. {
  18002. int sequence = helper.getSequence();
  18003. const char *storedName = helper.queryName();
  18004. assertex(storedName && *storedName);
  18005. assertex(sequence < 0);
  18006. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18007. loop
  18008. {
  18009. const void *row = input->nextInGroup();
  18010. if (!row)
  18011. {
  18012. row = input->nextInGroup();
  18013. if (!row)
  18014. break;
  18015. }
  18016. builder.appendOwn(row);
  18017. processed++;
  18018. }
  18019. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18020. }
  18021. };
  18022. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18023. {
  18024. public:
  18025. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18026. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18027. {
  18028. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18029. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18030. }
  18031. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18032. {
  18033. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager, usageCount);
  18034. }
  18035. };
  18036. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18037. {
  18038. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18039. }
  18040. //=================================================================================
  18041. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18042. {
  18043. IHThorRemoteResultArg &helper;
  18044. public:
  18045. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18046. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18047. {
  18048. }
  18049. virtual void onExecute()
  18050. {
  18051. OwnedConstRoxieRow row = input->nextInGroup();
  18052. helper.sendResult(row); // should be only one row or something has gone wrong!
  18053. }
  18054. };
  18055. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18056. {
  18057. public:
  18058. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18059. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18060. {
  18061. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18062. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18063. }
  18064. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18065. {
  18066. return new CRoxieServerRemoteResultActivity(this, _probeManager, usageCount);
  18067. }
  18068. };
  18069. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18070. {
  18071. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18072. }
  18073. //=================================================================================
  18074. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18075. {
  18076. IHThorXmlParseArg &helper;
  18077. Owned<IXMLParse> xmlParser;
  18078. const void * in;
  18079. char * srchStr;
  18080. unsigned numProcessedLastGroup;
  18081. bool srchStrNeedsFree;
  18082. Owned<IColumnProvider> lastMatch;
  18083. public:
  18084. IMPLEMENT_IINTERFACE;
  18085. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18086. : CRoxieServerActivity(_factory, _probeManager),
  18087. helper((IHThorXmlParseArg &)basehelper)
  18088. {
  18089. srchStrNeedsFree = helper.searchTextNeedsFree();
  18090. numProcessedLastGroup = 0;
  18091. srchStr = NULL;
  18092. in = NULL;
  18093. }
  18094. ~CRoxieServerXmlParseActivity()
  18095. {
  18096. }
  18097. virtual bool needsAllocator() const { return true; }
  18098. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18099. {
  18100. numProcessedLastGroup = 0;
  18101. srchStr = NULL;
  18102. in = NULL;
  18103. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18104. }
  18105. virtual void reset()
  18106. {
  18107. if (helper.searchTextNeedsFree())
  18108. rtlFree(srchStr);
  18109. srchStr = NULL;
  18110. ReleaseClearRoxieRow(in);
  18111. xmlParser.clear();
  18112. CRoxieServerActivity::reset();
  18113. }
  18114. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18115. {
  18116. lastMatch.set(&entry);
  18117. }
  18118. virtual const void *nextInGroup()
  18119. {
  18120. ActivityTimer t(totalCycles, timeActivities);
  18121. loop
  18122. {
  18123. if(xmlParser)
  18124. {
  18125. loop
  18126. {
  18127. if(!xmlParser->next())
  18128. {
  18129. if (srchStrNeedsFree)
  18130. {
  18131. rtlFree(srchStr);
  18132. srchStr = NULL;
  18133. }
  18134. xmlParser.clear();
  18135. break;
  18136. }
  18137. if(lastMatch)
  18138. {
  18139. try
  18140. {
  18141. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18142. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18143. lastMatch.clear();
  18144. if (outSize)
  18145. {
  18146. processed++;
  18147. return rowBuilder.finalizeRowClear(outSize);
  18148. }
  18149. }
  18150. catch (IException *E)
  18151. {
  18152. throw makeWrappedException(E);
  18153. }
  18154. }
  18155. }
  18156. }
  18157. ReleaseClearRoxieRow(in);
  18158. in = input->nextInGroup();
  18159. if(!in)
  18160. {
  18161. if(numProcessedLastGroup == processed)
  18162. in = input->nextInGroup();
  18163. if(!in)
  18164. {
  18165. numProcessedLastGroup = processed;
  18166. return NULL;
  18167. }
  18168. }
  18169. size32_t srchLen;
  18170. helper.getSearchText(srchLen, srchStr, in);
  18171. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  18172. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  18173. }
  18174. }
  18175. };
  18176. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  18177. {
  18178. public:
  18179. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18180. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  18181. {
  18182. }
  18183. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18184. {
  18185. return new CRoxieServerXmlParseActivity(this, _probeManager);
  18186. }
  18187. };
  18188. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18189. {
  18190. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  18191. }
  18192. //=====================================================================================================
  18193. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  18194. {
  18195. protected:
  18196. IHThorDiskReadBaseArg &helper;
  18197. IHThorCompoundExtra * compoundHelper;
  18198. RemoteActivityId remoteId; // Note we copy it rather than reference
  18199. Owned<CSkippableRemoteResultAdaptor> remote;
  18200. unsigned numParts;
  18201. unsigned __int64 rowLimit;
  18202. unsigned __int64 stopAfter;
  18203. Linked<IInMemoryIndexManager> manager;
  18204. Owned<IInMemoryIndexCursor> cursor;
  18205. Owned<IDirectReader> reader;
  18206. CThorContiguousRowBuffer deserializeSource;
  18207. Owned<ISourceRowPrefetcher> prefetcher;
  18208. bool eof;
  18209. bool isKeyed;
  18210. bool variableFileName;
  18211. bool isOpt;
  18212. bool sorted;
  18213. bool maySkip;
  18214. bool isLocal;
  18215. bool forceRemote;
  18216. CachedOutputMetaData diskSize;
  18217. Owned<const IResolvedFile> varFileInfo;
  18218. Owned<IFileIOArray> varFiles;
  18219. inline bool useRemote()
  18220. {
  18221. return remote != NULL && (forceRemote || numParts > 1);
  18222. }
  18223. public:
  18224. IMPLEMENT_IINTERFACE;
  18225. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18226. : CRoxieServerActivity(_factory, _probeManager),
  18227. helper((IHThorDiskReadBaseArg &)basehelper),
  18228. numParts(_numParts),
  18229. remoteId(_remoteId),
  18230. manager(_manager),
  18231. isLocal(_isLocal),
  18232. sorted(_sorted),
  18233. maySkip(_maySkip),
  18234. deserializeSource(NULL)
  18235. {
  18236. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  18237. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  18238. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  18239. compoundHelper = NULL;
  18240. eof = false;
  18241. rowLimit = (unsigned __int64) -1;
  18242. isKeyed = false;
  18243. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  18244. diskSize.set(helper.queryDiskRecordSize());
  18245. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18246. isOpt = (helper.getFlags() & TDRoptional) != 0;
  18247. }
  18248. virtual const IResolvedFile *queryVarFileInfo() const
  18249. {
  18250. return varFileInfo;
  18251. }
  18252. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18253. {
  18254. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18255. if (remote)
  18256. remote->onCreate(this, this, _ctx, _colocalParent);
  18257. }
  18258. virtual bool needsAllocator() const { return true; }
  18259. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18260. {
  18261. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18262. if (compoundHelper)
  18263. {
  18264. rowLimit = compoundHelper->getRowLimit();
  18265. stopAfter = compoundHelper->getChooseNLimit();
  18266. }
  18267. if (!helper.canMatchAny())
  18268. eof = true;
  18269. else
  18270. {
  18271. if (variableFileName)
  18272. {
  18273. OwnedRoxieString fileName(helper.getFileName());
  18274. varFileInfo.setown(resolveLFN(fileName, isOpt));
  18275. numParts = 0;
  18276. if (varFileInfo)
  18277. numParts = varFileInfo->getNumParts();
  18278. }
  18279. if (!numParts)
  18280. {
  18281. eof = true;
  18282. }
  18283. else if (useRemote())
  18284. {
  18285. remote->onStart(parentExtractSize, parentExtract);
  18286. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  18287. unsigned fileNo = 0;
  18288. // Translation into a message per channel done elsewhere....
  18289. remote->getMem(0, fileNo, 0);
  18290. remote->flush();
  18291. remote->senddone();
  18292. }
  18293. else
  18294. {
  18295. if (variableFileName)
  18296. {
  18297. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  18298. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  18299. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  18300. }
  18301. assertex(manager != NULL);
  18302. helper.createSegmentMonitors(this);
  18303. if (cursor)
  18304. {
  18305. isKeyed = cursor->selectKey();
  18306. cursor->reset();
  18307. }
  18308. if (!isKeyed)
  18309. {
  18310. reader.setown(manager->createReader(0, 0, 1));
  18311. deserializeSource.setStream(reader);
  18312. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  18313. }
  18314. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  18315. }
  18316. }
  18317. }
  18318. virtual void append(IKeySegmentMonitor *segment)
  18319. {
  18320. if (!segment->isWild())
  18321. {
  18322. if (!cursor)
  18323. cursor.setown(manager->createCursor());
  18324. cursor->append(segment);
  18325. }
  18326. }
  18327. virtual unsigned ordinality() const
  18328. {
  18329. return cursor ? cursor->ordinality() : 0;
  18330. }
  18331. virtual IKeySegmentMonitor *item(unsigned idx) const
  18332. {
  18333. return cursor ? cursor->item(idx) : 0;
  18334. }
  18335. virtual void setMergeBarrier(unsigned barrierOffset)
  18336. {
  18337. // no merging so no issue...
  18338. }
  18339. virtual void stop(bool aborting)
  18340. {
  18341. if (useRemote())
  18342. remote->onStop(aborting);
  18343. CRoxieServerActivity::stop(aborting);
  18344. }
  18345. virtual void reset()
  18346. {
  18347. if (useRemote())
  18348. {
  18349. processed = remote->processed;
  18350. remote->processed = 0;
  18351. remote->onReset();
  18352. }
  18353. varFileInfo.clear();
  18354. eof = false;
  18355. if (cursor)
  18356. cursor->reset();
  18357. deserializeSource.clearStream();
  18358. CRoxieServerActivity::reset();
  18359. }
  18360. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18361. {
  18362. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18363. }
  18364. virtual void onLimitExceeded(bool isKeyed)
  18365. {
  18366. if (traceLevel > 4)
  18367. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18368. assertex(compoundHelper);
  18369. if (isKeyed) // MORE does this exist for diskread? should it?
  18370. {
  18371. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  18372. {
  18373. if (ctx->queryDebugContext())
  18374. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18375. throw makeLimitSkipException(true);
  18376. }
  18377. else
  18378. {
  18379. UNIMPLEMENTED;
  18380. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  18381. }
  18382. }
  18383. else
  18384. {
  18385. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  18386. {
  18387. if (ctx->queryDebugContext())
  18388. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18389. throw makeLimitSkipException(false);
  18390. }
  18391. else
  18392. compoundHelper->onLimitExceeded();
  18393. }
  18394. }
  18395. virtual const void * createLimitFailRow(bool isKeyed)
  18396. {
  18397. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18398. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  18399. assertex(limitTransformExtra);
  18400. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18401. if (outSize)
  18402. return rowBuilder.finalizeRowClear(outSize);
  18403. return NULL;
  18404. }
  18405. };
  18406. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  18407. {
  18408. IHThorCompoundReadExtra * readHelper;
  18409. ConstPointerArray readrows;
  18410. bool readAheadDone;
  18411. unsigned readIndex;
  18412. public:
  18413. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18414. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18415. {
  18416. compoundHelper = (IHThorDiskReadArg *)&helper;
  18417. readHelper = (IHThorDiskReadArg *)&helper;
  18418. readAheadDone = false;
  18419. readIndex = 0;
  18420. }
  18421. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18422. {
  18423. rowLimit = compoundHelper->getRowLimit();
  18424. stopAfter = compoundHelper->getChooseNLimit();
  18425. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18426. readAheadDone = false;
  18427. readIndex = 0;
  18428. }
  18429. virtual void reset()
  18430. {
  18431. while (readrows.isItem(readIndex))
  18432. ReleaseRoxieRow(readrows.item(readIndex++));
  18433. readrows.kill();
  18434. readAheadDone = false;
  18435. readIndex = 0;
  18436. CRoxieServerDiskReadBaseActivity::reset();
  18437. }
  18438. virtual const void *nextInGroup()
  18439. {
  18440. if (eof)
  18441. return NULL;
  18442. else if (useRemote())
  18443. return remote->nextInGroup();
  18444. else if (maySkip)
  18445. {
  18446. if (!readAheadDone)
  18447. {
  18448. unsigned preprocessed = 0;
  18449. while (!eof)
  18450. {
  18451. const void *row = _nextInGroup();
  18452. if (row)
  18453. preprocessed++;
  18454. if (preprocessed > rowLimit)
  18455. {
  18456. ReleaseRoxieRow(row);
  18457. while (readrows.isItem(readIndex))
  18458. ReleaseRoxieRow(readrows.item(readIndex++));
  18459. readrows.kill();
  18460. eof = true;
  18461. if (ctx->queryDebugContext())
  18462. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18463. if (helper.getFlags() & TDRlimitskips)
  18464. return NULL;
  18465. else if (helper.getFlags() & TDRlimitcreates)
  18466. return createLimitFailRow(false);
  18467. else
  18468. throwUnexpected();
  18469. }
  18470. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  18471. {
  18472. eof = true;
  18473. ReleaseRoxieRow(row);
  18474. break;
  18475. }
  18476. readrows.append(row);
  18477. }
  18478. readAheadDone = true;
  18479. }
  18480. if (readrows.isItem(readIndex))
  18481. {
  18482. const void *ret = readrows.item(readIndex++);
  18483. if (ret)
  18484. processed++;
  18485. return ret;
  18486. }
  18487. else
  18488. {
  18489. eof = true;
  18490. return NULL;
  18491. }
  18492. }
  18493. else
  18494. {
  18495. const void *ret = _nextInGroup();
  18496. if (ret)
  18497. {
  18498. processed++;
  18499. if (processed > rowLimit)
  18500. {
  18501. if (traceLevel > 4)
  18502. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18503. ReleaseRoxieRow(ret);
  18504. compoundHelper->onLimitExceeded();
  18505. throwUnexpected(); // onLimitExceeded is not supposed to return
  18506. }
  18507. if (processed > stopAfter) // MORE - bit of a strange place to check
  18508. {
  18509. eof = true;
  18510. ReleaseRoxieRow(ret);
  18511. return NULL;
  18512. }
  18513. }
  18514. return ret;
  18515. }
  18516. }
  18517. const void *_nextInGroup()
  18518. {
  18519. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18520. unsigned transformedSize = 0;
  18521. if (isKeyed)
  18522. {
  18523. loop
  18524. {
  18525. const void *nextCandidate = cursor->nextMatch();
  18526. if (!nextCandidate)
  18527. {
  18528. eof = true;
  18529. return NULL;
  18530. }
  18531. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  18532. if (transformedSize)
  18533. break;
  18534. }
  18535. }
  18536. else // use reader...
  18537. {
  18538. assertex(reader != NULL);
  18539. loop
  18540. {
  18541. if (deserializeSource.eos())
  18542. {
  18543. eof = true;
  18544. return NULL;
  18545. }
  18546. prefetcher->readAhead(deserializeSource);
  18547. const byte *nextRec = deserializeSource.queryRow();
  18548. if (cursor && cursor->isFiltered(nextRec))
  18549. transformedSize = 0;
  18550. else
  18551. transformedSize = readHelper->transform(rowBuilder, nextRec);
  18552. deserializeSource.finishedRow();
  18553. if (transformedSize)
  18554. break;
  18555. }
  18556. }
  18557. return rowBuilder.finalizeRowClear(transformedSize);
  18558. }
  18559. };
  18560. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  18561. {
  18562. IHThorXmlReadArg * readHelper;
  18563. Owned<IXmlToRowTransformer> rowTransformer;
  18564. Owned<IXMLParse> xmlParser;
  18565. Owned<IColumnProvider> lastMatch;
  18566. unsigned __int64 localOffset;
  18567. public:
  18568. IMPLEMENT_IINTERFACE;
  18569. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18570. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18571. {
  18572. compoundHelper = NULL;
  18573. readHelper = (IHThorXmlReadArg *)&helper;
  18574. localOffset = 0;
  18575. }
  18576. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18577. {
  18578. rowLimit = readHelper->getRowLimit();
  18579. stopAfter = readHelper->getChooseNLimit();
  18580. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18581. if (!useRemote())
  18582. {
  18583. rowTransformer.set(readHelper->queryTransformer());
  18584. assertex(reader != NULL);
  18585. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  18586. if (factory->getKind()==TAKjsonread)
  18587. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18588. else
  18589. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18590. }
  18591. }
  18592. virtual void reset()
  18593. {
  18594. CRoxieServerDiskReadBaseActivity::reset();
  18595. rowTransformer.clear();
  18596. xmlParser.clear();
  18597. }
  18598. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18599. {
  18600. localOffset = startOffset;
  18601. lastMatch.set(&entry);
  18602. }
  18603. virtual const void *nextInGroup()
  18604. {
  18605. if (eof)
  18606. return NULL;
  18607. else if (useRemote())
  18608. return remote->nextInGroup();
  18609. assertex(xmlParser != NULL);
  18610. try
  18611. {
  18612. while (!eof)
  18613. {
  18614. //call to next() will callback on the IXmlSelect interface
  18615. bool gotNext = false;
  18616. gotNext = xmlParser->next();
  18617. if(!gotNext)
  18618. eof = true;
  18619. else if (lastMatch)
  18620. {
  18621. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18622. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18623. lastMatch.clear();
  18624. localOffset = 0;
  18625. if (sizeGot)
  18626. {
  18627. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18628. if (processed > rowLimit)
  18629. {
  18630. if (traceLevel > 4)
  18631. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18632. readHelper->onLimitExceeded();
  18633. throwUnexpected(); // onLimitExceeded is not supposed to return
  18634. }
  18635. processed++;
  18636. if (processed > stopAfter) // MORE - bit of a strange place to check
  18637. {
  18638. eof = true;
  18639. return NULL;
  18640. }
  18641. return ret.getClear();
  18642. }
  18643. }
  18644. }
  18645. return NULL;
  18646. }
  18647. catch(IException *E)
  18648. {
  18649. throw makeWrappedException(E);
  18650. }
  18651. }
  18652. };
  18653. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18654. {
  18655. IHThorCsvReadArg *readHelper;
  18656. ICsvParameters * csvInfo;
  18657. unsigned headerLines;
  18658. unsigned maxDiskSize;
  18659. CSVSplitter csvSplitter;
  18660. unsigned __int64 localOffset;
  18661. const char *quotes;
  18662. const char *separators;
  18663. const char *terminators;
  18664. const char *escapes;
  18665. size32_t maxRowSize;
  18666. public:
  18667. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18668. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18669. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  18670. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18671. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  18672. {
  18673. compoundHelper = NULL;
  18674. readHelper = (IHThorCsvReadArg *)&helper;
  18675. rowLimit = readHelper->getRowLimit();
  18676. stopAfter = readHelper->getChooseNLimit();
  18677. csvInfo = readHelper->queryCsvParameters();
  18678. maxDiskSize = csvInfo->queryMaxSize();
  18679. localOffset = 0;
  18680. headerLines = 0;
  18681. }
  18682. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18683. {
  18684. rowLimit = readHelper->getRowLimit();
  18685. stopAfter = readHelper->getChooseNLimit();
  18686. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18687. if (!useRemote())
  18688. {
  18689. headerLines = csvInfo->queryHeaderLen();
  18690. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18691. 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...
  18692. if (!eof)
  18693. {
  18694. if (varFileInfo)
  18695. {
  18696. const IPropertyTree *options = varFileInfo->queryProperties();
  18697. if (options)
  18698. {
  18699. quotes = options->queryProp("@csvQuote");
  18700. separators = options->queryProp("@csvSeparate");
  18701. terminators = options->queryProp("@csvTerminate");
  18702. escapes = options->queryProp("@csvEscape");
  18703. }
  18704. }
  18705. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18706. }
  18707. }
  18708. }
  18709. virtual const void *nextInGroup()
  18710. {
  18711. if (eof)
  18712. return NULL;
  18713. else if (useRemote())
  18714. return remote->nextInGroup();
  18715. try
  18716. {
  18717. while (!eof)
  18718. {
  18719. if (reader->eos())
  18720. {
  18721. eof = true;
  18722. break;
  18723. }
  18724. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18725. size32_t rowSize = 4096; // MORE - make configurable
  18726. size32_t thisLineLength;
  18727. loop
  18728. {
  18729. size32_t avail;
  18730. const void *peek = reader->peek(rowSize, avail);
  18731. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18732. if (thisLineLength < rowSize || avail < rowSize)
  18733. break;
  18734. if (rowSize == maxRowSize)
  18735. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  18736. if (rowSize >= maxRowSize/2)
  18737. rowSize = maxRowSize;
  18738. else
  18739. rowSize += rowSize;
  18740. }
  18741. if (headerLines)
  18742. {
  18743. headerLines--;
  18744. reader->skip(thisLineLength);
  18745. }
  18746. else
  18747. {
  18748. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18749. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18750. reader->skip(thisLineLength);
  18751. if (transformedSize)
  18752. {
  18753. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18754. if (processed > rowLimit)
  18755. {
  18756. readHelper->onLimitExceeded();
  18757. throwUnexpected(); // onLimitExceeded is not supposed to return
  18758. }
  18759. processed++;
  18760. if (processed > stopAfter) // MORE - bit of a strange place to check
  18761. {
  18762. eof = true;
  18763. return NULL;
  18764. }
  18765. return ret.getClear();
  18766. }
  18767. }
  18768. }
  18769. return NULL;
  18770. }
  18771. catch(IException *E)
  18772. {
  18773. throw makeWrappedException(E);
  18774. }
  18775. }
  18776. virtual void reset()
  18777. {
  18778. CRoxieServerDiskReadBaseActivity::reset();
  18779. csvSplitter.reset();
  18780. localOffset = 0;
  18781. }
  18782. virtual unsigned __int64 getFilePosition(const void * row)
  18783. {
  18784. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18785. }
  18786. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18787. {
  18788. UNIMPLEMENTED;
  18789. }
  18790. };
  18791. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18792. {
  18793. IHThorDiskNormalizeArg *normalizeHelper;
  18794. bool firstPending;
  18795. public:
  18796. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18797. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18798. {
  18799. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18800. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18801. firstPending = true;
  18802. }
  18803. virtual void reset()
  18804. {
  18805. firstPending = true;
  18806. CRoxieServerDiskReadBaseActivity::reset();
  18807. }
  18808. virtual const void *nextInGroup()
  18809. {
  18810. if (eof)
  18811. return NULL;
  18812. else if (useRemote())
  18813. return remote->nextInGroup();
  18814. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18815. unsigned transformedSize = 0;
  18816. if (isKeyed)
  18817. {
  18818. loop
  18819. {
  18820. while (firstPending)
  18821. {
  18822. const void *nextCandidate = cursor->nextMatch();
  18823. if (!nextCandidate)
  18824. {
  18825. eof = true;
  18826. return NULL;
  18827. }
  18828. if (normalizeHelper->first(nextCandidate))
  18829. {
  18830. firstPending = false;
  18831. break;
  18832. }
  18833. }
  18834. transformedSize = normalizeHelper->transform(rowBuilder);
  18835. firstPending = !normalizeHelper->next();
  18836. if (transformedSize)
  18837. break;
  18838. }
  18839. }
  18840. else
  18841. {
  18842. assertex(reader != NULL);
  18843. loop
  18844. {
  18845. while (firstPending)
  18846. {
  18847. if (deserializeSource.eos())
  18848. {
  18849. eof = true;
  18850. return NULL;
  18851. }
  18852. prefetcher->readAhead(deserializeSource);
  18853. const byte *nextRec = deserializeSource.queryRow();
  18854. if (!cursor || !cursor->isFiltered(nextRec))
  18855. {
  18856. if (normalizeHelper->first(nextRec))
  18857. firstPending = false;
  18858. }
  18859. deserializeSource.finishedRow();
  18860. }
  18861. transformedSize = normalizeHelper->transform(rowBuilder);
  18862. firstPending = !normalizeHelper->next();
  18863. if (transformedSize)
  18864. break;
  18865. }
  18866. }
  18867. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18868. processed++;
  18869. if (processed > rowLimit)
  18870. {
  18871. compoundHelper->onLimitExceeded();
  18872. throwUnexpected(); // onLimitExceeded is not supposed to return
  18873. }
  18874. if (processed > stopAfter) // MORE - bit of a strange place to check
  18875. {
  18876. eof = true;
  18877. return NULL;
  18878. }
  18879. return recBuffer.getClear();
  18880. }
  18881. };
  18882. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18883. {
  18884. protected:
  18885. bool done;
  18886. public:
  18887. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18888. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18889. done(false)
  18890. {
  18891. }
  18892. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18893. {
  18894. done = false;
  18895. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18896. }
  18897. virtual IRoxieInput *queryOutput(unsigned idx)
  18898. {
  18899. if (idx==(unsigned)-1)
  18900. idx = 0;
  18901. return idx ? NULL: this;
  18902. }
  18903. };
  18904. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18905. {
  18906. IHThorDiskCountArg & countHelper;
  18907. unsigned __int64 choosenLimit;
  18908. IHThorSourceCountLimit *limitHelper;
  18909. unsigned __int64 getSkippedCount()
  18910. {
  18911. unsigned flags = countHelper.getFlags();
  18912. if (flags & TDRlimitskips)
  18913. return 0;
  18914. else if (flags & TDRlimitcreates)
  18915. return 1;
  18916. else
  18917. {
  18918. assertex(limitHelper);
  18919. if (traceLevel > 4)
  18920. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18921. limitHelper->onLimitExceeded();
  18922. throwUnexpected(); // onLimitExceeded should always throw exception
  18923. }
  18924. }
  18925. public:
  18926. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18927. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18928. countHelper((IHThorDiskCountArg &)basehelper)
  18929. {
  18930. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18931. choosenLimit = 0;
  18932. }
  18933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18934. {
  18935. choosenLimit = countHelper.getChooseNLimit();
  18936. if (limitHelper)
  18937. {
  18938. rowLimit = limitHelper->getRowLimit();
  18939. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18940. }
  18941. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18942. }
  18943. virtual const void *nextInGroup()
  18944. {
  18945. ActivityTimer t(totalCycles, timeActivities);
  18946. if (done) return NULL;
  18947. done = true;
  18948. unsigned __int64 totalCount = 0;
  18949. if (helper.canMatchAny() && !eof)
  18950. {
  18951. if (useRemote())
  18952. {
  18953. loop
  18954. {
  18955. const void * next = remote->nextInGroup();
  18956. if (!next)
  18957. break;
  18958. if (meta.getFixedSize() == 1)
  18959. totalCount += *(byte *)next;
  18960. else
  18961. totalCount += *(unsigned __int64 *)next;
  18962. ReleaseRoxieRow(next);
  18963. if (totalCount > rowLimit)
  18964. {
  18965. totalCount = getSkippedCount();
  18966. break;
  18967. }
  18968. else if (totalCount >= choosenLimit)
  18969. {
  18970. totalCount = choosenLimit;
  18971. break;
  18972. }
  18973. }
  18974. }
  18975. else
  18976. {
  18977. if (isKeyed)
  18978. {
  18979. loop
  18980. {
  18981. const void *nextCandidate = cursor->nextMatch();
  18982. if (!nextCandidate)
  18983. break;
  18984. totalCount += countHelper.numValid(nextCandidate);
  18985. if (totalCount > rowLimit)
  18986. {
  18987. totalCount = getSkippedCount();
  18988. break;
  18989. }
  18990. else if (totalCount >= choosenLimit)
  18991. {
  18992. totalCount = choosenLimit;
  18993. break;
  18994. }
  18995. }
  18996. }
  18997. else
  18998. {
  18999. assertex(reader != NULL);
  19000. while (!deserializeSource.eos())
  19001. {
  19002. prefetcher->readAhead(deserializeSource);
  19003. const byte *nextRec = deserializeSource.queryRow();
  19004. if (!cursor || !cursor->isFiltered(nextRec))
  19005. {
  19006. totalCount += countHelper.numValid(nextRec);
  19007. }
  19008. deserializeSource.finishedRow();
  19009. if (totalCount > rowLimit)
  19010. {
  19011. totalCount = getSkippedCount();
  19012. break;
  19013. }
  19014. else if (totalCount >= choosenLimit)
  19015. {
  19016. totalCount = choosenLimit;
  19017. break;
  19018. }
  19019. }
  19020. }
  19021. }
  19022. }
  19023. size32_t rowSize = meta.getFixedSize();
  19024. void * result = rowAllocator->createRow();
  19025. if (rowSize == 1)
  19026. *(byte *)result = (byte)totalCount;
  19027. else
  19028. {
  19029. assertex(rowSize == sizeof(unsigned __int64));
  19030. *(unsigned __int64 *)result = totalCount;
  19031. }
  19032. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19033. }
  19034. };
  19035. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19036. {
  19037. IHThorCompoundAggregateExtra & aggregateHelper;
  19038. public:
  19039. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19040. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19041. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19042. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19043. {
  19044. }
  19045. const void * gatherMerged()
  19046. {
  19047. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19048. size32_t finalSize = 0;
  19049. if (useRemote())
  19050. {
  19051. const void * firstRow = remote->nextInGroup();
  19052. if (!firstRow)
  19053. {
  19054. rowBuilder.ensureRow();
  19055. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19056. }
  19057. else
  19058. {
  19059. // NOTE need to clone this because going to modify below, could special case 1 row only
  19060. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19061. ReleaseRoxieRow(firstRow);
  19062. }
  19063. loop
  19064. {
  19065. const void * next = remote->nextInGroup();
  19066. if (!next)
  19067. break;
  19068. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19069. ReleaseRoxieRow(next);
  19070. }
  19071. }
  19072. else
  19073. {
  19074. aggregateHelper.clearAggregate(rowBuilder);
  19075. if (helper.canMatchAny() && !eof)
  19076. {
  19077. if (isKeyed)
  19078. {
  19079. loop
  19080. {
  19081. const void *next = cursor->nextMatch();
  19082. if (!next)
  19083. break;
  19084. aggregateHelper.processRow(rowBuilder, next);
  19085. }
  19086. }
  19087. else
  19088. {
  19089. assertex(reader != NULL);
  19090. while (!deserializeSource.eos())
  19091. {
  19092. prefetcher->readAhead(deserializeSource);
  19093. const byte *nextRec = deserializeSource.queryRow();
  19094. if (!cursor || !cursor->isFiltered(nextRec))
  19095. {
  19096. aggregateHelper.processRow(rowBuilder, nextRec);
  19097. }
  19098. deserializeSource.finishedRow();
  19099. }
  19100. }
  19101. }
  19102. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19103. }
  19104. return rowBuilder.finalizeRowClear(finalSize);
  19105. }
  19106. virtual const void *nextInGroup()
  19107. {
  19108. ActivityTimer t(totalCycles, timeActivities);
  19109. if (done) return NULL;
  19110. const void * ret = gatherMerged();
  19111. done = true;
  19112. return ret;
  19113. }
  19114. };
  19115. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19116. {
  19117. IHThorDiskGroupAggregateArg & aggregateHelper;
  19118. RowAggregator resultAggregator;
  19119. bool gathered;
  19120. public:
  19121. IMPLEMENT_IINTERFACE;
  19122. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19123. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19124. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19125. resultAggregator(aggregateHelper, aggregateHelper),
  19126. gathered(false)
  19127. {
  19128. }
  19129. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19130. {
  19131. gathered= false;
  19132. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19133. resultAggregator.start(rowAllocator);
  19134. }
  19135. virtual void reset()
  19136. {
  19137. resultAggregator.reset();
  19138. CRoxieServerDiskAggregateBaseActivity::reset();
  19139. }
  19140. void gatherMerged()
  19141. {
  19142. if (useRemote())
  19143. {
  19144. loop
  19145. {
  19146. const void * next = remote->nextInGroup();
  19147. if (!next)
  19148. break;
  19149. resultAggregator.mergeElement(next);
  19150. ReleaseRoxieRow(next);
  19151. }
  19152. }
  19153. else
  19154. {
  19155. if (helper.canMatchAny() && !eof)
  19156. {
  19157. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  19158. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  19159. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  19160. ctx->queryCodeContext(), activityId);
  19161. processor->doQuery(NULL, 0, 0, 0);
  19162. }
  19163. }
  19164. gathered = true;
  19165. }
  19166. virtual const void *nextInGroup()
  19167. {
  19168. ActivityTimer t(totalCycles, timeActivities);
  19169. if (done)
  19170. return NULL;
  19171. if (!gathered)
  19172. gatherMerged();
  19173. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  19174. if (next)
  19175. {
  19176. processed++;
  19177. return next->finalizeRowClear();
  19178. }
  19179. done = true;
  19180. return NULL;
  19181. }
  19182. };
  19183. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  19184. {
  19185. public:
  19186. RemoteActivityId remoteId;
  19187. bool isLocal;
  19188. bool sorted;
  19189. bool maySkip;
  19190. bool variableFileName;
  19191. Owned<IFileIOArray> files;
  19192. Owned<IInMemoryIndexManager> manager;
  19193. Owned<const IResolvedFile> datafile;
  19194. const char *quotes;
  19195. const char *separators;
  19196. const char *terminators;
  19197. const char *escapes;
  19198. size32_t maxCsvRowSize;
  19199. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19200. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19201. {
  19202. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19203. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19204. sorted = (helper->getFlags() & TDRunsorted) == 0;
  19205. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19206. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  19207. quotes = separators = terminators = escapes = NULL;
  19208. if (!variableFileName)
  19209. {
  19210. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  19211. OwnedRoxieString fileName(helper->getFileName());
  19212. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  19213. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  19214. if (isLocal || isSimple)
  19215. {
  19216. if (datafile)
  19217. {
  19218. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  19219. files.setown(datafile->getIFileIOArray(isOpt, channel));
  19220. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  19221. const IPropertyTree *options = datafile->queryProperties();
  19222. if (options)
  19223. {
  19224. quotes = options->queryProp("@csvQuote");
  19225. separators = options->queryProp("@csvSeparate");
  19226. terminators = options->queryProp("@csvTerminate");
  19227. escapes = options->queryProp("@csvEscape");
  19228. }
  19229. }
  19230. else
  19231. manager.setown(getEmptyIndexManager());
  19232. }
  19233. }
  19234. switch (kind)
  19235. {
  19236. case TAKcsvread:
  19237. {
  19238. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  19239. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  19240. if (workunit)
  19241. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  19242. break;
  19243. }
  19244. default:
  19245. maxCsvRowSize = 0; // unused
  19246. }
  19247. }
  19248. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19249. {
  19250. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  19251. switch (kind)
  19252. {
  19253. case TAKcsvread:
  19254. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  19255. quotes, separators, terminators, escapes, maxCsvRowSize);
  19256. case TAKxmlread:
  19257. case TAKjsonread:
  19258. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19259. case TAKdiskread:
  19260. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19261. case TAKdisknormalize:
  19262. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  19263. case TAKdiskcount:
  19264. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19265. case TAKdiskaggregate:
  19266. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19267. case TAKdiskgroupaggregate:
  19268. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19269. }
  19270. throwUnexpected();
  19271. }
  19272. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19273. {
  19274. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  19275. }
  19276. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19277. {
  19278. if (datafile)
  19279. addXrefFileInfo(reply, datafile);
  19280. else
  19281. {
  19282. // Temporarily resolve the file
  19283. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19284. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  19285. {
  19286. OwnedRoxieString fileName(helper->getFileName());
  19287. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  19288. if (temp)
  19289. addXrefFileInfo(reply, temp);
  19290. }
  19291. }
  19292. }
  19293. virtual const StatisticsMapping &queryStatsMapping() const
  19294. {
  19295. return diskStatistics;
  19296. }
  19297. };
  19298. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19299. {
  19300. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19301. }
  19302. //=================================================================================
  19303. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  19304. {
  19305. protected:
  19306. IHThorIndexReadBaseArg &indexHelper;
  19307. IHThorSteppedSourceExtra * steppedExtra;
  19308. Linked<IKeyArray> keySet;
  19309. Linked<TranslatorArray> translators;
  19310. CSkippableRemoteResultAdaptor remote;
  19311. CIndexTransformCallback callback;
  19312. bool sorted;
  19313. bool variableFileName;
  19314. bool variableInfoPending;
  19315. bool isOpt;
  19316. bool isLocal;
  19317. unsigned __int64 rowLimit;
  19318. unsigned __int64 keyedLimit;
  19319. unsigned __int64 choosenLimit;
  19320. unsigned accepted;
  19321. unsigned rejected;
  19322. unsigned seekGEOffset;
  19323. Owned<IKeyManager> tlk;
  19324. Owned<const IResolvedFile> varFileInfo;
  19325. const RemoteActivityId &remoteId;
  19326. void setVariableFileInfo()
  19327. {
  19328. OwnedRoxieString indexName(indexHelper.getFileName());
  19329. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19330. if (varFileInfo)
  19331. {
  19332. translators.setown(new TranslatorArray) ;
  19333. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19334. }
  19335. variableInfoPending = false;
  19336. }
  19337. public:
  19338. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19339. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19340. : CRoxieServerActivity(_factory, _probeManager),
  19341. keySet(_keySet),
  19342. translators(_translators),
  19343. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  19344. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  19345. remoteId(_remoteId),
  19346. sorted(_sorted),
  19347. isLocal(_isLocal)
  19348. {
  19349. indexHelper.setCallback(&callback);
  19350. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19351. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19352. variableInfoPending = false;
  19353. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  19354. seekGEOffset = 0;
  19355. // started = false;
  19356. rejected = accepted = 0;
  19357. rowLimit = choosenLimit = keyedLimit = 0;
  19358. }
  19359. virtual const IResolvedFile *queryVarFileInfo() const
  19360. {
  19361. return varFileInfo;
  19362. }
  19363. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  19364. {
  19365. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  19366. remote.onCreate(this, this, _ctx, _colocalParent);
  19367. }
  19368. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19369. {
  19370. accepted = 0;
  19371. rejected = 0;
  19372. rowLimit = (unsigned __int64) -1;
  19373. keyedLimit = (unsigned __int64 ) -1;
  19374. choosenLimit = I64C(0x7fffffffffffffff);
  19375. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19376. remote.onStart(parentExtractSize, parentExtract);
  19377. variableInfoPending = variableFileName;
  19378. }
  19379. void processAllKeys()
  19380. {
  19381. try
  19382. {
  19383. if (indexHelper.canMatchAny())
  19384. {
  19385. if (variableInfoPending)
  19386. setVariableFileInfo();
  19387. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  19388. if (keySet)
  19389. {
  19390. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  19391. // 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
  19392. // However order is probably better to iterate fileno's inside partnos
  19393. // MORE - also not properly supporting STEPPED I fear.
  19394. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  19395. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  19396. {
  19397. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  19398. if (thisBase)
  19399. {
  19400. unsigned fileNo = 0;
  19401. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  19402. if (!thisKey->isTopLevelKey())
  19403. {
  19404. if (keyedLimit != (unsigned __int64) -1)
  19405. {
  19406. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19407. {
  19408. Owned<IKeyManager> countKey;
  19409. countKey.setown(createKeyManager(thisKey, 0, this));
  19410. countKey->setLayoutTranslator(translators->item(fileNo));
  19411. createSegmentMonitors(countKey);
  19412. unsigned __int64 count = countKey->checkCount(keyedLimit);
  19413. if (count > keyedLimit)
  19414. {
  19415. if (traceLevel > 4)
  19416. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19417. onLimitExceeded(true);
  19418. }
  19419. }
  19420. }
  19421. }
  19422. if (seekGEOffset && !thisKey->isTopLevelKey())
  19423. {
  19424. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  19425. }
  19426. else
  19427. {
  19428. tlk.setown(createKeyManager(thisKey, 0, this));
  19429. tlk->setLayoutTranslator(translators->item(fileNo));
  19430. }
  19431. createSegmentMonitors(tlk);
  19432. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19433. {
  19434. StringBuffer out;
  19435. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19436. CTXLOG("Using filter %s", out.str());
  19437. if (ctx->queryProbeManager())
  19438. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19439. }
  19440. tlk->reset();
  19441. loop // for each file part
  19442. {
  19443. //block for TransformCallbackAssociation
  19444. {
  19445. TransformCallbackAssociation associate(callback, tlk);
  19446. if (thisKey->isTopLevelKey())
  19447. {
  19448. if (thisKey->isFullySorted())
  19449. {
  19450. while (tlk->lookup(false))
  19451. {
  19452. unsigned slavePart = (unsigned) tlk->queryFpos();
  19453. if (slavePart)
  19454. {
  19455. accepted++;
  19456. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  19457. if (sorted && numChannels>1)
  19458. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  19459. }
  19460. }
  19461. }
  19462. else
  19463. {
  19464. // MORE - we could check whether there are any matching parts if we wanted.
  19465. // If people are in the habit of sending null values that would be worthwhile
  19466. remote.getMem(0, fileNo, 0);
  19467. }
  19468. }
  19469. else
  19470. {
  19471. if (processSingleKey(thisKey, translators->item(fileNo)))
  19472. break;
  19473. }
  19474. }
  19475. if (++fileNo < thisBase->numParts())
  19476. {
  19477. thisKey = thisBase->queryPart(fileNo);
  19478. tlk->setKey(thisKey);
  19479. tlk->setLayoutTranslator(translators->item(fileNo));
  19480. tlk->reset();
  19481. }
  19482. else
  19483. break;
  19484. }
  19485. tlk->releaseSegmentMonitors();
  19486. tlk->setKey(NULL);
  19487. }
  19488. }
  19489. }
  19490. }
  19491. remote.flush();
  19492. remote.senddone();
  19493. }
  19494. catch (IException *E)
  19495. {
  19496. remote.setException(E);
  19497. }
  19498. }
  19499. virtual void createSegmentMonitors(IKeyManager *key)
  19500. {
  19501. indexHelper.createSegmentMonitors(key);
  19502. key->finishSegmentMonitors();
  19503. }
  19504. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  19505. virtual void reset()
  19506. {
  19507. if (accepted)
  19508. noteStatistic(StNumIndexAccepted, accepted);
  19509. if (rejected)
  19510. noteStatistic(StNumIndexRejected, rejected);
  19511. remote.onReset();
  19512. CRoxieServerActivity::reset();
  19513. if (varFileInfo)
  19514. {
  19515. keySet.clear();
  19516. varFileInfo.clear();
  19517. }
  19518. variableInfoPending = false;
  19519. }
  19520. virtual void stop(bool aborting)
  19521. {
  19522. remote.onStop(aborting);
  19523. CRoxieServerActivity::stop(aborting);
  19524. }
  19525. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19526. {
  19527. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19528. }
  19529. };
  19530. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  19531. {
  19532. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19533. public:
  19534. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19535. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19536. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  19537. {
  19538. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19539. }
  19540. virtual void reset()
  19541. {
  19542. remote.onReset();
  19543. CRoxieServerIndexActivity::reset();
  19544. }
  19545. virtual const void *nextInGroup()
  19546. {
  19547. ActivityTimer t(totalCycles, timeActivities);
  19548. try
  19549. {
  19550. const void *ret = remote.nextInGroup();
  19551. if (ret)
  19552. processed++;
  19553. return ret;
  19554. }
  19555. catch (IException *E)
  19556. {
  19557. throw makeWrappedException(E);
  19558. }
  19559. }
  19560. protected:
  19561. virtual const void * createLimitFailRow(bool isKeyed)
  19562. {
  19563. createRowAllocator();
  19564. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19565. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19566. if (outSize)
  19567. return rowBuilder.finalizeRowClear(outSize);
  19568. return NULL;
  19569. }
  19570. };
  19571. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  19572. {
  19573. protected:
  19574. IHThorCompoundReadExtra & readHelper;
  19575. ISteppingMeta *rawMeta;
  19576. CSteppingMeta steppingMeta;
  19577. unsigned * seekSizes;
  19578. bool optimizeSteppedPostFilter;
  19579. ISteppingMeta * projectedMeta;
  19580. unsigned maxSeekLookahead;
  19581. public:
  19582. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19583. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  19584. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  19585. readHelper((IHThorIndexReadArg &)basehelper)
  19586. {
  19587. rawMeta = readHelper.queryRawSteppingMeta();
  19588. unsigned flags = indexHelper.getFlags();
  19589. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19590. seekSizes = NULL;
  19591. maxSeekLookahead = _maxSeekLookahead;
  19592. if (rawMeta)
  19593. {
  19594. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19595. unsigned maxFields = rawMeta->getNumFields();
  19596. seekGEOffset = fields[0].offset;
  19597. seekSizes = new unsigned[maxFields];
  19598. seekSizes[0] = fields[0].size;
  19599. for (unsigned i=1; i < maxFields; i++)
  19600. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19601. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19602. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  19603. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  19604. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19605. steppingMeta.init(useMeta, hasPostFilter);
  19606. }
  19607. }
  19608. ~CRoxieServerIndexReadActivity()
  19609. {
  19610. delete [] seekSizes;
  19611. }
  19612. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19613. {
  19614. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19615. steppingMeta.setDistributed();
  19616. if (steppedExtra)
  19617. steppingMeta.setExtra(steppedExtra);
  19618. rowLimit = readHelper.getRowLimit();
  19619. keyedLimit = readHelper.getKeyedLimit();
  19620. choosenLimit = readHelper.getChooseNLimit();
  19621. if (!paused)
  19622. processAllKeys();
  19623. }
  19624. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  19625. {
  19626. public:
  19627. IMPLEMENT_IINTERFACE;
  19628. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  19629. {
  19630. Link();
  19631. return const_cast<LazyLocalKeyReader*> (this);
  19632. }
  19633. virtual const void *getMessageHeader(unsigned &length) const
  19634. {
  19635. length = 0;
  19636. return NULL;
  19637. }
  19638. virtual const void *getMessageMetadata(unsigned &length) const
  19639. {
  19640. length = 0;
  19641. return NULL;
  19642. }
  19643. virtual void discard() const
  19644. {
  19645. // nothing to do.
  19646. }
  19647. unsigned keyedCount;
  19648. unsigned matched;
  19649. bool EOFseen;
  19650. Owned<IKeyIndexSet> keySet;
  19651. Owned<IKeyManager> tlk;
  19652. CRoxieServerIndexReadActivity &owner;
  19653. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19654. : owner(_owner)
  19655. {
  19656. keyedCount = 0;
  19657. matched = 0;
  19658. EOFseen = false;
  19659. keySet.setown(createKeyIndexSet());
  19660. keySet->addIndex(LINK(key));
  19661. if (owner.seekGEOffset)
  19662. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19663. else
  19664. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19665. tlk->setLayoutTranslator(trans);
  19666. owner.indexHelper.createSegmentMonitors(tlk);
  19667. tlk->finishSegmentMonitors();
  19668. tlk->reset();
  19669. }
  19670. virtual const void *getNext(int length)
  19671. {
  19672. TransformCallbackAssociation associate(owner.callback, tlk);
  19673. while (tlk->lookup(true))
  19674. {
  19675. keyedCount++;
  19676. if (keyedCount > owner.keyedLimit)
  19677. {
  19678. owner.onLimitExceeded(true); // Should throw exception
  19679. throwUnexpected();
  19680. }
  19681. size32_t transformedSize;
  19682. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19683. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19684. try
  19685. {
  19686. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19687. owner.callback.finishedRow();
  19688. }
  19689. catch (IException *E)
  19690. {
  19691. throw owner.makeWrappedException(E);
  19692. }
  19693. if (transformedSize)
  19694. {
  19695. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19696. matched++;
  19697. if (matched > owner.rowLimit)
  19698. {
  19699. owner.onLimitExceeded(false); // Should throw exception
  19700. throwUnexpected();
  19701. }
  19702. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19703. {
  19704. break;
  19705. }
  19706. owner.accepted++;
  19707. return result.getClear();
  19708. }
  19709. else
  19710. owner.rejected++;
  19711. }
  19712. EOFseen = true;
  19713. return NULL;
  19714. }
  19715. virtual bool atEOF() const
  19716. {
  19717. return EOFseen;
  19718. }
  19719. virtual bool isSerialized() const
  19720. {
  19721. return false;
  19722. }
  19723. };
  19724. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19725. {
  19726. createRowAllocator();
  19727. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19728. return false;
  19729. }
  19730. virtual void onLimitExceeded(bool isKeyed)
  19731. {
  19732. if (traceLevel > 4)
  19733. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19734. if (isKeyed)
  19735. {
  19736. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19737. {
  19738. if (ctx->queryDebugContext())
  19739. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19740. throw makeLimitSkipException(true);
  19741. }
  19742. else
  19743. readHelper.onKeyedLimitExceeded();
  19744. }
  19745. else
  19746. {
  19747. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19748. {
  19749. if (ctx->queryDebugContext())
  19750. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19751. throw makeLimitSkipException(false);
  19752. }
  19753. else
  19754. readHelper.onLimitExceeded();
  19755. }
  19756. }
  19757. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19758. {
  19759. out.append((unsigned short) numFields);
  19760. out.append((unsigned short) seekLen);
  19761. out.append((unsigned short) stepExtra.queryFlags());
  19762. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19763. if (seeks)
  19764. {
  19765. unsigned lookahead = 40000/seekLen;
  19766. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19767. lookahead = maxSeekLookahead;
  19768. seeks->ensureFilled(seek, numFields, lookahead);
  19769. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19770. unsigned serialized = 1; // rawseek is always serialized...
  19771. unsigned patchLength = out.length();
  19772. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19773. out.append(seekLen, rawSeek);
  19774. if (seeks->ordinality())
  19775. {
  19776. const void *lastSeek = rawSeek;
  19777. byte *nextSeek = NULL;
  19778. if (projectedMeta)
  19779. nextSeek = (byte *) alloca(seekLen);
  19780. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19781. {
  19782. if (projectedMeta)
  19783. {
  19784. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19785. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19786. }
  19787. else
  19788. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19789. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19790. if (diff > 0)
  19791. {
  19792. serialized++;
  19793. out.append(seekLen, nextSeek);
  19794. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19795. }
  19796. }
  19797. unsigned length = out.length();
  19798. out.setWritePos(patchLength);
  19799. out.append(serialized);
  19800. out.setWritePos(length);
  19801. }
  19802. }
  19803. else
  19804. {
  19805. out.append(false);
  19806. out.append(1);
  19807. out.append(seekLen, rawSeek);
  19808. }
  19809. }
  19810. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19811. {
  19812. ActivityTimer t(totalCycles, timeActivities);
  19813. try
  19814. {
  19815. unsigned seeklen = 0;
  19816. const void *rawSeek = NULL;
  19817. if (seek && numFields)
  19818. {
  19819. seeklen = seekSizes[numFields-1];
  19820. rawSeek = (const byte *)seek + seekGEOffset;
  19821. if (projectedMeta)
  19822. {
  19823. byte * temp = (byte *) alloca(seeklen);
  19824. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19825. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19826. rawSeek = (byte *)temp;
  19827. }
  19828. }
  19829. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19830. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19831. processed++;
  19832. return ret;
  19833. }
  19834. catch (IException *E)
  19835. {
  19836. throw makeWrappedException(E);
  19837. }
  19838. }
  19839. virtual IInputSteppingMeta * querySteppingMeta()
  19840. {
  19841. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19842. return &steppingMeta;
  19843. return NULL;
  19844. }
  19845. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19846. {
  19847. if (variableInfoPending)
  19848. setVariableFileInfo();
  19849. return this;
  19850. }
  19851. virtual IKeyArray *getKeySet() const
  19852. {
  19853. return keySet.getLink();
  19854. }
  19855. virtual const IResolvedFile *getVarFileInfo() const
  19856. {
  19857. return varFileInfo.getLink();
  19858. }
  19859. virtual TranslatorArray *getTranslators() const
  19860. {
  19861. return translators.getLink();
  19862. }
  19863. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19864. {
  19865. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19866. }
  19867. virtual IRoxieServerActivity *queryActivity() { return this; }
  19868. virtual const RemoteActivityId& queryRemoteId() const
  19869. {
  19870. return remoteId;
  19871. }
  19872. };
  19873. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19874. {
  19875. IHThorCompoundReadExtra & readHelper;
  19876. IHThorIndexReadBaseArg & indexHelper;
  19877. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19878. IHThorSteppedSourceExtra * steppedExtra;
  19879. bool eof;
  19880. Linked<IKeyArray>keySet;
  19881. Owned<IKeyIndexSet>keyIndexSet;
  19882. Owned<IKeyManager> tlk;
  19883. Linked<TranslatorArray> translators;
  19884. CIndexTransformCallback callback;
  19885. unsigned __int64 keyedLimit;
  19886. unsigned rowLimit;
  19887. unsigned chooseNLimit;
  19888. unsigned accepted;
  19889. unsigned rejected;
  19890. unsigned keyedCount;
  19891. ISteppingMeta * rawMeta;
  19892. ISteppingMeta * projectedMeta;
  19893. size32_t seekGEOffset;
  19894. unsigned * seekSizes;
  19895. CSteppingMeta steppingMeta;
  19896. Owned<const IResolvedFile> varFileInfo;
  19897. const RemoteActivityId &remoteId;
  19898. bool firstRead;
  19899. bool variableFileName;
  19900. bool variableInfoPending;
  19901. bool isOpt;
  19902. bool isLocal;
  19903. bool optimizeSteppedPostFilter;
  19904. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19905. void initKeySet()
  19906. {
  19907. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19908. {
  19909. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19910. }
  19911. keyIndexSet.setown(createKeyIndexSet());
  19912. for (unsigned part = 0; part < keySet->length(); part++)
  19913. {
  19914. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19915. if (kib)
  19916. {
  19917. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19918. {
  19919. IKeyIndex *k = kib->queryPart(subpart);
  19920. if (k)
  19921. {
  19922. assertex(!k->isTopLevelKey());
  19923. keyIndexSet->addIndex(LINK(k));
  19924. }
  19925. }
  19926. }
  19927. }
  19928. }
  19929. void setVariableFileInfo()
  19930. {
  19931. OwnedRoxieString indexName(indexHelper.getFileName());
  19932. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19933. translators.setown(new TranslatorArray) ;
  19934. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19935. initKeySet();
  19936. variableInfoPending = false;
  19937. }
  19938. void onEOF()
  19939. {
  19940. callback.setManager(NULL);
  19941. eof = true;
  19942. tlk.clear();
  19943. }
  19944. public:
  19945. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19946. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19947. : CRoxieServerActivity(_factory, _probeManager),
  19948. readHelper((IHThorIndexReadArg &)basehelper),
  19949. indexHelper((IHThorIndexReadArg &)basehelper),
  19950. translators(_translatorArray),
  19951. keySet(_keyArray),
  19952. isLocal(_isLocal),
  19953. remoteId(_remoteId)
  19954. {
  19955. rowLimit = 0;
  19956. keyedLimit = 0;
  19957. chooseNLimit = 0;
  19958. indexHelper.setCallback(&callback);
  19959. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19960. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19961. unsigned flags = indexHelper.getFlags();
  19962. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19963. variableInfoPending = false;
  19964. isOpt = (flags & TIRoptional) != 0;
  19965. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19966. firstRead = true;
  19967. accepted = 0;
  19968. rejected = 0;
  19969. keyedCount = 0;
  19970. eof = false;
  19971. rawMeta = readHelper.queryRawSteppingMeta();
  19972. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19973. seekGEOffset = 0;
  19974. seekSizes = NULL;
  19975. if (rawMeta)
  19976. {
  19977. // MORE - should check all keys in maxFields list can actually be keyed.
  19978. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19979. unsigned maxFields = rawMeta->getNumFields();
  19980. seekGEOffset = fields[0].offset;
  19981. seekSizes = new unsigned[maxFields];
  19982. seekSizes[0] = fields[0].size;
  19983. for (unsigned i=1; i < maxFields; i++)
  19984. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19985. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19986. if (projectedMeta)
  19987. steppingMeta.init(projectedMeta, hasPostFilter);
  19988. else
  19989. steppingMeta.init(rawMeta, hasPostFilter);
  19990. }
  19991. }
  19992. virtual const IResolvedFile *queryVarFileInfo() const
  19993. {
  19994. return varFileInfo;
  19995. }
  19996. ~CRoxieServerSimpleIndexReadActivity()
  19997. {
  19998. delete [] seekSizes;
  19999. }
  20000. virtual bool needsAllocator() const { return true; }
  20001. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20002. {
  20003. firstRead = true;
  20004. accepted = 0;
  20005. rejected = 0;
  20006. keyedCount = 0;
  20007. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20008. if (steppedExtra)
  20009. steppingMeta.setExtra(steppedExtra);
  20010. eof = !indexHelper.canMatchAny();
  20011. if (variableFileName)
  20012. variableInfoPending = true;
  20013. else
  20014. {
  20015. variableInfoPending = false;
  20016. if (!keyIndexSet)
  20017. initKeySet();
  20018. }
  20019. }
  20020. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20021. {
  20022. if (variableInfoPending)
  20023. setVariableFileInfo();
  20024. return this;
  20025. }
  20026. virtual IKeyArray *getKeySet() const
  20027. {
  20028. return keySet.getLink();
  20029. }
  20030. virtual const IResolvedFile *getVarFileInfo() const
  20031. {
  20032. return varFileInfo.getLink();
  20033. }
  20034. virtual TranslatorArray *getTranslators() const
  20035. {
  20036. return translators.getLink();
  20037. }
  20038. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20039. {
  20040. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20041. }
  20042. virtual IRoxieServerActivity *queryActivity() { return this; }
  20043. virtual const RemoteActivityId& queryRemoteId() const
  20044. {
  20045. return remoteId;
  20046. }
  20047. const void *nextInGroup()
  20048. {
  20049. bool matched = true;
  20050. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  20051. }
  20052. unsigned __int64 checkCount(unsigned __int64 limit)
  20053. {
  20054. unsigned numParts = keyIndexSet->numParts();
  20055. unsigned __int64 result = 0;
  20056. for (unsigned i = 0; i < numParts; i++)
  20057. {
  20058. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20059. countTlk->setLayoutTranslator(translators->item(i));
  20060. indexHelper.createSegmentMonitors(countTlk);
  20061. countTlk->finishSegmentMonitors();
  20062. result += countTlk->checkCount(limit-result);
  20063. if (result > limit)
  20064. break;
  20065. }
  20066. return result;
  20067. }
  20068. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20069. {
  20070. ActivityTimer t(totalCycles, timeActivities);
  20071. if (eof)
  20072. return NULL;
  20073. if (firstRead)
  20074. {
  20075. if (variableInfoPending)
  20076. setVariableFileInfo();
  20077. rowLimit = (unsigned) readHelper.getRowLimit();
  20078. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20079. unsigned numParts = keyIndexSet->numParts();
  20080. if (!numParts)
  20081. {
  20082. onEOF();
  20083. return NULL;
  20084. }
  20085. if (numParts > 1 || seekGEOffset)
  20086. {
  20087. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20088. // note that we don't set up translator because we don't support it. If that ever changes...
  20089. }
  20090. else
  20091. {
  20092. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20093. tlk->setLayoutTranslator(translators->item(0));
  20094. }
  20095. indexHelper.createSegmentMonitors(tlk);
  20096. tlk->finishSegmentMonitors();
  20097. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20098. {
  20099. StringBuffer out;
  20100. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20101. CTXLOG("Using filter %s", out.str());
  20102. if (ctx->queryProbeManager())
  20103. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20104. }
  20105. tlk->reset();
  20106. callback.setManager(tlk);
  20107. keyedLimit = readHelper.getKeyedLimit();
  20108. if (keyedLimit != (unsigned __int64) -1)
  20109. {
  20110. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20111. {
  20112. unsigned __int64 count = checkCount(keyedLimit);
  20113. if (count > keyedLimit)
  20114. {
  20115. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20116. readHelper.onKeyedLimitExceeded();
  20117. const void * ret = NULL;
  20118. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20119. ret = createKeyedLimitOnFailRow();
  20120. onEOF();
  20121. return ret;
  20122. }
  20123. keyedLimit = (unsigned __int64) -1;
  20124. }
  20125. }
  20126. firstRead = false;
  20127. }
  20128. if (accepted == chooseNLimit)
  20129. {
  20130. onEOF();
  20131. return NULL;
  20132. }
  20133. const byte * rawSeek = NULL;
  20134. unsigned seekSize = 0;
  20135. if (seek)
  20136. {
  20137. seekSize = seekSizes[numFields-1];
  20138. rawSeek = (const byte *)seek + seekGEOffset;
  20139. if (projectedMeta)
  20140. {
  20141. byte *temp = (byte *) alloca(seekSize);
  20142. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20143. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20144. rawSeek = (byte *)temp;
  20145. }
  20146. #ifdef _DEBUG
  20147. // StringBuffer seekStr;
  20148. // for (unsigned i = 0; i < seekSize; i++)
  20149. // {
  20150. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  20151. // }
  20152. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  20153. #endif
  20154. }
  20155. const byte * originalRawSeek = rawSeek;
  20156. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20157. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  20158. {
  20159. checkAbort();
  20160. keyedCount++;
  20161. if (keyedCount > keyedLimit)
  20162. {
  20163. readHelper.onKeyedLimitExceeded();
  20164. break;
  20165. }
  20166. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  20167. #ifdef _DEBUG
  20168. // StringBuffer recstr;
  20169. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  20170. // for (unsigned i = 0; i < size; i++)
  20171. // {
  20172. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  20173. // }
  20174. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  20175. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  20176. assertex(!"smart seek failure");
  20177. #endif
  20178. size32_t transformedSize;
  20179. rowBuilder.ensureRow();
  20180. try
  20181. {
  20182. transformedSize = readHelper.transform(rowBuilder, keyRow);
  20183. //if the post filter causes a mismatch, and the stepping condition no longer matches
  20184. //then return a mismatch record - so the join code can start seeking on the other input.
  20185. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  20186. {
  20187. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  20188. {
  20189. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  20190. if (transformedSize != 0)
  20191. wasCompleteMatch = false;
  20192. }
  20193. }
  20194. callback.finishedRow();
  20195. }
  20196. catch (IException *E)
  20197. {
  20198. throw makeWrappedException(E);
  20199. }
  20200. if (transformedSize)
  20201. {
  20202. accepted++;
  20203. if (accepted > rowLimit)
  20204. {
  20205. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  20206. {
  20207. throwUnexpected(); // should not have used simple variant if maySkip set...
  20208. }
  20209. if (traceLevel > 4)
  20210. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20211. readHelper.onLimitExceeded();
  20212. break;
  20213. }
  20214. processed++;
  20215. #ifdef _DEBUG
  20216. // const byte *ret = (const byte *) out.get();
  20217. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  20218. // queryOutputMeta()->toXML(ret, xmlwrite);
  20219. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  20220. #endif
  20221. return rowBuilder.finalizeRowClear(transformedSize);
  20222. }
  20223. else
  20224. rejected++;
  20225. rawSeek = NULL;
  20226. }
  20227. onEOF();
  20228. return NULL;
  20229. }
  20230. virtual void reset()
  20231. {
  20232. onEOF();
  20233. if (accepted)
  20234. noteStatistic(StNumIndexAccepted, accepted);
  20235. if (rejected)
  20236. noteStatistic(StNumIndexRejected, rejected);
  20237. if (variableFileName)
  20238. {
  20239. varFileInfo.clear();
  20240. translators.clear();
  20241. }
  20242. variableInfoPending = false;
  20243. CRoxieServerActivity::reset();
  20244. }
  20245. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20246. {
  20247. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20248. }
  20249. virtual IInputSteppingMeta * querySteppingMeta()
  20250. {
  20251. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20252. return &steppingMeta;
  20253. return NULL;
  20254. }
  20255. protected:
  20256. const void * createKeyedLimitOnFailRow()
  20257. {
  20258. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20259. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  20260. if (outSize)
  20261. return rowBuilder.finalizeRowClear(outSize);
  20262. return NULL;
  20263. }
  20264. };
  20265. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20266. {
  20267. public:
  20268. Owned<IKeyArray> keySet;
  20269. Owned<TranslatorArray> translatorArray;
  20270. Owned<IDefRecordMeta> activityMeta;
  20271. RemoteActivityId remoteId;
  20272. bool isSimple;
  20273. bool isLocal;
  20274. bool maySkip;
  20275. bool sorted;
  20276. bool variableFileName;
  20277. bool enableFieldTranslation;
  20278. unsigned maxSeekLookahead;
  20279. Owned<const IResolvedFile> indexfile;
  20280. CRoxieServerSideCache *cache;
  20281. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20282. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20283. {
  20284. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20285. unsigned flags = indexHelper->getFlags();
  20286. sorted = (flags & TIRunordered) == 0;
  20287. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20288. rtlDataAttr indexLayoutMeta;
  20289. size32_t indexLayoutSize;
  20290. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  20291. assertex(indexLayoutSize==0);
  20292. MemoryBuffer m;
  20293. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  20294. activityMeta.setown(deserializeRecordMeta(m, true));
  20295. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  20296. translatorArray.setown(new TranslatorArray);
  20297. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20298. if (!variableFileName)
  20299. {
  20300. bool isOpt = (flags & TIRoptional) != 0;
  20301. OwnedRoxieString indexName(indexHelper->getFileName());
  20302. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  20303. if (indexfile)
  20304. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  20305. }
  20306. isSimple = isLocal;
  20307. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20308. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20309. {
  20310. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20311. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20312. isSimple = true;
  20313. }
  20314. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20315. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20316. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20317. }
  20318. ~CRoxieServerBaseIndexActivityFactory()
  20319. {
  20320. delete cache;
  20321. }
  20322. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20323. {
  20324. if (indexfile)
  20325. addXrefFileInfo(reply, indexfile);
  20326. else
  20327. {
  20328. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20329. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20330. {
  20331. OwnedRoxieString indexName(indexHelper->getFileName());
  20332. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  20333. if (temp)
  20334. addXrefFileInfo(reply, temp);
  20335. }
  20336. }
  20337. }
  20338. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20339. {
  20340. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20341. }
  20342. virtual IRoxieServerSideCache *queryServerSideCache() const
  20343. {
  20344. return cache;
  20345. }
  20346. virtual bool getEnableFieldTranslation() const
  20347. {
  20348. return enableFieldTranslation;
  20349. }
  20350. virtual IDefRecordMeta *queryActivityMeta() const
  20351. {
  20352. return activityMeta;
  20353. }
  20354. virtual const StatisticsMapping &queryStatsMapping() const
  20355. {
  20356. return indexStatistics;
  20357. }
  20358. };
  20359. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20360. {
  20361. public:
  20362. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20363. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20364. {
  20365. }
  20366. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20367. {
  20368. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20369. return new CRoxieServerNullActivity(this, _probeManager);
  20370. else if (isSimple && !maySkip)
  20371. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20372. else
  20373. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  20374. }
  20375. };
  20376. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20377. {
  20378. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20379. }
  20380. //--------------------------------------------------------------------------------------------------------------------------
  20381. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  20382. {
  20383. bool done;
  20384. public:
  20385. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20386. : CRoxieServerActivity(_factory, _probeManager)
  20387. {
  20388. done = false;
  20389. }
  20390. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20391. {
  20392. done = false;
  20393. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20394. }
  20395. virtual bool needsAllocator() const { return true; }
  20396. virtual const void *nextInGroup()
  20397. {
  20398. ActivityTimer t(totalCycles, timeActivities);
  20399. if (done) return NULL;
  20400. done = true;
  20401. size32_t rowSize = meta.getFixedSize();
  20402. void * nullRow = rowAllocator->createRow();
  20403. if (rowSize == 1)
  20404. *(byte *)nullRow = 0;
  20405. else
  20406. {
  20407. assertex(rowSize == sizeof(unsigned __int64));
  20408. *(unsigned __int64 *)nullRow = 0;
  20409. }
  20410. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  20411. }
  20412. };
  20413. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  20414. {
  20415. IHThorCompoundCountExtra & countHelper;
  20416. IHThorSourceCountLimit * limitHelper;
  20417. bool done;
  20418. public:
  20419. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20420. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20421. countHelper((IHThorIndexCountArg &)basehelper),
  20422. done(false)
  20423. {
  20424. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  20425. }
  20426. virtual bool needsAllocator() const { return true; }
  20427. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20428. {
  20429. done = false;
  20430. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20431. choosenLimit = countHelper.getChooseNLimit();
  20432. if (limitHelper)
  20433. {
  20434. rowLimit = limitHelper->getRowLimit();
  20435. keyedLimit = limitHelper->getKeyedLimit();
  20436. }
  20437. if (!paused)
  20438. processAllKeys();
  20439. }
  20440. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20441. {
  20442. unsigned __int64 count = 0;
  20443. if (countHelper.hasFilter())
  20444. {
  20445. while (tlk->lookup(true))
  20446. {
  20447. try
  20448. {
  20449. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  20450. callback.finishedRow();
  20451. }
  20452. catch (IException *E)
  20453. {
  20454. throw makeWrappedException(E);
  20455. }
  20456. accepted++;
  20457. if (count >= choosenLimit) // MORE - what about limit?
  20458. break;
  20459. }
  20460. }
  20461. else
  20462. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  20463. if (count)
  20464. {
  20465. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  20466. if (count > choosenLimit)
  20467. count = choosenLimit;
  20468. void * recBuffer = rowAllocator->createRow();
  20469. if (meta.getFixedSize() == 1)
  20470. *(byte *)recBuffer = (byte)count;
  20471. else
  20472. {
  20473. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20474. *(unsigned __int64 *)recBuffer = count;
  20475. }
  20476. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  20477. result->append(recBuffer);
  20478. remote.injectResult(result.getClear());
  20479. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  20480. if (count >= choosenLimit)
  20481. return true;
  20482. }
  20483. return false;
  20484. }
  20485. virtual void onLimitExceeded(bool isKeyed)
  20486. {
  20487. if (traceLevel > 4)
  20488. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20489. if (isKeyed)
  20490. {
  20491. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20492. {
  20493. if (ctx->queryDebugContext())
  20494. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20495. throw makeLimitSkipException(true);
  20496. }
  20497. else
  20498. {
  20499. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  20500. limitHelper->onKeyedLimitExceeded();
  20501. }
  20502. }
  20503. else
  20504. {
  20505. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20506. {
  20507. if (ctx->queryDebugContext())
  20508. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20509. throw makeLimitSkipException(false);
  20510. }
  20511. else
  20512. {
  20513. assertex(limitHelper);
  20514. limitHelper->onLimitExceeded();
  20515. }
  20516. }
  20517. }
  20518. virtual const void *createLimitFailRow(bool isKeyed)
  20519. {
  20520. throwUnexpected();
  20521. }
  20522. virtual const void *nextInGroup()
  20523. {
  20524. ActivityTimer t(totalCycles, timeActivities);
  20525. if (done) return NULL;
  20526. done = true;
  20527. unsigned __int64 totalCount = 0;
  20528. bool hasLimit = rowLimit != (unsigned __int64) -1;
  20529. try
  20530. {
  20531. loop
  20532. {
  20533. const void * next = remote.nextInGroup();
  20534. if (!next)
  20535. break;
  20536. if (meta.getFixedSize() == 1)
  20537. totalCount += *(byte *)next;
  20538. else
  20539. totalCount += *(unsigned __int64 *) next;
  20540. ReleaseRoxieRow(next);
  20541. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  20542. break;
  20543. }
  20544. if (totalCount > rowLimit)
  20545. {
  20546. unsigned flags = indexHelper.getFlags();
  20547. if (flags & TIRlimitskips)
  20548. totalCount = 0;
  20549. else if (flags & TIRlimitcreates)
  20550. totalCount = 1;
  20551. else
  20552. {
  20553. assertex(limitHelper);
  20554. limitHelper->onLimitExceeded();
  20555. }
  20556. }
  20557. else if (totalCount > choosenLimit)
  20558. totalCount = choosenLimit;
  20559. }
  20560. catch (IException *E)
  20561. {
  20562. if (QUERYINTERFACE(E, LimitSkipException))
  20563. {
  20564. totalCount = 0;
  20565. unsigned flags = indexHelper.getFlags();
  20566. if (E->errorCode() == KeyedLimitSkipErrorCode)
  20567. {
  20568. if (flags & TIRkeyedlimitcreates)
  20569. totalCount++;
  20570. }
  20571. else
  20572. {
  20573. if (flags & TIRlimitcreates)
  20574. totalCount++;
  20575. }
  20576. if (totalCount > choosenLimit)
  20577. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  20578. E->Release();
  20579. }
  20580. else
  20581. throw ;
  20582. }
  20583. void * result = rowAllocator->createRow();
  20584. if (meta.getFixedSize() == 1)
  20585. *(byte *)result = (byte)totalCount;
  20586. else
  20587. {
  20588. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20589. *(unsigned __int64 *)result = totalCount;
  20590. }
  20591. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  20592. }
  20593. };
  20594. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20595. {
  20596. public:
  20597. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20598. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20599. {
  20600. }
  20601. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20602. {
  20603. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20604. return new CRoxieServerNullCountActivity(this, _probeManager);
  20605. // else if (isSimple)
  20606. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20607. else
  20608. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20609. }
  20610. };
  20611. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20612. {
  20613. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20614. }
  20615. //--------------------------------------------------------------------------------------------------------------------------
  20616. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  20617. {
  20618. IHThorIndexAggregateArg &aggregateHelper;
  20619. bool done;
  20620. public:
  20621. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20622. : CRoxieServerActivity(_factory, _probeManager),
  20623. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  20624. {
  20625. done = false;
  20626. }
  20627. virtual bool needsAllocator() const { return true; }
  20628. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20629. {
  20630. done = false;
  20631. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20632. }
  20633. virtual const void *nextInGroup()
  20634. {
  20635. ActivityTimer t(totalCycles, timeActivities);
  20636. if (done) return NULL;
  20637. done = true;
  20638. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20639. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  20640. return rowBuilder.finalizeRowClear(thisSize);
  20641. }
  20642. };
  20643. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  20644. {
  20645. IHThorCompoundAggregateExtra & aggregateHelper;
  20646. bool done;
  20647. public:
  20648. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20649. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20650. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20651. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  20652. done(false)
  20653. {
  20654. }
  20655. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20656. {
  20657. done = false;
  20658. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20659. if (!paused)
  20660. processAllKeys();
  20661. }
  20662. virtual bool needsAllocator() const { return true; }
  20663. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20664. {
  20665. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20666. while (tlk->lookup(true))
  20667. {
  20668. if (!rowBuilder.exists())
  20669. {
  20670. rowBuilder.ensureRow();
  20671. aggregateHelper.clearAggregate(rowBuilder);
  20672. }
  20673. try
  20674. {
  20675. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20676. callback.finishedRow();
  20677. }
  20678. catch (IException *E)
  20679. {
  20680. throw makeWrappedException(E);
  20681. }
  20682. accepted++;
  20683. }
  20684. if (aggregateHelper.processedAnyRows())
  20685. {
  20686. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20687. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20688. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20689. result->append(recBuffer);
  20690. remote.injectResult(result.getClear());
  20691. }
  20692. return false;
  20693. }
  20694. virtual void onLimitExceeded(bool isKeyed)
  20695. {
  20696. if (traceLevel > 4)
  20697. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20698. throwUnexpected();
  20699. }
  20700. virtual const void *createLimitFailRow(bool isKeyed)
  20701. {
  20702. throwUnexpected();
  20703. }
  20704. const void * gatherMerged()
  20705. {
  20706. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20707. const void * firstRow = remote.nextInGroup();
  20708. size32_t finalSize = 0;
  20709. if (!firstRow)
  20710. {
  20711. rowBuilder.ensureRow();
  20712. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20713. }
  20714. else
  20715. {
  20716. // NOTE need to clone this because going to modify below, could special case 1 row only
  20717. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20718. ReleaseRoxieRow(firstRow);
  20719. }
  20720. loop
  20721. {
  20722. const void * next = remote.nextInGroup();
  20723. if (!next)
  20724. break;
  20725. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20726. ReleaseRoxieRow(next);
  20727. }
  20728. return rowBuilder.finalizeRowClear(finalSize);
  20729. }
  20730. virtual const void *nextInGroup()
  20731. {
  20732. ActivityTimer t(totalCycles, timeActivities);
  20733. if (done) return NULL;
  20734. const void * ret = gatherMerged();
  20735. done = true;
  20736. return ret;
  20737. }
  20738. };
  20739. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20740. {
  20741. public:
  20742. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20743. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20744. {
  20745. }
  20746. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20747. {
  20748. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20749. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20750. // else if (isSimple)
  20751. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20752. else
  20753. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20754. }
  20755. };
  20756. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20757. {
  20758. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20759. }
  20760. //--------------------------------------------------------------------------------------------------------------------------
  20761. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20762. {
  20763. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20764. RowAggregator singleAggregator;
  20765. RowAggregator resultAggregator;
  20766. unsigned groupSegCount;
  20767. bool gathered;
  20768. bool eof;
  20769. public:
  20770. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20771. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20772. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20773. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20774. singleAggregator(aggregateHelper, aggregateHelper),
  20775. resultAggregator(aggregateHelper, aggregateHelper),
  20776. gathered(false), eof(true)
  20777. {
  20778. groupSegCount = 0;
  20779. }
  20780. IMPLEMENT_IINTERFACE
  20781. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20782. {
  20783. eof = false;
  20784. gathered= false;
  20785. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20786. groupSegCount = 0;
  20787. if (!paused)
  20788. processAllKeys();
  20789. resultAggregator.start(rowAllocator);
  20790. }
  20791. virtual bool needsAllocator() const { return true; }
  20792. virtual void reset()
  20793. {
  20794. resultAggregator.reset();
  20795. CRoxieServerIndexActivity::reset();
  20796. }
  20797. virtual void processRow(const void * next)
  20798. {
  20799. singleAggregator.addRow(next);
  20800. }
  20801. virtual void createSegmentMonitors(IKeyManager *key)
  20802. {
  20803. unsigned groupSegSize;
  20804. ThorActivityKind kind = factory->getKind();
  20805. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20806. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20807. else
  20808. groupSegSize = 0;
  20809. if (groupSegSize)
  20810. {
  20811. key->setMergeBarrier(groupSegSize);
  20812. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20813. unsigned numSegs = tlk->ordinality();
  20814. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20815. {
  20816. IKeySegmentMonitor *seg = tlk->item(segNo);
  20817. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20818. {
  20819. groupSegCount = segNo+1;
  20820. break;
  20821. }
  20822. }
  20823. assertex(groupSegCount);
  20824. }
  20825. else
  20826. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20827. }
  20828. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20829. {
  20830. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20831. singleAggregator.start(rowAllocator);
  20832. ThorActivityKind kind = factory->getKind();
  20833. while (tlk->lookup(true))
  20834. {
  20835. try
  20836. {
  20837. if (groupSegCount && !trans)
  20838. {
  20839. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20840. callback.finishedRow();
  20841. if (kind==TAKindexgroupcount)
  20842. {
  20843. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20844. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20845. }
  20846. if (!tlk->nextRange(groupSegCount))
  20847. break;
  20848. }
  20849. else
  20850. {
  20851. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20852. callback.finishedRow();
  20853. }
  20854. }
  20855. catch (IException *E)
  20856. {
  20857. throw makeWrappedException(E);
  20858. }
  20859. accepted++;
  20860. }
  20861. loop
  20862. {
  20863. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20864. if (!next)
  20865. break;
  20866. size32_t size = next->querySize();
  20867. result->append(next->finalizeRowClear());
  20868. }
  20869. remote.injectResult(result.getClear());
  20870. singleAggregator.reset();
  20871. return false;
  20872. }
  20873. virtual void onLimitExceeded(bool isKeyed)
  20874. {
  20875. if (traceLevel > 4)
  20876. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20877. throwUnexpected();
  20878. }
  20879. virtual const void *createLimitFailRow(bool isKeyed)
  20880. {
  20881. throwUnexpected();
  20882. }
  20883. void gatherMerged()
  20884. {
  20885. gathered = true;
  20886. loop
  20887. {
  20888. const void * next = remote.nextInGroup();
  20889. if (!next)
  20890. break;
  20891. resultAggregator.mergeElement(next);
  20892. ReleaseRoxieRow(next);
  20893. }
  20894. }
  20895. virtual const void *nextInGroup()
  20896. {
  20897. ActivityTimer t(totalCycles, timeActivities);
  20898. if (eof)
  20899. return NULL;
  20900. if (!gathered)
  20901. gatherMerged();
  20902. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20903. if (next)
  20904. {
  20905. processed++;
  20906. return next->finalizeRowClear();
  20907. }
  20908. eof = true;
  20909. return NULL;
  20910. }
  20911. };
  20912. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20913. {
  20914. public:
  20915. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20916. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20917. {
  20918. }
  20919. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20920. {
  20921. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20922. return new CRoxieServerNullActivity(this, _probeManager);
  20923. // else if (isSimple)
  20924. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20925. else
  20926. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20927. }
  20928. };
  20929. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20930. {
  20931. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20932. }
  20933. //--------------------------------------------------------------------------------------------------------------------------
  20934. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20935. {
  20936. IHThorCompoundNormalizeExtra & readHelper;
  20937. public:
  20938. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20939. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20940. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20941. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20942. {
  20943. }
  20944. virtual bool needsAllocator() const { return true; }
  20945. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20946. {
  20947. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20948. rowLimit = readHelper.getRowLimit();
  20949. keyedLimit = readHelper.getKeyedLimit();
  20950. choosenLimit = readHelper.getChooseNLimit();
  20951. if (!paused)
  20952. processAllKeys();
  20953. }
  20954. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20955. {
  20956. unsigned keyedCount = 0;
  20957. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20958. while (tlk->lookup(true))
  20959. {
  20960. keyedCount++;
  20961. if (keyedCount > keyedLimit)
  20962. {
  20963. if (traceLevel > 4)
  20964. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20965. onLimitExceeded(true);
  20966. break;
  20967. }
  20968. size32_t transformedSize;
  20969. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20970. {
  20971. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20972. do
  20973. {
  20974. if (accepted>=choosenLimit)
  20975. break;
  20976. rowBuilder.ensureRow();
  20977. try
  20978. {
  20979. transformedSize = readHelper.transform(rowBuilder);
  20980. }
  20981. catch (IException *E)
  20982. {
  20983. throw makeWrappedException(E);
  20984. }
  20985. if (transformedSize)
  20986. {
  20987. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20988. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20989. accepted++;
  20990. }
  20991. else
  20992. rejected++;
  20993. } while (readHelper.next());
  20994. remote.injectResult(result.getClear());
  20995. callback.finishedRow();
  20996. if (accepted>=choosenLimit)
  20997. return true;
  20998. }
  20999. }
  21000. return false;
  21001. }
  21002. virtual void onLimitExceeded(bool isKeyed)
  21003. {
  21004. if (traceLevel > 4)
  21005. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21006. if (isKeyed)
  21007. {
  21008. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21009. {
  21010. if (ctx->queryDebugContext())
  21011. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21012. throw makeLimitSkipException(true);
  21013. }
  21014. else
  21015. readHelper.onKeyedLimitExceeded();
  21016. }
  21017. else
  21018. {
  21019. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21020. {
  21021. if (ctx->queryDebugContext())
  21022. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21023. throw makeLimitSkipException(false);
  21024. }
  21025. else
  21026. readHelper.onLimitExceeded();
  21027. }
  21028. }
  21029. virtual const void *createLimitFailRow(bool isKeyed)
  21030. {
  21031. UNIMPLEMENTED;
  21032. }
  21033. };
  21034. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21035. {
  21036. public:
  21037. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21038. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  21039. {
  21040. }
  21041. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21042. {
  21043. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21044. return new CRoxieServerNullActivity(this, _probeManager);
  21045. else
  21046. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21047. }
  21048. };
  21049. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21050. {
  21051. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21052. }
  21053. //=================================================================================
  21054. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21055. {
  21056. IHThorFetchBaseArg &helper;
  21057. IHThorFetchContext * fetchContext;
  21058. Linked<IFilePartMap> map;
  21059. CRemoteResultAdaptor remote;
  21060. RecordPullerThread puller;
  21061. bool needsRHS;
  21062. bool variableFileName;
  21063. bool isOpt;
  21064. Owned<const IResolvedFile> varFileInfo;
  21065. public:
  21066. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21067. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21068. {
  21069. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21070. needsRHS = helper.transformNeedsRhs();
  21071. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21072. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21073. }
  21074. virtual const IResolvedFile *queryVarFileInfo() const
  21075. {
  21076. return varFileInfo;
  21077. }
  21078. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21079. {
  21080. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21081. remote.onCreate(this, this, _ctx, _colocalParent);
  21082. }
  21083. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21084. {
  21085. if (idx)
  21086. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21087. puller.setInput(this, _in);
  21088. }
  21089. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21090. {
  21091. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21092. remote.onStart(parentExtractSize, parentExtract);
  21093. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21094. if (variableFileName)
  21095. {
  21096. OwnedRoxieString fname(fetchContext->getFileName());
  21097. varFileInfo.setown(resolveLFN(fname, isOpt));
  21098. if (varFileInfo)
  21099. map.setown(varFileInfo->getFileMap());
  21100. }
  21101. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21102. }
  21103. virtual void stop(bool aborting)
  21104. {
  21105. // Called from remote, so no need to call back to it....
  21106. puller.stop(aborting);
  21107. CRoxieServerActivity::stop(aborting);
  21108. }
  21109. virtual void reset()
  21110. {
  21111. processed = remote.processed;
  21112. remote.processed = 0;
  21113. puller.reset();
  21114. if (variableFileName)
  21115. {
  21116. varFileInfo.clear();
  21117. map.clear();
  21118. }
  21119. CRoxieServerActivity::reset();
  21120. }
  21121. virtual IRoxieInput *queryOutput(unsigned idx)
  21122. {
  21123. if (idx==(unsigned)-1)
  21124. idx = 0;
  21125. return idx ? NULL : &remote;
  21126. }
  21127. virtual void processRow(const void *row)
  21128. {
  21129. // called from puller thread
  21130. offset_t rp = fetchContext->extractPosition(row);
  21131. unsigned partNo;
  21132. if (isLocalFpos(rp))
  21133. partNo = getLocalFposPart(rp) + 1;
  21134. else
  21135. partNo = map->mapOffset(rp);
  21136. if (needsRHS)
  21137. {
  21138. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  21139. RtlDynamicRowBuilder rb(extractAllocator, true);
  21140. unsigned rhsSize = helper.extractJoinFields(rb, row);
  21141. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  21142. *(offset_t *) block = rp;
  21143. block += sizeof(rp);
  21144. *(unsigned *) block = rhsSize;
  21145. block += sizeof(rhsSize);
  21146. memcpy(block, rb.row(), rhsSize);
  21147. }
  21148. else
  21149. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  21150. ReleaseRoxieRow(row);
  21151. }
  21152. void processEOG()
  21153. {
  21154. #ifdef FETCH_PRESERVES_GROUPING
  21155. UNIMPLEMENTED;
  21156. #endif
  21157. // else discard is correct
  21158. }
  21159. void processGroup(const ConstPointerArray &)
  21160. {
  21161. throwUnexpected();
  21162. }
  21163. void processDone()
  21164. {
  21165. // called from puller thread
  21166. remote.flush();
  21167. remote.senddone();
  21168. }
  21169. virtual bool fireException(IException *e)
  21170. {
  21171. return remote.fireException(e);
  21172. }
  21173. virtual void onLimitExceeded(bool isKeyed)
  21174. {
  21175. if (traceLevel > 4)
  21176. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21177. if (isKeyed)
  21178. throwUnexpected();
  21179. helper.onLimitExceeded();
  21180. }
  21181. virtual const void *createLimitFailRow(bool isKeyed)
  21182. {
  21183. UNIMPLEMENTED;
  21184. }
  21185. virtual const void *nextInGroup()
  21186. {
  21187. throwUnexpected(); // I am nobody's input
  21188. }
  21189. };
  21190. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  21191. {
  21192. RemoteActivityId remoteId;
  21193. Owned<IFilePartMap> map;
  21194. bool variableFileName;
  21195. Owned<const IResolvedFile> datafile;
  21196. public:
  21197. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21198. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  21199. {
  21200. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21201. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21202. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21203. if (!variableFileName)
  21204. {
  21205. OwnedRoxieString fname(fetchContext->getFileName());
  21206. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  21207. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  21208. true, true,
  21209. _queryFactory.queryWorkUnit(), true));
  21210. if (datafile)
  21211. map.setown(datafile->getFileMap());
  21212. }
  21213. }
  21214. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21215. {
  21216. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  21217. }
  21218. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21219. {
  21220. if (datafile)
  21221. addXrefFileInfo(reply, datafile);
  21222. else
  21223. {
  21224. // Temporarily resolve the file
  21225. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21226. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21227. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  21228. {
  21229. OwnedRoxieString fileName(fetchContext->getFileName());
  21230. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  21231. if (temp)
  21232. addXrefFileInfo(reply, temp);
  21233. }
  21234. }
  21235. }
  21236. virtual const StatisticsMapping &queryStatsMapping() const
  21237. {
  21238. return diskStatistics;
  21239. }
  21240. };
  21241. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21242. {
  21243. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21244. }
  21245. // MORE - is there any point keeping this now?
  21246. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  21247. {
  21248. public:
  21249. Owned<const IResolvedFile> indexfile;
  21250. Owned<const IResolvedFile> datafile;
  21251. StringAttr fileName;
  21252. StringAttr indexName;
  21253. Owned<IKeyArray> keySet;
  21254. Owned<IFileIOArray> files;
  21255. TranslatorArray layoutTranslators;
  21256. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21257. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  21258. {
  21259. try // does not want any missing file errors to be fatal, or throw traps - just log it
  21260. {
  21261. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  21262. return; // ignore 'spills'
  21263. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21264. ThorActivityKind kind = getActivityKind(_graphNode);
  21265. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  21266. {
  21267. fileName.set(queryNodeFileName(_graphNode, kind));
  21268. indexName.set(queryNodeIndexName(_graphNode, kind));
  21269. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  21270. {
  21271. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  21272. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21273. if (indexfile)
  21274. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  21275. }
  21276. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  21277. {
  21278. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  21279. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  21280. if (datafile)
  21281. {
  21282. if (isLocal)
  21283. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  21284. }
  21285. }
  21286. }
  21287. }
  21288. catch(IException *E)
  21289. {
  21290. StringBuffer errors;
  21291. E->errorMessage(errors);
  21292. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  21293. E->Release();
  21294. }
  21295. }
  21296. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), __FILE__, __LINE__); }
  21297. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21298. {
  21299. if (!allFilesDynamic)
  21300. {
  21301. if (datafile)
  21302. addXrefFileInfo(reply, datafile);
  21303. if (indexfile)
  21304. addXrefFileInfo(reply, indexfile);
  21305. }
  21306. else
  21307. {
  21308. Owned<const IResolvedFile> temp;
  21309. if (fileName.length())
  21310. {
  21311. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  21312. if (temp)
  21313. addXrefFileInfo(reply, temp);
  21314. }
  21315. if (indexName.length())
  21316. {
  21317. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  21318. if (temp)
  21319. addXrefFileInfo(reply, temp);
  21320. }
  21321. }
  21322. }
  21323. };
  21324. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21325. {
  21326. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  21327. }
  21328. //=====================================================================================================
  21329. // Keyed joins...
  21330. //
  21331. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  21332. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  21333. // 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
  21334. // the transform and returns rows that are created.
  21335. // 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)
  21336. //
  21337. //=====================================================================================================
  21338. class CJoinGroup;
  21339. interface IJoinProcessor
  21340. {
  21341. virtual void processEOG() = 0;
  21342. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  21343. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  21344. virtual bool fireException(IException *E) = 0;
  21345. virtual void processCompletedGroups() = 0;
  21346. };
  21347. //------------------------------------------------------------------------------------------------------
  21348. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  21349. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  21350. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  21351. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  21352. // per-query limits etc (Note that the pointer array block is not though).
  21353. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  21354. //
  21355. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  21356. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  21357. // initial count when created.
  21358. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  21359. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  21360. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  21361. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  21362. // remaining reference and the JoinGroup will be processed and destroyed.
  21363. //
  21364. //------------------------------------------------------------------------------------------------------
  21365. class CJoinGroup : public CInterface, implements IInterface
  21366. {
  21367. protected:
  21368. const void *left; // LHS row
  21369. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  21370. atomic_t endMarkersPending; // How many slave responses still waiting for
  21371. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  21372. unsigned lastPartNo;
  21373. unsigned pos;
  21374. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  21375. public:
  21376. #undef new
  21377. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  21378. {
  21379. return a->allocate(size, activityId);
  21380. }
  21381. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21382. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21383. #endif
  21384. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  21385. {
  21386. ReleaseRoxieRow(ptr);
  21387. }
  21388. void operator delete(void *ptr)
  21389. {
  21390. ReleaseRoxieRow(ptr);
  21391. }
  21392. public:
  21393. IMPLEMENT_IINTERFACE;
  21394. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  21395. {
  21396. #ifdef TRACE_JOINGROUPS
  21397. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  21398. #endif
  21399. candidates = 0;
  21400. lastPartNo = 0;
  21401. pos = 0;
  21402. left = _left;
  21403. groupStart = _groupStart;
  21404. if (_groupStart)
  21405. {
  21406. atomic_inc(&_groupStart->endMarkersPending);
  21407. }
  21408. atomic_set(&endMarkersPending, 1);
  21409. }
  21410. ~CJoinGroup()
  21411. {
  21412. #ifdef TRACE_JOINGROUPS
  21413. DBGLOG("Destroying joinGroup %p", this);
  21414. #endif
  21415. if (left)
  21416. {
  21417. ReleaseRoxieRow(left);
  21418. ForEachItemIn(idx, rows)
  21419. ReleaseRoxieRow(rows.item(idx));
  21420. rows.kill();
  21421. }
  21422. }
  21423. inline bool isHeadRecord() const
  21424. {
  21425. return left==NULL;
  21426. }
  21427. inline bool complete() const
  21428. {
  21429. return atomic_read(&endMarkersPending) == 0;
  21430. }
  21431. #ifdef TRACE_JOINGROUPS
  21432. inline void notePending(unsigned lineNo)
  21433. #else
  21434. inline void notePending()
  21435. #endif
  21436. {
  21437. assert(!complete());
  21438. atomic_inc(&endMarkersPending);
  21439. #ifdef TRACE_JOINGROUPS
  21440. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  21441. #endif
  21442. }
  21443. inline bool inGroup(CJoinGroup *leader) const
  21444. {
  21445. return groupStart==leader;
  21446. }
  21447. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  21448. {
  21449. // Single threaded by now
  21450. assert(complete());
  21451. return rows.item(idx);
  21452. }
  21453. #ifdef TRACE_JOINGROUPS
  21454. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  21455. #else
  21456. bool noteEndReceived(unsigned candidateCount)
  21457. #endif
  21458. {
  21459. assert(!complete());
  21460. if (candidateCount)
  21461. {
  21462. candidates += candidateCount;
  21463. }
  21464. #ifdef TRACE_JOINGROUPS
  21465. 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);
  21466. #endif
  21467. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  21468. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  21469. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  21470. CJoinGroup *localGroupStart = groupStart;
  21471. if (atomic_dec_and_test(&endMarkersPending))
  21472. {
  21473. if (localGroupStart)
  21474. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  21475. else
  21476. return true;
  21477. }
  21478. else
  21479. return false;
  21480. }
  21481. inline const void *queryLeft() const
  21482. {
  21483. return left;
  21484. }
  21485. void addRightMatch(KeyedJoinHeader *right)
  21486. {
  21487. assert(!complete());
  21488. unsigned short partNo = right->partNo;
  21489. if (partNo != lastPartNo)
  21490. {
  21491. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  21492. if (partNo > lastPartNo)
  21493. pos = rows.length();
  21494. while (pos>0)
  21495. {
  21496. if (rows.item(pos-1)->partNo <= partNo)
  21497. break;
  21498. pos--;
  21499. }
  21500. lastPartNo = partNo;
  21501. }
  21502. rows.add(right, pos);
  21503. pos++;
  21504. }
  21505. inline unsigned rowsSeen() const
  21506. {
  21507. assert(complete());
  21508. return rows.length();
  21509. }
  21510. inline unsigned candidateCount() const
  21511. {
  21512. assert(complete());
  21513. return candidates;
  21514. }
  21515. };
  21516. #ifdef TRACE_JOINGROUPS
  21517. #define notePending() notePending(__LINE__)
  21518. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  21519. #endif
  21520. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  21521. {
  21522. private:
  21523. SafeQueueOf<const void, true> ready;
  21524. public:
  21525. IHThorKeyedJoinArg &helper;
  21526. unsigned joinProcessed;
  21527. bool isFullKey;
  21528. bool eof;
  21529. bool isSimple;
  21530. bool allPulled;
  21531. ActivityTimeAccumulator totalCycles;
  21532. unsigned activityId;
  21533. RecordPullerThread &puller;
  21534. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  21535. Owned<IEngineRowAllocator> ccdRecordAllocator;
  21536. IJoinProcessor &processor;
  21537. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  21538. RecordPullerThread &_puller, IJoinProcessor &_processor)
  21539. : helper(_helper),
  21540. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  21541. isFullKey(_isFullKey),
  21542. isSimple(_isSimple),
  21543. puller(_puller),
  21544. processor(_processor),
  21545. activityId(_activity.queryId())
  21546. {
  21547. joinProcessed = 0;
  21548. allPulled = false;
  21549. eof = false;
  21550. }
  21551. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  21552. {
  21553. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  21554. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  21555. }
  21556. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21557. {
  21558. eof = false;
  21559. joinProcessed = 0;
  21560. totalCycles.totalCycles = 0;
  21561. allPulled = false;
  21562. assertex(ready.ordinality()==0);
  21563. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  21564. }
  21565. virtual void reset()
  21566. {
  21567. CRemoteResultAdaptor::reset();
  21568. while (ready.ordinality())
  21569. {
  21570. const void *goer = ready.dequeue();
  21571. if (goer)
  21572. ReleaseRoxieRow(goer);
  21573. }
  21574. while (injected.ordinality())
  21575. {
  21576. const void *goer = injected.dequeue();
  21577. if (goer)
  21578. ReleaseRoxieRow(goer);
  21579. }
  21580. }
  21581. inline void addResult(const void *row)
  21582. {
  21583. ready.enqueue(row);
  21584. }
  21585. virtual unsigned __int64 queryTotalCycles() const
  21586. {
  21587. return totalCycles.totalCycles;
  21588. }
  21589. virtual IOutputMetaData * queryOutputMeta() const
  21590. {
  21591. return owner->queryOutputMeta();
  21592. }
  21593. virtual const void *nextInGroup()
  21594. {
  21595. ActivityTimer t(totalCycles, timeActivities);
  21596. loop
  21597. {
  21598. if (eof)
  21599. return NULL;
  21600. processSlaveResults();
  21601. if (ready.ordinality())
  21602. {
  21603. const void *result = ready.dequeue();
  21604. if (result)
  21605. joinProcessed++;
  21606. return result;
  21607. }
  21608. else
  21609. eof = true;
  21610. }
  21611. }
  21612. private:
  21613. void processSlaveResults()
  21614. {
  21615. while (!ready.ordinality())
  21616. {
  21617. KeyedJoinHeader *fetchedData;
  21618. if (isSimple)
  21619. {
  21620. while (!allPulled && !injected.ordinality())
  21621. {
  21622. if (!puller.pullRecords(1))
  21623. {
  21624. puller.done();
  21625. allPulled = true;
  21626. }
  21627. }
  21628. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21629. }
  21630. else
  21631. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21632. if (fetchedData)
  21633. {
  21634. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21635. if (fetchedData->partNo == (unsigned short) -1)
  21636. {
  21637. #ifdef TRACE_JOINGROUPS
  21638. CTXLOG("Got end for group %p", thisGroup);
  21639. #endif
  21640. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21641. ReleaseRoxieRow(fetchedData);
  21642. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21643. }
  21644. else
  21645. {
  21646. #ifdef TRACE_JOINGROUPS
  21647. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21648. #endif
  21649. thisGroup->addRightMatch(fetchedData);
  21650. if (isFullKey)
  21651. {
  21652. #ifdef TRACE_JOINGROUPS
  21653. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21654. #endif
  21655. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21656. }
  21657. }
  21658. }
  21659. else
  21660. break;
  21661. }
  21662. }
  21663. };
  21664. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21665. {
  21666. IHThorKeyedJoinArg &helper;
  21667. Owned<IKeyManager> tlk;
  21668. Linked<IKeyArray> keySet;
  21669. Linked<TranslatorArray> translators;
  21670. CRemoteResultAdaptor remote;
  21671. RecordPullerThread puller;
  21672. IOutputMetaData *indexReadMeta;
  21673. IJoinProcessor *joinHandler;
  21674. bool variableIndexFileName;
  21675. bool indexReadInputRecordVariable;
  21676. bool isLocal;
  21677. Owned<IEngineRowAllocator> indexReadAllocator;
  21678. Owned<const IResolvedFile> varFileInfo;
  21679. IRoxieInput *indexReadInput;
  21680. IIndexReadActivityInfo *rootIndex;
  21681. public:
  21682. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21683. : CRoxieServerActivity(_factory, _probeManager),
  21684. helper((IHThorKeyedJoinArg &)basehelper),
  21685. tlk(createKeyManager(NULL, 0, this)),
  21686. translators(_translators),
  21687. keySet(_keySet),
  21688. remote(_remoteId, 0, helper, *this, true, true),
  21689. indexReadMeta(_indexReadMeta),
  21690. joinHandler(_joinHandler),
  21691. puller(false),
  21692. isLocal(_isLocal)
  21693. {
  21694. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  21695. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21696. indexReadInput = NULL;
  21697. rootIndex = NULL;
  21698. }
  21699. virtual const IResolvedFile *queryVarFileInfo() const
  21700. {
  21701. return varFileInfo;
  21702. }
  21703. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21704. {
  21705. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21706. remote.onCreate(this, this, _ctx, _colocalParent);
  21707. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21708. }
  21709. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21710. {
  21711. if (!idx)
  21712. puller.setInput(this, _in);
  21713. else if (idx==1)
  21714. indexReadInput = _in;
  21715. else
  21716. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21717. }
  21718. virtual void serializeExtra(MemoryBuffer &out)
  21719. {
  21720. if (helper.getJoinFlags() & JFindexfromactivity)
  21721. {
  21722. assertex(rootIndex);
  21723. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21724. indexId.serialize(out);
  21725. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21726. MemoryBuffer tmp;
  21727. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21728. if (rootIndex->queryActivity()->queryVarFileInfo())
  21729. {
  21730. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21731. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21732. }
  21733. unsigned ctxlen = tmp.length();
  21734. out.append(ctxlen).append(tmp);
  21735. }
  21736. }
  21737. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21738. {
  21739. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21740. if (indexReadInput)
  21741. {
  21742. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21743. rootIndex = indexReadInput->queryIndexReadActivity();
  21744. if (!rootIndex)
  21745. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21746. }
  21747. remote.onStart(parentExtractSize, parentExtract);
  21748. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21749. if (rootIndex)
  21750. {
  21751. varFileInfo.setown(rootIndex->getVarFileInfo());
  21752. translators.setown(rootIndex->getTranslators());
  21753. keySet.setown(rootIndex->getKeySet());
  21754. }
  21755. else if (variableIndexFileName)
  21756. {
  21757. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21758. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21759. if (varFileInfo)
  21760. {
  21761. translators.setown(new TranslatorArray);
  21762. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  21763. }
  21764. }
  21765. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  21766. }
  21767. virtual void stop(bool aborting)
  21768. {
  21769. puller.stop(aborting);
  21770. CRoxieServerActivity::stop(aborting);
  21771. }
  21772. virtual void reset()
  21773. {
  21774. CRoxieServerActivity::reset();
  21775. puller.reset();
  21776. if (varFileInfo)
  21777. {
  21778. keySet.clear();
  21779. varFileInfo.clear();
  21780. }
  21781. }
  21782. virtual IRoxieInput *queryOutput(unsigned idx)
  21783. {
  21784. if (idx==(unsigned)-1)
  21785. idx = 0;
  21786. return idx ? NULL : &remote;
  21787. }
  21788. virtual void processRow(const void *row)
  21789. {
  21790. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21791. // called from front puller thread
  21792. // buffer up an IndexRead request
  21793. if (helper.leftCanMatch(row))
  21794. {
  21795. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21796. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21797. OwnedConstRoxieRow extracted;
  21798. if (indexReadSize)
  21799. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21800. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21801. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21802. {
  21803. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21804. if (thisBase)
  21805. {
  21806. unsigned fileNo = 0;
  21807. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21808. try
  21809. {
  21810. tlk->setKey(thisKey);
  21811. tlk->setLayoutTranslator(translators->item(fileNo));
  21812. helper.createSegmentMonitors(tlk, extracted);
  21813. if (rootIndex)
  21814. rootIndex->mergeSegmentMonitors(tlk);
  21815. tlk->finishSegmentMonitors();
  21816. tlk->reset();
  21817. loop
  21818. {
  21819. typedef const void * cvp;
  21820. if (thisKey->isTopLevelKey())
  21821. {
  21822. bool locallySorted = !thisKey->isFullySorted();
  21823. while (locallySorted || tlk->lookup(false))
  21824. {
  21825. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21826. if (locallySorted || slavePart)
  21827. {
  21828. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21829. *outputBuffer++ = jg;
  21830. if (indexReadInputRecordVariable)
  21831. {
  21832. *(unsigned *) outputBuffer = indexReadSize;
  21833. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21834. }
  21835. jg->notePending();
  21836. memcpy(outputBuffer, extracted, indexReadSize);
  21837. if (locallySorted)
  21838. {
  21839. for (unsigned i = 1; i < numChannels; i++)
  21840. jg->notePending();
  21841. break;
  21842. }
  21843. }
  21844. }
  21845. }
  21846. else
  21847. {
  21848. // MORE - this code seems to be duplicated in half keyed
  21849. unsigned accepted = 0;
  21850. unsigned rejected = 0;
  21851. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21852. jg->notePending();
  21853. unsigned candidateCount = 0;
  21854. while (tlk->lookup(true))
  21855. {
  21856. candidateCount++;
  21857. atomic_inc(&indexRecordsRead);
  21858. KLBlobProviderAdapter adapter(tlk);
  21859. offset_t recptr;
  21860. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21861. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21862. {
  21863. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21864. rhs->fpos = recptr;
  21865. rhs->thisGroup = jg;
  21866. rhs->partNo = partNo;
  21867. result->append(rhs);
  21868. }
  21869. else
  21870. {
  21871. rejected++;
  21872. atomic_inc(&postFiltered);
  21873. }
  21874. }
  21875. // output an end marker for the matches to this group
  21876. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21877. endMarker->fpos = (offset_t) candidateCount;
  21878. endMarker->thisGroup = jg;
  21879. endMarker->partNo = (unsigned short) -1;
  21880. result->append(endMarker);
  21881. remote.injectResult(result.getClear());
  21882. if (accepted)
  21883. noteStatistic(StNumIndexAccepted, accepted);
  21884. if (rejected)
  21885. noteStatistic(StNumIndexRejected, rejected);
  21886. }
  21887. if (++fileNo < thisBase->numParts())
  21888. {
  21889. thisKey = thisBase->queryPart(fileNo);
  21890. tlk->setKey(thisKey);
  21891. tlk->setLayoutTranslator(translators->item(fileNo));
  21892. tlk->reset();
  21893. }
  21894. else
  21895. break;
  21896. }
  21897. tlk->releaseSegmentMonitors();
  21898. tlk->setKey(NULL);
  21899. }
  21900. catch (...)
  21901. {
  21902. tlk->releaseSegmentMonitors();
  21903. tlk->setKey(NULL);
  21904. throw;
  21905. }
  21906. }
  21907. }
  21908. joinHandler->noteEndReceived(jg, 0);
  21909. }
  21910. else
  21911. {
  21912. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21913. }
  21914. }
  21915. void processGroup(const ConstPointerArray &)
  21916. {
  21917. throwUnexpected();
  21918. }
  21919. virtual void processEOG()
  21920. {
  21921. joinHandler->processEOG();
  21922. }
  21923. virtual void processDone()
  21924. {
  21925. // called from puller thread
  21926. remote.flush();
  21927. remote.senddone();
  21928. }
  21929. virtual void onLimitExceeded(bool isKeyed)
  21930. {
  21931. if (traceLevel > 4)
  21932. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21933. if (isKeyed)
  21934. throwUnexpected();
  21935. helper.onLimitExceeded();
  21936. }
  21937. virtual const void *createLimitFailRow(bool isKeyed)
  21938. {
  21939. throwUnexpected();
  21940. }
  21941. virtual bool fireException(IException *e)
  21942. {
  21943. // called from puller thread on failure
  21944. remote.fireException(LINK(e));
  21945. return joinHandler->fireException(e);
  21946. }
  21947. virtual const void *nextInGroup()
  21948. {
  21949. throwUnexpected(); // I am nobody's input
  21950. }
  21951. };
  21952. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21953. {
  21954. protected:
  21955. IHThorKeyedJoinArg &helper;
  21956. KeyedJoinRemoteAdaptor remote;
  21957. RecordPullerThread puller;
  21958. OwnedConstRoxieRow defaultRight;
  21959. Owned<IEngineRowAllocator> defaultRightAllocator;
  21960. unsigned joinFlags;
  21961. unsigned atMost;
  21962. unsigned atmostsTriggered;
  21963. unsigned abortLimit;
  21964. unsigned keepLimit;
  21965. bool limitFail;
  21966. bool limitOnFail;
  21967. bool preserveGroups;
  21968. bool cloneLeft;
  21969. bool isSimple;
  21970. bool isLocal;
  21971. ThorActivityKind activityKind;
  21972. CJoinGroup *groupStart;
  21973. CriticalSection groupsCrit;
  21974. QueueOf<CJoinGroup, false> groups;
  21975. IRoxieInput *indexReadInput;
  21976. IIndexReadActivityInfo *rootIndex;
  21977. void createDefaultRight()
  21978. {
  21979. if (!defaultRight)
  21980. {
  21981. if (!defaultRightAllocator)
  21982. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21983. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21984. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21985. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21986. }
  21987. }
  21988. public:
  21989. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21990. , bool isFull, bool _isSimple, bool _isLocal)
  21991. : CRoxieServerActivity(_factory, _probeManager),
  21992. helper((IHThorKeyedJoinArg &)basehelper),
  21993. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21994. joinFlags(_joinFlags),
  21995. preserveGroups(meta.isGrouped()),
  21996. puller(false),
  21997. isSimple(_isSimple),
  21998. isLocal(_isLocal),
  21999. abortLimit(0),
  22000. keepLimit(0),
  22001. atMost(0),
  22002. limitFail(false),
  22003. limitOnFail(false),
  22004. cloneLeft(false)
  22005. {
  22006. groupStart = NULL;
  22007. activityKind = _factory->getKind();
  22008. indexReadInput = NULL;
  22009. rootIndex = NULL;
  22010. atmostsTriggered = 0;
  22011. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22012. }
  22013. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22014. {
  22015. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  22016. remote.onCreate(this, this, _ctx, _colocalParent);
  22017. }
  22018. virtual void setInput(unsigned idx, IRoxieInput *_in)
  22019. {
  22020. if (!idx)
  22021. puller.setInput(this, _in);
  22022. else if (idx==1)
  22023. indexReadInput = _in;
  22024. else
  22025. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22026. }
  22027. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22028. {
  22029. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22030. if (indexReadInput)
  22031. {
  22032. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22033. rootIndex = indexReadInput->queryIndexReadActivity();
  22034. if (!rootIndex)
  22035. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22036. }
  22037. remote.onStart(parentExtractSize, parentExtract);
  22038. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22039. atmostsTriggered = 0;
  22040. atMost = helper.getJoinLimit();
  22041. if (atMost == 0) atMost = (unsigned)-1;
  22042. abortLimit = helper.getMatchAbortLimit();
  22043. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22044. keepLimit = helper.getKeepLimit();
  22045. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22046. getLimitType(joinFlags, limitFail, limitOnFail);
  22047. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22048. if (joinFlags & JFleftouter)
  22049. createDefaultRight();
  22050. }
  22051. virtual void stop(bool aborting)
  22052. {
  22053. puller.stop(aborting);
  22054. if (indexReadInput)
  22055. indexReadInput->stop(aborting);
  22056. CRoxieServerActivity::stop(aborting);
  22057. }
  22058. virtual unsigned __int64 queryLocalCycles() const
  22059. {
  22060. __int64 localCycles = remote.totalCycles.totalCycles;
  22061. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22062. if (localCycles < 0)
  22063. localCycles = 0;
  22064. return localCycles;
  22065. }
  22066. virtual IRoxieInput *queryInput(unsigned idx)
  22067. {
  22068. if (idx==0)
  22069. return puller.queryInput();
  22070. else if (idx==1)
  22071. return indexReadInput;
  22072. else
  22073. return NULL;
  22074. }
  22075. virtual void reset()
  22076. {
  22077. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22078. remote.totalCycles.totalCycles = 0;
  22079. processed = remote.joinProcessed;
  22080. remote.joinProcessed = 0;
  22081. defaultRight.clear();
  22082. if (indexReadInput)
  22083. indexReadInput->reset();
  22084. if (atmostsTriggered)
  22085. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22086. CRoxieServerActivity::reset();
  22087. puller.reset();
  22088. while (groups.ordinality())
  22089. {
  22090. ::Release(groups.dequeue());
  22091. }
  22092. }
  22093. virtual IRoxieInput *queryOutput(unsigned idx)
  22094. {
  22095. if (idx==(unsigned)-1)
  22096. idx = 0;
  22097. return idx ? NULL : &remote;
  22098. }
  22099. #undef new
  22100. virtual CJoinGroup *createJoinGroup(const void *row)
  22101. {
  22102. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22103. CriticalBlock c(groupsCrit);
  22104. if (preserveGroups && !groupStart)
  22105. {
  22106. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22107. groups.enqueue(groupStart);
  22108. }
  22109. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  22110. groups.enqueue(jg);
  22111. return jg;
  22112. }
  22113. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22114. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22115. #endif
  22116. void endGroup()
  22117. {
  22118. CriticalBlock c(groupsCrit);
  22119. if (groupStart)
  22120. noteEndReceived(groupStart, 0);
  22121. groupStart = NULL;
  22122. }
  22123. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  22124. {
  22125. if (jg->noteEndReceived(candidateCount))
  22126. processCompletedGroups();
  22127. }
  22128. void processCompletedGroups()
  22129. {
  22130. CriticalBlock c(groupsCrit);
  22131. while (groups.ordinality())
  22132. {
  22133. if (!groups.head()->complete())
  22134. break;
  22135. Owned<CJoinGroup> head = groups.dequeue();
  22136. if (preserveGroups)
  22137. {
  22138. assert(head->isHeadRecord());
  22139. assert(groups.head()->inGroup(head));
  22140. unsigned joinGroupSize = 0;
  22141. while (groups.ordinality() && groups.head()->inGroup(head))
  22142. {
  22143. Owned<CJoinGroup> finger = groups.dequeue();
  22144. joinGroupSize += doJoinGroup(finger);
  22145. }
  22146. if (joinGroupSize)
  22147. remote.addResult(NULL);
  22148. }
  22149. else
  22150. doJoinGroup(head);
  22151. }
  22152. }
  22153. void failLimit(const void * left)
  22154. {
  22155. helper.onMatchAbortLimitExceeded();
  22156. CommonXmlWriter xmlwrite(0);
  22157. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  22158. {
  22159. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  22160. }
  22161. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  22162. }
  22163. virtual bool needsAllocator() const { return true; }
  22164. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  22165. {
  22166. if (cloneLeft && !except)
  22167. {
  22168. LinkRoxieRow(left);
  22169. remote.addResult((void *) left);
  22170. return 1;
  22171. }
  22172. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22173. unsigned outSize;
  22174. try
  22175. {
  22176. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  22177. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  22178. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  22179. }
  22180. catch (IException *E)
  22181. {
  22182. throw makeWrappedException(E);
  22183. }
  22184. if (outSize)
  22185. {
  22186. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  22187. remote.addResult(shrunk);
  22188. return 1;
  22189. }
  22190. else
  22191. return 0;
  22192. }
  22193. unsigned doJoinGroup(CJoinGroup *jg)
  22194. {
  22195. unsigned matched = jg->rowsSeen();
  22196. unsigned added = 0;
  22197. const void *left = jg->queryLeft();
  22198. if (jg->candidateCount() > abortLimit)
  22199. {
  22200. if (limitFail)
  22201. failLimit(left);
  22202. if (ctx->queryDebugContext())
  22203. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22204. if (limitOnFail)
  22205. {
  22206. Owned<IException> except;
  22207. try
  22208. {
  22209. failLimit(left);
  22210. }
  22211. catch(IException * e)
  22212. {
  22213. except.setown(e);
  22214. }
  22215. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  22216. }
  22217. }
  22218. else if (!matched || jg->candidateCount() > atMost)
  22219. {
  22220. if (jg->candidateCount() > atMost)
  22221. atmostsTriggered++;
  22222. switch (joinFlags & JFtypemask)
  22223. {
  22224. case JFleftouter:
  22225. case JFleftonly:
  22226. switch (activityKind)
  22227. {
  22228. case TAKkeyedjoin:
  22229. case TAKkeyeddenormalizegroup:
  22230. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  22231. break;
  22232. case TAKkeyeddenormalize:
  22233. LinkRoxieRow(left);
  22234. remote.addResult((void *) left);
  22235. added++;
  22236. break;
  22237. }
  22238. break;
  22239. }
  22240. }
  22241. else if (!(joinFlags & JFexclude))
  22242. {
  22243. unsigned idx = 0;
  22244. switch (activityKind)
  22245. {
  22246. case TAKkeyedjoin:
  22247. while (idx < matched)
  22248. {
  22249. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22250. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  22251. if (added==keepLimit)
  22252. break;
  22253. idx++;
  22254. }
  22255. break;
  22256. case TAKkeyeddenormalize:
  22257. {
  22258. OwnedConstRoxieRow newLeft;
  22259. newLeft.set(left);
  22260. unsigned rowSize = 0;
  22261. unsigned rightAdded = 0;
  22262. while (idx < matched)
  22263. {
  22264. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22265. try
  22266. {
  22267. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22268. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  22269. if (transformedSize)
  22270. {
  22271. rowSize = transformedSize;
  22272. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  22273. rightAdded++;
  22274. if (rightAdded==keepLimit)
  22275. break;
  22276. }
  22277. idx++;
  22278. }
  22279. catch (IException *E)
  22280. {
  22281. throw makeWrappedException(E);
  22282. }
  22283. }
  22284. if (rowSize)
  22285. {
  22286. remote.addResult(newLeft.getClear());
  22287. added++;
  22288. }
  22289. }
  22290. break;
  22291. case TAKkeyeddenormalizegroup:
  22292. {
  22293. ConstPointerArray extractedRows;
  22294. while (idx < matched && idx < keepLimit)
  22295. {
  22296. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22297. extractedRows.append((void *) &rhs->rhsdata);
  22298. idx++;
  22299. }
  22300. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  22301. }
  22302. break;
  22303. }
  22304. }
  22305. return added;
  22306. }
  22307. virtual void processDone()
  22308. {
  22309. // called from puller thread
  22310. remote.flush();
  22311. remote.senddone();
  22312. }
  22313. virtual void onLimitExceeded(bool isKeyed)
  22314. {
  22315. if (traceLevel > 4)
  22316. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22317. if (isKeyed)
  22318. throwUnexpected();
  22319. helper.onLimitExceeded();
  22320. }
  22321. virtual const void *createLimitFailRow(bool isKeyed)
  22322. {
  22323. throwUnexpected();
  22324. }
  22325. virtual bool fireException(IException *e)
  22326. {
  22327. // called from puller thread on failure
  22328. return remote.fireException(e);
  22329. }
  22330. virtual const void *nextInGroup()
  22331. {
  22332. throwUnexpected(); // I am nobody's input
  22333. }
  22334. };
  22335. #ifdef _MSC_VER
  22336. #pragma warning ( push )
  22337. #pragma warning ( disable: 4355 )
  22338. #endif
  22339. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22340. {
  22341. CRoxieServerFullKeyedJoinHead head;
  22342. Owned<IEngineRowAllocator> fetchInputAllocator;
  22343. Linked<IFilePartMap> map;
  22344. bool variableFetchFileName;
  22345. Owned<const IResolvedFile> varFetchFileInfo;
  22346. CachedOutputMetaData fetchInputFields;
  22347. public:
  22348. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  22349. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  22350. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  22351. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  22352. map(_map)
  22353. {
  22354. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  22355. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22356. }
  22357. virtual const IResolvedFile *queryVarFileInfo() const
  22358. {
  22359. return varFetchFileInfo;
  22360. }
  22361. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22362. {
  22363. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22364. head.onCreate(_ctx, _colocalParent);
  22365. fetchInputFields.set(helper.queryFetchInputRecordSize());
  22366. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  22367. }
  22368. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22369. {
  22370. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22371. if (variableFetchFileName)
  22372. {
  22373. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22374. OwnedRoxieString fname(helper.getFileName());
  22375. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  22376. if (varFetchFileInfo)
  22377. map.setown(varFetchFileInfo->getFileMap());
  22378. }
  22379. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  22380. }
  22381. virtual void setInput(unsigned idx, IRoxieInput *in)
  22382. {
  22383. head.setInput(idx, in);
  22384. }
  22385. virtual void processRow(const void *_rhs)
  22386. {
  22387. // called from puller thread
  22388. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  22389. CJoinGroup *jg = rhs->thisGroup;
  22390. if (rhs->partNo != (unsigned short) -1)
  22391. {
  22392. unsigned partNo = map->mapOffset(rhs->fpos);
  22393. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  22394. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  22395. if (fetchInputFields.isVariableSize())
  22396. {
  22397. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  22398. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22399. ReleaseRoxieRow(rhs);
  22400. jg->notePending();
  22401. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  22402. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  22403. }
  22404. else
  22405. {
  22406. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  22407. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22408. ReleaseRoxieRow(rhs);
  22409. jg->notePending();
  22410. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  22411. }
  22412. }
  22413. else
  22414. {
  22415. unsigned candidateCount = (unsigned) rhs->fpos;
  22416. // CTXLOG("Full keyed join - all results back from index");
  22417. ReleaseRoxieRow(rhs);
  22418. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  22419. }
  22420. }
  22421. virtual void processEOG()
  22422. {
  22423. // called from front puller thread
  22424. if (preserveGroups)
  22425. endGroup();
  22426. }
  22427. void processGroup(const ConstPointerArray &)
  22428. {
  22429. throwUnexpected();
  22430. }
  22431. };
  22432. #ifdef _MSC_VER
  22433. #pragma warning ( pop )
  22434. #endif
  22435. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22436. {
  22437. IOutputMetaData *indexReadMeta;
  22438. Owned<IEngineRowAllocator> indexReadAllocator;
  22439. Owned<IKeyManager> tlk;
  22440. bool variableIndexFileName;
  22441. bool indexReadInputRecordVariable;
  22442. Owned<const IResolvedFile> varFileInfo;
  22443. Linked<TranslatorArray> translators;
  22444. Linked<IKeyArray> keySet;
  22445. Owned<IOutputMetaData> joinPrefixedMeta;
  22446. Owned<IEngineRowAllocator> joinFieldsAllocator;
  22447. public:
  22448. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  22449. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  22450. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  22451. indexReadMeta(_indexReadMeta),
  22452. tlk(createKeyManager(NULL, 0, this)),
  22453. keySet(_keySet),
  22454. translators(_translators)
  22455. {
  22456. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22457. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22458. }
  22459. virtual void serializeExtra(MemoryBuffer &out)
  22460. {
  22461. if (helper.getJoinFlags() & JFindexfromactivity)
  22462. {
  22463. assertex(rootIndex);
  22464. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22465. indexId.serialize(out);
  22466. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22467. MemoryBuffer tmp;
  22468. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22469. if (rootIndex->queryActivity()->queryVarFileInfo())
  22470. {
  22471. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22472. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22473. }
  22474. unsigned ctxlen = tmp.length();
  22475. out.append(ctxlen).append(tmp);
  22476. }
  22477. }
  22478. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22479. {
  22480. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22481. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  22482. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  22483. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  22484. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  22485. }
  22486. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22487. {
  22488. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22489. if (rootIndex)
  22490. {
  22491. varFileInfo.setown(rootIndex->getVarFileInfo());
  22492. translators.setown(rootIndex->getTranslators());
  22493. keySet.setown(rootIndex->getKeySet());
  22494. }
  22495. else if (variableIndexFileName)
  22496. {
  22497. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22498. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22499. if (varFileInfo)
  22500. {
  22501. translators.setown(new TranslatorArray);
  22502. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  22503. }
  22504. }
  22505. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  22506. }
  22507. virtual const IResolvedFile *queryVarFileInfo() const
  22508. {
  22509. return varFileInfo;
  22510. }
  22511. virtual void reset()
  22512. {
  22513. CRoxieServerKeyedJoinBase::reset();
  22514. if (varFileInfo)
  22515. {
  22516. keySet.clear();
  22517. varFileInfo.clear();
  22518. }
  22519. }
  22520. virtual void processRow(const void *row)
  22521. {
  22522. // called from front puller thread
  22523. // buffer up an IndexRead request
  22524. if (helper.leftCanMatch(row) && keySet)
  22525. {
  22526. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  22527. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  22528. OwnedConstRoxieRow extracted;
  22529. if (indexReadRecordSize)
  22530. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  22531. CJoinGroup *jg = createJoinGroup(row);
  22532. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22533. {
  22534. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22535. if (thisBase)
  22536. {
  22537. unsigned fileNo = 0;
  22538. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22539. tlk->setKey(thisKey);
  22540. tlk->setLayoutTranslator(translators->item(fileNo));
  22541. helper.createSegmentMonitors(tlk, extracted);
  22542. if (rootIndex)
  22543. rootIndex->mergeSegmentMonitors(tlk);
  22544. tlk->finishSegmentMonitors();
  22545. try
  22546. {
  22547. tlk->reset();
  22548. loop
  22549. {
  22550. typedef const void * cvp;
  22551. if (thisKey && thisKey->isTopLevelKey())
  22552. {
  22553. bool locallySorted = (!thisKey->isFullySorted());
  22554. while (locallySorted || tlk->lookup(false))
  22555. {
  22556. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22557. if (locallySorted || slavePart)
  22558. {
  22559. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22560. *outputBuffer++ = jg;
  22561. if (indexReadInputRecordVariable)
  22562. {
  22563. *(unsigned *) outputBuffer = indexReadRecordSize;
  22564. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  22565. }
  22566. jg->notePending();
  22567. memcpy(outputBuffer, extracted, indexReadRecordSize);
  22568. if (locallySorted)
  22569. {
  22570. for (unsigned i = 1; i < numChannels; i++)
  22571. jg->notePending();
  22572. break;
  22573. }
  22574. }
  22575. }
  22576. }
  22577. else
  22578. {
  22579. unsigned accepted = 0;
  22580. unsigned rejected = 0;
  22581. Owned<CRowArrayMessageResult> result;
  22582. if (!isSimple)
  22583. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22584. // MORE - This code seems to be duplicated in keyedJoinHead
  22585. jg->notePending();
  22586. unsigned candidateCount = 0;
  22587. while (tlk->lookup(true))
  22588. {
  22589. candidateCount++;
  22590. atomic_inc(&indexRecordsRead);
  22591. KLBlobProviderAdapter adapter(tlk);
  22592. offset_t recptr;
  22593. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22594. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22595. {
  22596. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22597. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22598. accepted++;
  22599. KLBlobProviderAdapter adapter(tlk);
  22600. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22601. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22602. rec->fpos = recptr;
  22603. rec->thisGroup = jg;
  22604. rec->partNo = partNo;
  22605. if (isSimple)
  22606. remote.injected.enqueue(rec);
  22607. else
  22608. result->append(rec);
  22609. }
  22610. else
  22611. {
  22612. rejected++;
  22613. atomic_inc(&postFiltered);
  22614. }
  22615. }
  22616. // output an end marker for the matches to this group
  22617. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22618. rec->fpos = (offset_t) candidateCount;
  22619. rec->thisGroup = jg;
  22620. rec->partNo = (unsigned short) -1;
  22621. if (isSimple)
  22622. remote.injected.enqueue(rec);
  22623. else
  22624. {
  22625. result->append(rec);
  22626. remote.injectResult(result.getClear());
  22627. }
  22628. if (accepted)
  22629. noteStatistic(StNumIndexAccepted, accepted);
  22630. if (rejected)
  22631. noteStatistic(StNumIndexRejected, rejected);
  22632. }
  22633. if (++fileNo < thisBase->numParts())
  22634. {
  22635. thisKey = thisBase->queryPart(fileNo);
  22636. tlk->setKey(thisKey);
  22637. tlk->setLayoutTranslator(translators->item(fileNo));
  22638. tlk->reset();
  22639. }
  22640. else
  22641. break;
  22642. }
  22643. tlk->releaseSegmentMonitors();
  22644. tlk->setKey(NULL);
  22645. }
  22646. catch (...)
  22647. {
  22648. tlk->releaseSegmentMonitors();
  22649. tlk->setKey(NULL);
  22650. throw;
  22651. }
  22652. }
  22653. }
  22654. noteEndReceived(jg, 0);
  22655. }
  22656. else
  22657. {
  22658. noteEndReceived(createJoinGroup(row), 0);
  22659. }
  22660. }
  22661. virtual void processEOG()
  22662. {
  22663. // called from front puller thread
  22664. if (preserveGroups)
  22665. endGroup();
  22666. }
  22667. void processGroup(const ConstPointerArray &)
  22668. {
  22669. throwUnexpected();
  22670. }
  22671. };
  22672. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22673. {
  22674. Owned<const IResolvedFile> indexfile;
  22675. Owned<const IResolvedFile> datafile;
  22676. Owned<IKeyArray> keySet;
  22677. Owned<TranslatorArray> translatorArray;
  22678. Owned<IDefRecordMeta> activityMeta;
  22679. RemoteActivityId headId;
  22680. RemoteActivityId tailId;
  22681. IOutputMetaData *indexReadMeta;
  22682. Owned<IFilePartMap> map;
  22683. Owned<IFileIOArray> files;
  22684. unsigned joinFlags;
  22685. bool isHalfKeyed;
  22686. bool isLocal;
  22687. bool enableFieldTranslation;
  22688. bool variableFetchFileName;
  22689. bool variableIndexFileName;
  22690. bool isSimple;
  22691. public:
  22692. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22693. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22694. {
  22695. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22696. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22697. isSimple = isLocal;
  22698. rtlDataAttr indexLayoutMeta;
  22699. size32_t indexLayoutSize;
  22700. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22701. assertex(indexLayoutSize== 0);
  22702. MemoryBuffer m;
  22703. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22704. activityMeta.setown(deserializeRecordMeta(m, true));
  22705. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  22706. translatorArray.setown(new TranslatorArray);
  22707. joinFlags = helper->getJoinFlags();
  22708. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22709. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22710. if (!variableIndexFileName)
  22711. {
  22712. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22713. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22714. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22715. if (indexfile)
  22716. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22717. }
  22718. if (keySet && keySet->length()==1 && !isSimple)
  22719. {
  22720. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22721. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  22722. isSimple = true;
  22723. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22724. }
  22725. if (!simpleLocalKeyedJoins)
  22726. isSimple = false;
  22727. isHalfKeyed = !helper->diskAccessRequired();
  22728. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22729. if (!isHalfKeyed && !variableFetchFileName)
  22730. {
  22731. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22732. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  22733. if (datafile)
  22734. {
  22735. if (isLocal)
  22736. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22737. else
  22738. map.setown(datafile->getFileMap());
  22739. }
  22740. }
  22741. }
  22742. virtual bool getEnableFieldTranslation() const
  22743. {
  22744. return enableFieldTranslation;
  22745. }
  22746. virtual IDefRecordMeta *queryActivityMeta() const
  22747. {
  22748. return activityMeta;
  22749. }
  22750. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22751. {
  22752. if (isHalfKeyed)
  22753. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22754. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22755. else
  22756. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22757. headId, keySet, translatorArray, indexReadMeta,
  22758. tailId, map, joinFlags, isLocal);
  22759. }
  22760. virtual const StatisticsMapping &queryStatsMapping() const
  22761. {
  22762. return keyedJoinStatistics;
  22763. }
  22764. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22765. {
  22766. if (datafile)
  22767. addXrefFileInfo(reply, datafile);
  22768. if (indexfile)
  22769. addXrefFileInfo(reply, indexfile);
  22770. }
  22771. };
  22772. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22773. {
  22774. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22775. }
  22776. //=================================================================================
  22777. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22778. {
  22779. protected:
  22780. Owned<ISoapCallHelper> soaphelper;
  22781. IHThorSoapActionArg & helper;
  22782. StringBuffer authToken;
  22783. bool eof;
  22784. CriticalSection crit;
  22785. ClientCertificate *pClientCert;
  22786. public:
  22787. IMPLEMENT_IINTERFACE;
  22788. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22789. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22790. {
  22791. eof = false;
  22792. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22793. pClientCert = &clientCert;
  22794. else
  22795. pClientCert = NULL;
  22796. }
  22797. // ISoapCallRowProvider
  22798. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22799. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22800. virtual const void * getNextRow() { return NULL; };
  22801. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22802. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22803. {
  22804. eof = false;
  22805. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22806. authToken.append(ctx->queryAuthToken());
  22807. }
  22808. virtual void reset()
  22809. {
  22810. // MORE - Shouldn't we make sure thread is stopped etc???
  22811. soaphelper.clear();
  22812. CRoxieServerActivity::reset();
  22813. }
  22814. // IRoxieAbortMonitor
  22815. virtual void checkForAbort() { checkAbort(); }
  22816. };
  22817. //---------------------------------------------------------------------------
  22818. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22819. {
  22820. IHThorSoapCallArg & callHelper;
  22821. public:
  22822. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22823. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22824. {
  22825. }
  22826. virtual IHThorSoapCallArg * queryCallHelper()
  22827. {
  22828. return &callHelper;
  22829. }
  22830. virtual bool needsAllocator() const { return true; }
  22831. virtual const void *nextInGroup()
  22832. {
  22833. ActivityTimer t(totalCycles, timeActivities);
  22834. if(eof) return NULL;
  22835. if (soaphelper == NULL)
  22836. {
  22837. if (factory->getKind()==TAKhttp_rowdataset)
  22838. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22839. else
  22840. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22841. soaphelper->start();
  22842. }
  22843. OwnedConstRoxieRow ret = soaphelper->getRow();
  22844. if (!ret)
  22845. {
  22846. eof = true;
  22847. return NULL;
  22848. }
  22849. ++processed;
  22850. return ret.getClear();
  22851. }
  22852. };
  22853. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22854. {
  22855. public:
  22856. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22857. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22858. {
  22859. }
  22860. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22861. {
  22862. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22863. }
  22864. virtual const StatisticsMapping &queryStatsMapping() const
  22865. {
  22866. return soapStatistics;
  22867. }
  22868. };
  22869. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22870. {
  22871. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22872. }
  22873. //---------------------------------------------------------------------------
  22874. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22875. {
  22876. public:
  22877. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22878. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22879. {}
  22880. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22881. {
  22882. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22883. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  22884. soaphelper->start();
  22885. soaphelper->waitUntilDone();
  22886. IException *e = soaphelper->getError();
  22887. soaphelper.clear();
  22888. if (e)
  22889. throw e;
  22890. }
  22891. virtual IRoxieInput *queryOutput(unsigned idx)
  22892. {
  22893. return NULL;
  22894. }
  22895. virtual const void *nextInGroup()
  22896. {
  22897. throwUnexpected(); // I am nobody's input
  22898. }
  22899. };
  22900. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22901. {
  22902. bool isRoot;
  22903. public:
  22904. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22905. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22906. {
  22907. }
  22908. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22909. {
  22910. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22911. }
  22912. virtual bool isSink() const
  22913. {
  22914. return isRoot;
  22915. }
  22916. virtual const StatisticsMapping &queryStatsMapping() const
  22917. {
  22918. return soapStatistics;
  22919. }
  22920. };
  22921. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22922. {
  22923. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22924. }
  22925. //---------------------------------------------------------------------------
  22926. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22927. {
  22928. IHThorSoapCallArg & callHelper;
  22929. public:
  22930. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22931. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22932. {
  22933. }
  22934. virtual IHThorSoapCallArg * queryCallHelper()
  22935. {
  22936. return &callHelper;
  22937. }
  22938. virtual const void *getNextRow()
  22939. {
  22940. CriticalBlock b(crit);
  22941. const void *nextrec = input->nextInGroup();
  22942. if (!nextrec)
  22943. {
  22944. nextrec = input->nextInGroup();
  22945. }
  22946. return nextrec;
  22947. }
  22948. virtual bool needsAllocator() const { return true; }
  22949. virtual const void *nextInGroup()
  22950. {
  22951. ActivityTimer t(totalCycles, timeActivities);
  22952. if(eof) return NULL;
  22953. if (soaphelper == NULL)
  22954. {
  22955. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  22956. soaphelper->start();
  22957. }
  22958. OwnedConstRoxieRow ret = soaphelper->getRow();
  22959. if (!ret)
  22960. {
  22961. eof = true;
  22962. return NULL;
  22963. }
  22964. ++processed;
  22965. return ret.getClear();
  22966. }
  22967. };
  22968. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22969. {
  22970. public:
  22971. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22972. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22973. {
  22974. }
  22975. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22976. {
  22977. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22978. }
  22979. virtual const StatisticsMapping &queryStatsMapping() const
  22980. {
  22981. return soapStatistics;
  22982. }
  22983. };
  22984. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22985. {
  22986. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22987. }
  22988. //---------------------------------------------------------------------------
  22989. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22990. {
  22991. public:
  22992. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22993. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22994. {}
  22995. virtual const void *getNextRow()
  22996. {
  22997. CriticalBlock b(crit);
  22998. const void *nextrec = input->nextInGroup();
  22999. if (!nextrec)
  23000. {
  23001. nextrec = input->nextInGroup();
  23002. }
  23003. if (nextrec)
  23004. processed++;
  23005. return nextrec;
  23006. }
  23007. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23008. {
  23009. try
  23010. {
  23011. start(parentExtractSize, parentExtract, false);
  23012. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  23013. soaphelper->start();
  23014. soaphelper->waitUntilDone();
  23015. IException *e = soaphelper->getError();
  23016. soaphelper.clear();
  23017. if (e)
  23018. throw e;
  23019. stop(false);
  23020. }
  23021. catch (IException *E)
  23022. {
  23023. ctx->notifyAbort(E);
  23024. stop(true);
  23025. throw;
  23026. }
  23027. catch(...)
  23028. {
  23029. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  23030. ctx->notifyAbort(E);
  23031. stop(true);
  23032. throw;
  23033. }
  23034. }
  23035. virtual IRoxieInput *queryOutput(unsigned idx)
  23036. {
  23037. return NULL;
  23038. }
  23039. virtual const void *nextInGroup()
  23040. {
  23041. throwUnexpected(); // I am nobody's input
  23042. }
  23043. };
  23044. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23045. {
  23046. bool isRoot;
  23047. public:
  23048. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23049. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  23050. {
  23051. }
  23052. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  23053. {
  23054. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  23055. }
  23056. virtual bool isSink() const
  23057. {
  23058. return isRoot;
  23059. }
  23060. virtual const StatisticsMapping &queryStatsMapping() const
  23061. {
  23062. return soapStatistics;
  23063. }
  23064. };
  23065. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23066. {
  23067. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  23068. }
  23069. //=====================================================================================================
  23070. class CGraphResults : public CInterface, implements IRoxieGraphResults
  23071. {
  23072. IArrayOf<IGraphResult> results;
  23073. CriticalSection cs;
  23074. IGraphResult & select(unsigned idx)
  23075. {
  23076. CriticalBlock procedure(cs);
  23077. if (idx >= results.ordinality())
  23078. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23079. return results.item(idx);
  23080. }
  23081. public:
  23082. IMPLEMENT_IINTERFACE
  23083. void clear()
  23084. {
  23085. CriticalBlock procedure(cs);
  23086. results.kill();
  23087. }
  23088. IRoxieInput * createIterator(unsigned id)
  23089. {
  23090. return select(id).createIterator();
  23091. }
  23092. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23093. {
  23094. select(id).getLinkedResult(count, ret);
  23095. }
  23096. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23097. {
  23098. select(id).getLinkedResult(count, ret);
  23099. }
  23100. virtual const void * getLinkedRowResult(unsigned id)
  23101. {
  23102. return select(id).getLinkedRowResult();
  23103. }
  23104. void setResult(unsigned id, IGraphResult * result)
  23105. {
  23106. CriticalBlock procedure(cs);
  23107. if (results.ordinality() <= id)
  23108. {
  23109. while (results.ordinality() < id)
  23110. results.append(*new CGraphResult);
  23111. results.append(*LINK(result));
  23112. }
  23113. else
  23114. results.replace(*LINK(result), id);
  23115. }
  23116. void appendResult(IGraphResult * result)
  23117. {
  23118. CriticalBlock procedure(cs);
  23119. results.append(*LINK(result));
  23120. }
  23121. };
  23122. //===================================================================================================================
  23123. class CPseudoArg : public CInterface, implements IHThorArg
  23124. {
  23125. public:
  23126. IMPLEMENT_IINTERFACE
  23127. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  23128. };
  23129. class CPseudoActivity : public CRoxieServerActivity
  23130. {
  23131. public:
  23132. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  23133. virtual const void *nextInGroup()
  23134. {
  23135. throwUnexpected(); // I am nobody's input
  23136. }
  23137. };
  23138. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  23139. {
  23140. protected:
  23141. class ActivityGraphSlaveContext : public IndirectSlaveContext
  23142. {
  23143. SpinLock abortLock;
  23144. bool aborted;
  23145. Owned<IException> exception;
  23146. public:
  23147. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  23148. {
  23149. aborted = false;
  23150. }
  23151. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  23152. virtual void notifyAbort(IException *E)
  23153. {
  23154. SpinBlock b(abortLock);
  23155. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  23156. {
  23157. aborted = true;
  23158. exception.set(E);
  23159. }
  23160. }
  23161. virtual void checkAbort()
  23162. {
  23163. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  23164. {
  23165. SpinBlock b(abortLock);
  23166. if (!exception)
  23167. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  23168. throw exception.getLink();
  23169. }
  23170. IndirectSlaveContext::checkAbort();
  23171. }
  23172. virtual ICodeContext *queryCodeContext()
  23173. {
  23174. return codeContext;
  23175. }
  23176. void setCodeContext(ICodeContext * _codeContext)
  23177. {
  23178. codeContext = _codeContext;
  23179. }
  23180. void setLoopCounter(unsigned _loopCounter)
  23181. {
  23182. loopCounter = _loopCounter;
  23183. }
  23184. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  23185. {
  23186. childGraphs.setValue(id, childGraph);
  23187. }
  23188. virtual IActivityGraph * queryChildGraph(unsigned id)
  23189. {
  23190. if (queryTraceLevel() > 10)
  23191. CTXLOG("resolveChildGraph %d", id);
  23192. IActivityGraph *childGraph = childGraphs.getValue(id);
  23193. assertex(childGraph);
  23194. return childGraph;
  23195. }
  23196. // 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
  23197. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  23198. {
  23199. logctx.getLogPrefix(ret);
  23200. if (loopCounter)
  23201. ret.appendf("{%u}", loopCounter);
  23202. return ret;
  23203. }
  23204. protected:
  23205. const IRoxieContextLogger &logctx;
  23206. unsigned loopCounter;
  23207. ICodeContext * codeContext;
  23208. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  23209. } graphSlaveContext;
  23210. class ActivityGraphCodeContext : public IndirectCodeContext
  23211. {
  23212. public:
  23213. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  23214. {
  23215. if ((unsigned) activityId == container->queryId())
  23216. return container;
  23217. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23218. if (match)
  23219. return match->queryLocalGraph();
  23220. return IndirectCodeContext::resolveLocalQuery(activityId);
  23221. }
  23222. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  23223. {
  23224. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23225. return LINK(match->queryChildGraph());
  23226. }
  23227. virtual unsigned getGraphLoopCounter() const
  23228. {
  23229. return container->queryLoopCounter(); // only called if value is valid
  23230. }
  23231. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  23232. {
  23233. slaveContext = _slaveContext;
  23234. container = _container;
  23235. }
  23236. protected:
  23237. IRoxieSlaveContext * slaveContext;
  23238. CActivityGraph * container;
  23239. } graphCodeContext;
  23240. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  23241. IArrayOf<IRoxieServerActivity> activities;
  23242. IArrayOf<IRoxieInput> probes;
  23243. IRoxieServerActivityCopyArray sinks;
  23244. StringAttr graphName;
  23245. Owned<CGraphResults> results;
  23246. CGraphResults graphLoopResults;
  23247. ActivityArray & graphDefinition;
  23248. CriticalSection evaluateCrit;
  23249. IProbeManager *probeManager;
  23250. unsigned id;
  23251. unsigned loopCounter;
  23252. public:
  23253. IMPLEMENT_IINTERFACE;
  23254. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23255. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  23256. {
  23257. id = x.getLibraryGraphId();
  23258. if (!id)
  23259. id = _id;
  23260. loopCounter = 0;
  23261. graphSlaveContext.setCodeContext(&graphCodeContext);
  23262. graphCodeContext.setContainer(&graphSlaveContext, this);
  23263. }
  23264. ~CActivityGraph()
  23265. {
  23266. if (probeManager)
  23267. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  23268. }
  23269. virtual const char *queryName() const
  23270. {
  23271. return graphName.get();
  23272. }
  23273. void createGraph()
  23274. {
  23275. ForEachItemIn(idx, graphDefinition)
  23276. {
  23277. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  23278. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  23279. activities.append(activity);
  23280. if (donor.isSink())
  23281. {
  23282. sinks.append(activity);
  23283. if (probeManager)
  23284. probeManager->noteSink(&activity);
  23285. }
  23286. }
  23287. ForEachItemIn(idx1, graphDefinition)
  23288. {
  23289. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  23290. IRoxieServerActivity &activity = activities.item(idx1);
  23291. unsigned inputidx = 0;
  23292. loop
  23293. {
  23294. unsigned outputidx;
  23295. unsigned source = donor.getInput(inputidx, outputidx);
  23296. if (source==(unsigned) -1)
  23297. break;
  23298. connectInput(idx1, inputidx, source, outputidx, 0);
  23299. inputidx++;
  23300. }
  23301. IntArray &dependencies = donor.queryDependencies();
  23302. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23303. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23304. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  23305. ForEachItemIn(idx2, dependencies)
  23306. {
  23307. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  23308. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  23309. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  23310. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  23311. if (probeManager)
  23312. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  23313. }
  23314. }
  23315. }
  23316. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  23317. {
  23318. IRoxieServerActivity &targetActivity = activities.item(target);
  23319. IRoxieServerActivity &sourceActivity = activities.item(source);
  23320. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  23321. if (probeManager)
  23322. {
  23323. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  23324. output = static_cast<IRoxieInput*>(inputBase);
  23325. probes.append(*LINK(output));
  23326. }
  23327. targetActivity.setInput(targetIdx, output);
  23328. }
  23329. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  23330. {
  23331. graphSlaveContext.set(ctx);
  23332. if (graphDefinition.isMultiInstance())
  23333. {
  23334. graphCodeContext.set(ctx->queryCodeContext());
  23335. ctx = &graphSlaveContext;
  23336. }
  23337. ForEachItemIn(idx, activities)
  23338. {
  23339. IRoxieServerActivity *activity = &activities.item(idx);
  23340. if (activity)
  23341. activity->onCreate(ctx, _colocalParent);
  23342. }
  23343. }
  23344. virtual void abort()
  23345. {
  23346. ForEachItemIn(idx, sinks)
  23347. {
  23348. IRoxieServerActivity &sink = sinks.item(idx);
  23349. sink.stop(true);
  23350. }
  23351. }
  23352. virtual void reset()
  23353. {
  23354. ForEachItemIn(idx, sinks)
  23355. {
  23356. IRoxieServerActivity &sink = sinks.item(idx);
  23357. sink.reset();
  23358. }
  23359. }
  23360. Linked<IException> exception;
  23361. CriticalSection eCrit;
  23362. virtual void noteException(IException *E)
  23363. {
  23364. CriticalBlock b(eCrit);
  23365. if (!exception)
  23366. {
  23367. if (graphSlaveContext.queryDebugContext())
  23368. {
  23369. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  23370. }
  23371. exception.set(E);
  23372. }
  23373. }
  23374. virtual void checkAbort()
  23375. {
  23376. CriticalBlock b(eCrit);
  23377. if (exception)
  23378. throw exception.getLink();
  23379. }
  23380. virtual void execute()
  23381. {
  23382. results.setown(new CGraphResults);
  23383. doExecute(0, NULL);
  23384. }
  23385. //New child query code...
  23386. virtual IThorChildGraph * queryChildGraph()
  23387. {
  23388. return this;
  23389. }
  23390. virtual IEclGraphResults * queryLocalGraph()
  23391. {
  23392. return this;
  23393. }
  23394. virtual IRoxieServerChildGraph * queryLoopGraph()
  23395. {
  23396. return this;
  23397. }
  23398. inline unsigned queryId() const
  23399. {
  23400. return id;
  23401. }
  23402. inline unsigned queryLoopCounter() const
  23403. {
  23404. return loopCounter;
  23405. }
  23406. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  23407. {
  23408. if (sinks.ordinality()==1)
  23409. sinks.item(0).execute(parentExtractSize, parentExtract);
  23410. #ifdef PARALLEL_EXECUTE
  23411. else if (!probeManager && !graphDefinition.isSequential())
  23412. {
  23413. class casyncfor: public CAsyncFor
  23414. {
  23415. public:
  23416. IActivityGraph &parent;
  23417. unsigned parentExtractSize;
  23418. const byte * parentExtract;
  23419. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  23420. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  23421. void Do(unsigned i)
  23422. {
  23423. try
  23424. {
  23425. sinks.item(i).execute(parentExtractSize, parentExtract);
  23426. }
  23427. catch (IException *E)
  23428. {
  23429. parent.noteException(E);
  23430. throw;
  23431. }
  23432. }
  23433. private:
  23434. IRoxieServerActivityCopyArray &sinks;
  23435. } afor(sinks, *this, parentExtractSize, parentExtract);
  23436. afor.For(sinks.ordinality(), sinks.ordinality());
  23437. }
  23438. #endif
  23439. else
  23440. {
  23441. ForEachItemIn(idx, sinks)
  23442. {
  23443. IRoxieServerActivity &sink = sinks.item(idx);
  23444. sink.execute(parentExtractSize, parentExtract);
  23445. }
  23446. }
  23447. }
  23448. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  23449. {
  23450. CriticalBlock block(evaluateCrit);
  23451. results.setown(new CGraphResults);
  23452. try
  23453. {
  23454. doExecute(parentExtractSize, parentExtract);
  23455. }
  23456. catch (...)
  23457. {
  23458. DBGLOG("Exception thrown in child query - cleaning up");
  23459. reset();
  23460. throw;
  23461. }
  23462. reset();
  23463. return results.getClear();
  23464. }
  23465. //interface IRoxieServerChildGraph
  23466. virtual void beforeExecute()
  23467. {
  23468. results.setown(new CGraphResults);
  23469. }
  23470. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23471. {
  23472. IRoxieInput * ret = selectOutput(id);
  23473. ret->start(parentExtractSize, parentExtract, paused);
  23474. return ret;
  23475. }
  23476. virtual IRoxieInput * selectOutput(unsigned id)
  23477. {
  23478. ForEachItemIn(i, sinks)
  23479. {
  23480. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  23481. if (ret)
  23482. return ret;
  23483. }
  23484. throwUnexpected();
  23485. return NULL;
  23486. }
  23487. virtual void setInputResult(unsigned id, IGraphResult * result)
  23488. {
  23489. results->setResult(id, result);
  23490. }
  23491. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  23492. {
  23493. ForEachItemIn(i, activities)
  23494. {
  23495. if (activities.item(i).querySetStreamInput(id, input))
  23496. return true;
  23497. }
  23498. return false;
  23499. }
  23500. virtual void stopUnusedOutputs()
  23501. {
  23502. //Hmm not sure how to do this...
  23503. }
  23504. virtual void afterExecute()
  23505. {
  23506. ForEachItemIn(i, sinks)
  23507. {
  23508. sinks.item(i).stop(false);
  23509. }
  23510. if (graphSlaveContext.queryDebugContext())
  23511. {
  23512. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  23513. }
  23514. reset();
  23515. }
  23516. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  23517. {
  23518. doExecute(parentExtractSize, parentExtract);
  23519. return LINK(results);
  23520. }
  23521. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23522. {
  23523. results->getLinkedResult(count, ret, id);
  23524. }
  23525. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23526. {
  23527. results->getLinkedResult(count, ret, id);
  23528. }
  23529. virtual const void * getLinkedRowResult(unsigned id)
  23530. {
  23531. return results->getLinkedRowResult(id);
  23532. }
  23533. virtual void setResult(unsigned id, IGraphResult * result)
  23534. {
  23535. results->setResult(id, result);
  23536. }
  23537. virtual IRoxieInput * createResultIterator(unsigned id)
  23538. {
  23539. return results->createIterator(id);
  23540. }
  23541. virtual void setGraphLoopResult(IGraphResult * result)
  23542. {
  23543. graphLoopResults.appendResult(result);
  23544. }
  23545. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  23546. {
  23547. try
  23548. {
  23549. return graphLoopResults.createIterator(id);
  23550. }
  23551. catch (IException * e)
  23552. {
  23553. e->Release();
  23554. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  23555. }
  23556. }
  23557. virtual void clearGraphLoopResults()
  23558. {
  23559. graphLoopResults.clear();
  23560. }
  23561. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  23562. {
  23563. doExecute(parentExtractSize, parentExtract);
  23564. }
  23565. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  23566. {
  23567. graphLoopResults.setResult(id, result);
  23568. }
  23569. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  23570. {
  23571. return graphLoopResults.createIterator(id);
  23572. }
  23573. virtual void getProbeResponse(IPropertyTree *query)
  23574. {
  23575. if (probeManager)
  23576. probeManager->getProbeResponse(query);
  23577. }
  23578. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23579. {
  23580. throwUnexpected();
  23581. }
  23582. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23583. {
  23584. return NULL;
  23585. }
  23586. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23587. {
  23588. throwUnexpected();
  23589. }
  23590. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23591. {
  23592. throwUnexpected();
  23593. }
  23594. };
  23595. class CIterationActivityGraph : public CActivityGraph
  23596. {
  23597. IHThorArg * colocalParent;
  23598. unsigned fixedParentExtractSize;
  23599. const byte * fixedParentExtract;
  23600. unsigned graphOutputActivityIndex;
  23601. public:
  23602. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  23603. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  23604. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  23605. {
  23606. graphOutputActivityIndex = 0;
  23607. loopCounter = _loopCounter;
  23608. colocalParent = _colocalParent;
  23609. graphSlaveContext.set(ctx);
  23610. graphSlaveContext.setLoopCounter(loopCounter);
  23611. graphCodeContext.set(ctx->queryCodeContext());
  23612. fixedParentExtractSize = parentExtractSize;
  23613. fixedParentExtract = parentExtract;
  23614. }
  23615. void createIterationGraph()
  23616. {
  23617. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23618. ForEachItemIn(idx1, graphDefinition)
  23619. activities.append(*LINK(pseudoActivity));
  23620. graphOutputActivityIndex = queryGraphOutputIndex();
  23621. recursiveCreateGraph(graphOutputActivityIndex);
  23622. }
  23623. unsigned queryGraphOutputIndex() const
  23624. {
  23625. ForEachItemIn(i, graphDefinition)
  23626. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23627. return i;
  23628. throwUnexpected();
  23629. }
  23630. void recursiveCreateGraph(unsigned whichActivity)
  23631. {
  23632. //Check to see if already created
  23633. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23634. if (prevActivity.queryId() != 0)
  23635. {
  23636. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23637. return;
  23638. }
  23639. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23640. IRoxieServerActivity * activity = NULL;
  23641. if (donor.isGraphInvariant())
  23642. {
  23643. ThorActivityKind kind = donor.getKind();
  23644. switch (kind)
  23645. {
  23646. case TAKif:
  23647. case TAKchildif:
  23648. case TAKcase:
  23649. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23650. {
  23651. Owned<IHThorArg> helper = &donor.getHelper();
  23652. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23653. helper->onStart(fixedParentExtract, NULL);
  23654. unsigned branch;
  23655. switch (kind)
  23656. {
  23657. case TAKif: case TAKchildif:
  23658. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23659. break;
  23660. case TAKcase: case TAKchildcase:
  23661. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23662. if (branch >= donor.numInputs())
  23663. branch = donor.numInputs() - 1;
  23664. break;
  23665. default:
  23666. throwUnexpected();
  23667. }
  23668. helper.clear();
  23669. unsigned outputidx;
  23670. unsigned source = donor.getInput(branch, outputidx);
  23671. if (source ==(unsigned) -1)
  23672. activity = createRoxieServerNullActivity(&donor, probeManager);
  23673. else
  23674. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23675. activities.replace(*activity, whichActivity);
  23676. activity->onCreate(&graphSlaveContext, colocalParent);
  23677. if (source ==(unsigned) -1)
  23678. return;
  23679. recursiveCreateGraph(source);
  23680. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23681. break;
  23682. }
  23683. }
  23684. }
  23685. if (!activity)
  23686. {
  23687. activity = donor.createActivity(probeManager);
  23688. activities.replace(*activity, whichActivity);
  23689. activity->onCreate(&graphSlaveContext, colocalParent);
  23690. activity->resetOutputsUsed();
  23691. unsigned inputidx = 0;
  23692. loop
  23693. {
  23694. unsigned outputidx;
  23695. unsigned source = donor.getInput(inputidx, outputidx);
  23696. if (source==(unsigned) -1)
  23697. break;
  23698. recursiveCreateGraph(source);
  23699. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23700. inputidx++;
  23701. }
  23702. }
  23703. IntArray &dependencies = donor.queryDependencies();
  23704. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23705. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23706. ForEachItemIn(idx2, dependencies)
  23707. {
  23708. unsigned input = dependencies.item(idx2);
  23709. recursiveCreateGraph(input);
  23710. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23711. }
  23712. }
  23713. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23714. {
  23715. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23716. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23717. }
  23718. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23719. {
  23720. ForEachItemIn(i, activities)
  23721. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23722. }
  23723. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23724. {
  23725. ForEachItemIn(i, activities)
  23726. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23727. }
  23728. };
  23729. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23730. {
  23731. StringAttr graphName;
  23732. ActivityArray & graphDefinition;
  23733. IProbeManager *probeManager;
  23734. unsigned id;
  23735. IRoxieSlaveContext * ctx;
  23736. IHThorArg * colocalParent;
  23737. public:
  23738. IMPLEMENT_IINTERFACE;
  23739. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23740. : probeManager(_probeManager), graphDefinition(x)
  23741. {
  23742. graphName.set(_graphName);
  23743. id = _id;
  23744. ctx = NULL;
  23745. colocalParent = NULL;
  23746. }
  23747. virtual const char *queryName() const { return graphName.get(); }
  23748. virtual void abort() { throwUnexpected(); }
  23749. virtual void reset() { }
  23750. virtual void execute() { throwUnexpected(); }
  23751. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23752. virtual void noteException(IException *E) { throwUnexpected(); }
  23753. virtual void checkAbort() { throwUnexpected(); }
  23754. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23755. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23756. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23757. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23758. {
  23759. ctx = _ctx;
  23760. colocalParent = _colocalParent;
  23761. }
  23762. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23763. {
  23764. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23765. ret->createIterationGraph();
  23766. return ret.getClear();
  23767. }
  23768. };
  23769. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23770. {
  23771. if (childFactories.isDelayed())
  23772. {
  23773. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23774. }
  23775. else
  23776. {
  23777. Owned<IProbeManager> childProbe;
  23778. if (_probeManager)
  23779. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23780. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23781. ret->createGraph();
  23782. if (_probeManager)
  23783. _probeManager->endChildGraph(childProbe, parentActivity);
  23784. return ret.getClear();
  23785. }
  23786. }
  23787. //================================================================================================================
  23788. #ifdef _USE_CPPUNIT
  23789. #include "unittests.hpp"
  23790. // 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...
  23791. #if _MSC_VER==1200
  23792. #undef protected
  23793. #endif
  23794. static const char *sortAlgorithm;
  23795. class TestMetaData : public CInterface, implements IOutputMetaData
  23796. {
  23797. public:
  23798. IMPLEMENT_IINTERFACE;
  23799. virtual size32_t getRecordSize(const void *) { return 10; }
  23800. virtual size32_t getMinRecordSize() const { return 10; }
  23801. virtual size32_t getFixedSize() const { return 10; }
  23802. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23803. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23804. virtual unsigned getMetaFlags() { return 0; }
  23805. virtual void destruct(byte * self) {}
  23806. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23807. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23808. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23809. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23810. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23811. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23812. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23813. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  23814. } testMeta;
  23815. class TestInput : public CInterface, implements IRoxieInput
  23816. {
  23817. char const * const *input;
  23818. IRoxieSlaveContext *ctx;
  23819. unsigned endSeen;
  23820. bool eof;
  23821. unsigned count;
  23822. ActivityTimeAccumulator totalCycles;
  23823. size32_t recordSize;
  23824. unsigned activityId;
  23825. public:
  23826. enum { STATEreset, STATEstarted, STATEstopped } state;
  23827. bool allRead;
  23828. unsigned repeat;
  23829. IMPLEMENT_IINTERFACE;
  23830. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23831. {
  23832. ctx = _ctx;
  23833. input = _input;
  23834. count = 0;
  23835. eof = false;
  23836. allRead = false;
  23837. endSeen = 0;
  23838. recordSize = testMeta.getFixedSize();
  23839. state = STATEreset;
  23840. activityId = 1;
  23841. repeat = 0;
  23842. }
  23843. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23844. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23845. {
  23846. ASSERT(state == STATEreset);
  23847. }
  23848. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23849. {
  23850. ASSERT(state == STATEreset);
  23851. state = STATEstarted;
  23852. }
  23853. virtual IRoxieServerActivity *queryActivity()
  23854. {
  23855. throwUnexpected();
  23856. }
  23857. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23858. {
  23859. throwUnexpected();
  23860. }
  23861. virtual void stop(bool aborting)
  23862. {
  23863. state = STATEstopped;
  23864. }
  23865. virtual void reset()
  23866. {
  23867. ASSERT(state == STATEstopped);
  23868. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  23869. }
  23870. virtual void resetEOF()
  23871. {
  23872. throwUnexpected();
  23873. }
  23874. virtual void checkAbort() {}
  23875. virtual unsigned queryId() const { return activityId; };
  23876. virtual const void *nextInGroup()
  23877. {
  23878. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  23879. ASSERT(state == STATEstarted);
  23880. ASSERT(allRead || !eof);
  23881. if (eof)
  23882. return NULL;
  23883. again:
  23884. const char *nextSource = input[count++];
  23885. if (nextSource)
  23886. {
  23887. endSeen = 0;
  23888. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23889. memset(ret, 0, recordSize);
  23890. strncpy((char *) ret, nextSource, recordSize);
  23891. return ret;
  23892. }
  23893. else if (repeat)
  23894. {
  23895. repeat--;
  23896. count = 0;
  23897. goto again;
  23898. }
  23899. else
  23900. {
  23901. endSeen++;
  23902. if (endSeen==2)
  23903. eof = true;
  23904. return NULL;
  23905. }
  23906. }
  23907. virtual bool nextGroup(ConstPointerArray & group)
  23908. {
  23909. const void * next;
  23910. while ((next = nextInGroup()) != NULL)
  23911. group.append(next);
  23912. if (group.ordinality())
  23913. return true;
  23914. return false;
  23915. }
  23916. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  23917. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  23918. virtual IRoxieInput *queryInput(unsigned idx) const
  23919. {
  23920. return NULL;
  23921. }
  23922. };
  23923. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23924. public:
  23925. struct CompareClass : public ICompare {
  23926. virtual int docompare(const void * _left, const void * _right) const {
  23927. return memcmp(_left, _right, 5);
  23928. }
  23929. } compare;
  23930. virtual ICompare * queryCompare() { return &compare; }
  23931. virtual IOutputMetaData * queryOutputMeta()
  23932. {
  23933. return &testMeta;
  23934. }
  23935. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23936. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23937. };
  23938. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23939. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23940. static bool isDedup;
  23941. public:
  23942. struct CompareClass : public ICompare {
  23943. virtual int docompare(const void * _left, const void * _right) const {
  23944. return memcmp(_left, _right, 5);
  23945. }
  23946. } compare;
  23947. virtual ICompare * queryCompare() { return &compare; }
  23948. virtual IOutputMetaData * queryOutputMeta()
  23949. {
  23950. return &testMeta;
  23951. }
  23952. virtual bool dedup() { return isDedup; }
  23953. };
  23954. bool MergeActivityTest::isDedup = false;
  23955. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23956. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  23957. public:
  23958. virtual unsigned numBranches() { return 2; }
  23959. virtual IOutputMetaData * queryOutputMeta()
  23960. {
  23961. return &testMeta;
  23962. }
  23963. };
  23964. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  23965. class CcdServerTest : public CppUnit::TestFixture
  23966. {
  23967. CPPUNIT_TEST_SUITE(CcdServerTest);
  23968. CPPUNIT_TEST(testSetup);
  23969. CPPUNIT_TEST(testHeapSort);
  23970. CPPUNIT_TEST(testInsertionSort);
  23971. CPPUNIT_TEST(testQuickSort);
  23972. CPPUNIT_TEST(testMerge);
  23973. CPPUNIT_TEST(testMergeDedup);
  23974. CPPUNIT_TEST(testMiscellaneous);
  23975. CPPUNIT_TEST(testSplitter);
  23976. CPPUNIT_TEST(testCleanup);
  23977. CPPUNIT_TEST_SUITE_END();
  23978. protected:
  23979. SlaveContextLogger logctx;
  23980. Owned<const IQueryDll> queryDll;
  23981. Owned<IRoxiePackage> package;
  23982. Owned<IPropertyTree> stateInfo;
  23983. Owned<IQueryFactory> queryFactory;
  23984. Owned<IRoxieSlaveContext> ctx;
  23985. void testSetup()
  23986. {
  23987. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  23988. }
  23989. void testCleanup()
  23990. {
  23991. roxiemem::releaseRoxieHeap();
  23992. }
  23993. void init()
  23994. {
  23995. package.setown(createRoxiePackage(NULL, NULL));
  23996. queryDll.setown(createExeQueryDll("roxie"));
  23997. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  23998. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  23999. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  24000. queryActiveTimer()->reset();
  24001. }
  24002. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  24003. {
  24004. testActivity(activity, input, NULL, output);
  24005. }
  24006. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  24007. {
  24008. TestInput in(ctx, input);
  24009. TestInput in2(ctx, input2);
  24010. activity->setInput(0, &in);
  24011. if (input2)
  24012. activity->setInput(1, &in2);
  24013. IRoxieInput *out = activity->queryOutput(outputIdx);
  24014. IOutputMetaData *meta = out->queryOutputMeta();
  24015. void *buf = alloca(meta->getFixedSize());
  24016. for (unsigned iteration = 0; iteration < 8; iteration++)
  24017. {
  24018. // 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)
  24019. // This should be true whether we read all, some, or none of the data.
  24020. // Should not matter if an activity is not started
  24021. if (iteration % 4 == 0)
  24022. activity->onCreate(ctx, NULL);
  24023. unsigned count = 0;
  24024. if (iteration % 4 != 3)
  24025. {
  24026. activity->start(0, NULL, false);
  24027. ASSERT(in.state == TestInput::STATEstarted);
  24028. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  24029. loop
  24030. {
  24031. const void *next = out->nextInGroup();
  24032. if (!next)
  24033. {
  24034. ASSERT(output[count++] == NULL);
  24035. next = out->nextInGroup();
  24036. if (!next)
  24037. {
  24038. ASSERT(output[count++] == NULL);
  24039. break;
  24040. }
  24041. }
  24042. ASSERT(output[count] != NULL);
  24043. unsigned outsize = meta->getRecordSize(next);
  24044. memset(buf, 0, outsize);
  24045. strncpy((char *) buf, output[count++], outsize);
  24046. ASSERT(memcmp(next, buf, outsize) == 0);
  24047. ReleaseRoxieRow(next);
  24048. if (iteration % 4 == 2)
  24049. break;
  24050. }
  24051. if (iteration % 4 != 2)
  24052. {
  24053. // Check that reading after end is harmless
  24054. in.allRead = true;
  24055. const void *next = out->nextInGroup();
  24056. ASSERT(next == NULL);
  24057. }
  24058. }
  24059. activity->stop(false);
  24060. ASSERT(in.state == TestInput::STATEstopped);
  24061. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  24062. activity->reset();
  24063. ASSERT(in.state == TestInput::STATEreset);
  24064. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  24065. ctx->queryRowManager().reportLeaks();
  24066. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24067. }
  24068. }
  24069. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  24070. {
  24071. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24072. TestInput in(ctx, input);
  24073. in.repeat = repeat;
  24074. activity->setInput(0, &in);
  24075. ArrayOf<IRoxieInput *> out;
  24076. for (unsigned i = 0; i < numOutputs; i++)
  24077. {
  24078. out.append(activity->queryOutput(i));
  24079. }
  24080. activity->onCreate(ctx, NULL);
  24081. class casyncfor: public CAsyncFor
  24082. {
  24083. public:
  24084. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  24085. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  24086. {}
  24087. void Do(unsigned i)
  24088. {
  24089. IRoxieInput *out = outputs.item(i);
  24090. out->start(0, NULL, false);
  24091. IOutputMetaData *meta = out->queryOutputMeta();
  24092. void *buf = alloca(meta->getFixedSize());
  24093. unsigned count = 0;
  24094. unsigned repeats = repeat;
  24095. loop
  24096. {
  24097. const void *next = out->nextInGroup();
  24098. if (!next)
  24099. {
  24100. ASSERT(repeats==0);
  24101. ASSERT(output[count++] == NULL);
  24102. next = out->nextInGroup();
  24103. if (!next)
  24104. {
  24105. ASSERT(output[count++] == NULL);
  24106. break;
  24107. }
  24108. }
  24109. if (output[count] == NULL && repeats)
  24110. {
  24111. repeats--;
  24112. count = 0;
  24113. }
  24114. ASSERT(output[count] != NULL);
  24115. unsigned outsize = meta->getRecordSize(next);
  24116. memset(buf, 0, outsize);
  24117. strncpy((char *) buf, output[count++], outsize);
  24118. ASSERT(memcmp(next, buf, outsize) == 0);
  24119. ReleaseRoxieRow(next);
  24120. }
  24121. out->stop(false);
  24122. }
  24123. private:
  24124. IRoxieServerActivity *activity;
  24125. ArrayOf<IRoxieInput *> &outputs;
  24126. char const * const *input;
  24127. char const * const *output;
  24128. unsigned repeat;
  24129. CcdServerTest *parent;
  24130. } afor(this, activity, out, input, output, repeat);
  24131. afor.For(numOutputs, numOutputs);
  24132. ASSERT(in.state == TestInput::STATEstopped);
  24133. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  24134. {
  24135. out.item(i2)->reset();
  24136. }
  24137. ASSERT(in.state == TestInput::STATEreset);
  24138. ctx->queryRowManager().reportLeaks();
  24139. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24140. }
  24141. static int compareFunc(const void *l, const void *r)
  24142. {
  24143. return strcmp(*(char **) l, *(char **) r);
  24144. }
  24145. void testSort(unsigned type)
  24146. {
  24147. init();
  24148. sortAlgorithm = NULL;
  24149. if (type==2)
  24150. sortAlgorithm = "heapSort";
  24151. else if (type == 1)
  24152. sortAlgorithm = "insertionSort";
  24153. else
  24154. sortAlgorithm = "quickSort";
  24155. DBGLOG("Testing %s activity", sortAlgorithm);
  24156. Owned<IPropertyTree> dummyNode = createPTree("node");
  24157. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  24158. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24159. const char * test[] = { NULL, NULL };
  24160. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24161. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  24162. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24163. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24164. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24165. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24166. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24167. testActivity(activity, test, test);
  24168. testActivity(activity, test12345, test12345);
  24169. testActivity(activity, test54321, test12345);
  24170. testActivity(activity, test11111, test11111);
  24171. testActivity(activity, test11111_12345, test11111_12345);
  24172. testActivity(activity, test11111_54321, test11111_12345);
  24173. testActivity(activity, test54321_54321, test12345_12345);
  24174. // A few larger tests
  24175. char *input[2002];
  24176. char *output[2002];
  24177. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  24178. unsigned i;
  24179. // identical
  24180. for (i=0; i<2000; i++)
  24181. {
  24182. input[i] = new char[11];
  24183. output[i] = new char[11];
  24184. sprintf(input[i], "1");
  24185. sprintf(output[i], "1");
  24186. }
  24187. testActivity(activity, input, output);
  24188. // Ascending
  24189. for (i=0; i<2000; i++)
  24190. {
  24191. sprintf(input[i], "%04d", i);
  24192. sprintf(output[i], "%04d", i);
  24193. }
  24194. testActivity(activity, input, output);
  24195. // Almost sorted
  24196. for (i=0; i<20; i++)
  24197. {
  24198. unsigned h = i*100;
  24199. sprintf(input[h], "%04d", 1900-h);
  24200. }
  24201. testActivity(activity, input, output);
  24202. // Descending
  24203. for (i=0; i<2000; i++)
  24204. {
  24205. sprintf(input[i], "%04d", 1999-i);
  24206. sprintf(output[i], "%04d", i);
  24207. }
  24208. testActivity(activity, input, output);
  24209. // Random
  24210. for (i=0; i<2000; i++)
  24211. {
  24212. unsigned r = rand() % 1500;
  24213. sprintf(input[i], "%04d", r);
  24214. sprintf(output[i], "%04d", r);
  24215. }
  24216. qsort(output, 2000, sizeof(output[0]), compareFunc);
  24217. testActivity(activity, input, output);
  24218. #if 0
  24219. // Random
  24220. #define BIGSORTSIZE 1000000
  24221. char **linput = new char*[BIGSORTSIZE +2];
  24222. char **loutput = new char *[BIGSORTSIZE+2];
  24223. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  24224. for (i=0; i<BIGSORTSIZE; i++)
  24225. {
  24226. unsigned r = rand() % 15000;
  24227. linput[i] = loutput[i] = new char[11];
  24228. sprintf(linput[i], "%04d", r);
  24229. }
  24230. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  24231. testActivity(activity, linput, loutput);
  24232. for (i=0; i<BIGSORTSIZE; i++)
  24233. {
  24234. delete [] linput[i];
  24235. }
  24236. delete [] linput;
  24237. delete [] loutput;
  24238. #endif
  24239. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  24240. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  24241. factory->resetNodeProgressInfo();
  24242. if (type)
  24243. {
  24244. // Other than quicksort, it's supposed to be stable. Let's check that it is
  24245. // All sort identical
  24246. for (i=0; i<2000; i++)
  24247. {
  24248. sprintf(input[i], "1 %d", i);
  24249. sprintf(output[i], "1 %d", i);
  24250. }
  24251. testActivity(activity, input, output);
  24252. // Already sorted
  24253. for (i=0; i<2000; i++)
  24254. {
  24255. sprintf(input[i], "%04d %d", i / 10, i);
  24256. sprintf(output[i], "%04d %d", i / 10, i);
  24257. }
  24258. testActivity(activity, input, output);
  24259. // Reverse order
  24260. for (i=0; i<2000; i++)
  24261. {
  24262. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  24263. sprintf(output[i], "%04d %d", i / 10, i%10);
  24264. }
  24265. testActivity(activity, input, output);
  24266. }
  24267. for (i=0; i<2000; i++)
  24268. {
  24269. delete [] input[i];
  24270. delete [] output[i];
  24271. }
  24272. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  24273. }
  24274. void testQuickSort()
  24275. {
  24276. testSort(0);
  24277. }
  24278. void testInsertionSort()
  24279. {
  24280. testSort(1);
  24281. }
  24282. void testHeapSort()
  24283. {
  24284. testSort(2);
  24285. }
  24286. void testMerge()
  24287. {
  24288. DBGLOG("testMerge");
  24289. init();
  24290. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24291. factory->setInput(0,0,0);
  24292. factory->setInput(1,0,0);
  24293. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24294. const char * test[] = { NULL, NULL };
  24295. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24296. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  24297. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24298. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  24299. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24300. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24301. 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 };
  24302. testActivity(activity, test, test, test);
  24303. testActivity(activity, test12345, test, test12345);
  24304. testActivity(activity, test, test12345, test12345);
  24305. testActivity(activity, test12345, test12345, test1122334455);
  24306. testActivity(activity, test11111, test, test11111);
  24307. testActivity(activity, test, test11111, test11111);
  24308. testActivity(activity, test11111, test11111, test1111111111);
  24309. testActivity(activity, test11111_12345, test, test1111112345);
  24310. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  24311. // Should really test WHICH side gets kept...
  24312. // Should test with more than 2 inputs...
  24313. DBGLOG("testMerge done");
  24314. }
  24315. void testMergeDedup()
  24316. {
  24317. DBGLOG("testMergeDedup");
  24318. init();
  24319. MergeActivityTest::isDedup = true;
  24320. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24321. factory->setInput(0,0,0);
  24322. factory->setInput(1,0,0);
  24323. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24324. const char * test[] = { NULL, NULL };
  24325. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24326. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24327. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24328. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24329. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  24330. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  24331. testActivity(activity, test, test11111, test11111);
  24332. testActivity(activity, test, test, test);
  24333. testActivity(activity, test12345, test, test12345);
  24334. testActivity(activity, test, test12345, test12345);
  24335. testActivity(activity, test12345, test12345, test12345);
  24336. testActivity(activity, test11111_12345, test, test1111112345);
  24337. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  24338. // Should really test WHICH side gets kept...
  24339. // Should test with more than 2 inputs...
  24340. DBGLOG("testMergeDedup done");
  24341. }
  24342. void doTestSplitter(unsigned numOutputs)
  24343. {
  24344. DBGLOG("testSplit %d", numOutputs);
  24345. init();
  24346. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs);
  24347. factory->setInput(0,0,0);
  24348. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24349. const char * test[] = { NULL, NULL };
  24350. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24351. unsigned start = msTick();
  24352. testSplitActivity(factory, test, test, numOutputs, 0);
  24353. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  24354. testSplitActivity(factory, test12345, test12345, numOutputs, 1000000);
  24355. unsigned elapsed = msTick() - start;
  24356. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  24357. }
  24358. void testSplitter()
  24359. {
  24360. doTestSplitter(1);
  24361. doTestSplitter(2);
  24362. doTestSplitter(3);
  24363. doTestSplitter(10);
  24364. }
  24365. void testMiscellaneous()
  24366. {
  24367. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  24368. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  24369. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  24370. ASSERT(sizeof(CJoinGroup) <= 120);
  24371. }
  24372. };
  24373. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  24374. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  24375. #endif