ccdserver.cpp 911 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117
  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. namespace ccdserver_hqlhelper
  40. {
  41. #include "eclhelper_base.hpp"
  42. }
  43. #include "ccd.hpp"
  44. #include "ccdserver.hpp"
  45. #include "ccdcontext.hpp"
  46. #include "ccdactivities.hpp"
  47. #include "ccdquery.hpp"
  48. #include "ccdstate.hpp"
  49. #include "ccdqueue.ipp"
  50. #include "ccdsnmp.hpp"
  51. #include "ccddali.hpp"
  52. #include "jsmartsock.hpp"
  53. #include "dllserver.hpp"
  54. #include "workflow.hpp"
  55. #include "roxiemem.hpp"
  56. #include "roxierowbuff.hpp"
  57. #include "roxiehelper.hpp"
  58. #include "roxielmj.hpp"
  59. #include "roxierow.hpp"
  60. #include "thorplugin.hpp"
  61. #include "keybuild.hpp"
  62. #define MAX_HTTP_HEADERSIZE 8000
  63. #define MIN_PAYLOAD_SIZE 800
  64. #pragma warning(disable : 4355)
  65. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  66. #define PROBE
  67. #ifdef _DEBUG
  68. //#define FAKE_EXCEPTIONS
  69. //#define TRACE_JOINGROUPS
  70. //#define TRACE_SPLIT
  71. //#define _CHECK_HEAPSORT
  72. //#undef PARALLEL_EXECUTE
  73. //#define TRACE_SEEK_REQUESTS
  74. #endif
  75. using roxiemem::OwnedRoxieRow;
  76. using roxiemem::OwnedRoxieString;
  77. using roxiemem::OwnedConstRoxieRow;
  78. using roxiemem::IRowManager;
  79. // 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...
  80. #if _MSC_VER==1200
  81. #define protected public
  82. #endif
  83. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  84. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  85. inline void ReleaseRoxieRowSet(ConstPointerArray &data)
  86. {
  87. ForEachItemIn(idx, data)
  88. ReleaseRoxieRow(data.item(idx));
  89. data.kill();
  90. }
  91. //=================================================================================
  92. class RestartableThread : public CInterface
  93. {
  94. class MyThread : public Thread
  95. {
  96. Linked<RestartableThread> owner;
  97. public:
  98. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  99. {
  100. }
  101. virtual int run()
  102. {
  103. owner->started.signal();
  104. return owner->run();
  105. }
  106. };
  107. friend class MyThread;
  108. Semaphore started;
  109. Owned<MyThread> thread;
  110. CriticalSection crit;
  111. StringAttr name;
  112. public:
  113. RestartableThread(const char *_name) : name(_name)
  114. {
  115. }
  116. virtual void start(const char *namePrefix)
  117. {
  118. StringBuffer s(namePrefix);
  119. s.append(name);
  120. {
  121. CriticalBlock b(crit);
  122. assertex(!thread);
  123. thread.setown(new MyThread(this, s));
  124. thread->start();
  125. }
  126. started.wait();
  127. }
  128. virtual void join()
  129. {
  130. {
  131. Owned<Thread> tthread;
  132. {
  133. CriticalBlock b(crit);
  134. tthread.setown(thread.getClear());
  135. }
  136. if (tthread)
  137. tthread->join();
  138. }
  139. }
  140. virtual int run() = 0;
  141. };
  142. //================================================================================
  143. // default implementation - can be overridden for efficiency...
  144. bool IRoxieInput::nextGroup(ConstPointerArray & group)
  145. {
  146. // MORE - this should be replaced with a version that reads to a builder
  147. const void * next;
  148. while ((next = nextInGroup()) != NULL)
  149. group.append(next);
  150. if (group.ordinality())
  151. return true;
  152. return false;
  153. }
  154. void IRoxieInput::readAll(RtlLinkedDatasetBuilder &builder)
  155. {
  156. loop
  157. {
  158. const void *nextrec = nextInGroup();
  159. if (!nextrec)
  160. {
  161. nextrec = nextInGroup();
  162. if (!nextrec)
  163. break;
  164. builder.appendEOG();
  165. }
  166. builder.appendOwn(nextrec);
  167. }
  168. }
  169. inline const void * nextUngrouped(IRoxieInput * input)
  170. {
  171. const void * ret = input->nextInGroup();
  172. if (!ret)
  173. ret = input->nextInGroup();
  174. return ret;
  175. };
  176. //=================================================================================
  177. //The following don't link their arguments because that creates a circular reference
  178. //But I wish there was a better way
  179. class IndirectSlaveContext : public CInterface, implements IRoxieSlaveContext
  180. {
  181. public:
  182. IndirectSlaveContext(IRoxieSlaveContext * _ctx = NULL) : ctx(_ctx) {}
  183. IMPLEMENT_IINTERFACE
  184. void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  185. virtual ICodeContext *queryCodeContext()
  186. {
  187. return ctx->queryCodeContext();
  188. }
  189. virtual void checkAbort()
  190. {
  191. ctx->checkAbort();
  192. }
  193. virtual void notifyAbort(IException *E)
  194. {
  195. ctx->notifyAbort(E);
  196. }
  197. virtual IActivityGraph * queryChildGraph(unsigned id)
  198. {
  199. return ctx->queryChildGraph(id);
  200. }
  201. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  202. {
  203. ctx->noteChildGraph(id, childGraph) ;
  204. }
  205. virtual IRowManager &queryRowManager()
  206. {
  207. return ctx->queryRowManager();
  208. }
  209. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  210. {
  211. ctx->noteStatistic(kind, value);
  212. }
  213. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  214. {
  215. ctx->mergeStats(from);
  216. }
  217. virtual const CRuntimeStatisticCollection &queryStats() const
  218. {
  219. return ctx->queryStats();
  220. }
  221. virtual void CTXLOGva(const char *format, va_list args) const
  222. {
  223. ctx->CTXLOGva(format, args);
  224. }
  225. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  226. {
  227. ctx->CTXLOGa(category, prefix, text);
  228. }
  229. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  230. {
  231. ctx->logOperatorExceptionVA(E, file, line, format, args);
  232. }
  233. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  234. {
  235. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  236. }
  237. virtual void CTXLOGl(LogItem *log) const
  238. {
  239. ctx->CTXLOGl(log);
  240. }
  241. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  242. {
  243. return ctx->getLogPrefix(ret);
  244. }
  245. virtual unsigned queryTraceLevel() const
  246. {
  247. return ctx->queryTraceLevel();
  248. }
  249. virtual bool isIntercepted() const
  250. {
  251. return ctx->isIntercepted();
  252. }
  253. virtual bool isBlind() const
  254. {
  255. return ctx->isBlind();
  256. }
  257. virtual const QueryOptions &queryOptions() const
  258. {
  259. return ctx->queryOptions();
  260. }
  261. virtual void addSlavesReplyLen(unsigned len)
  262. {
  263. ctx->addSlavesReplyLen(len);
  264. }
  265. virtual const char *queryAuthToken()
  266. {
  267. return ctx->queryAuthToken();
  268. }
  269. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  270. {
  271. return ctx->resolveLFN(filename, isOpt);
  272. }
  273. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  274. {
  275. return ctx->createLFN(filename, overwrite, extend, clusters);
  276. }
  277. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  278. {
  279. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  280. }
  281. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  282. {
  283. return ctx->getLibraryGraph(extra, parentActivity);
  284. }
  285. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed) const
  286. {
  287. ctx->noteProcessed(subgraphId, activityId, _idx, _processed);
  288. }
  289. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  290. {
  291. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  292. }
  293. virtual IProbeManager *queryProbeManager() const
  294. {
  295. return ctx->queryProbeManager();
  296. }
  297. virtual IDebuggableContext *queryDebugContext() const
  298. {
  299. return ctx->queryDebugContext();
  300. }
  301. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  302. {
  303. ctx->printResults(output, name, sequence);
  304. }
  305. virtual void setWUState(WUState state)
  306. {
  307. ctx->setWUState(state);
  308. }
  309. virtual bool checkWuAborted()
  310. {
  311. return ctx->checkWuAborted();
  312. }
  313. virtual IWorkUnit *updateWorkUnit() const
  314. {
  315. return ctx->updateWorkUnit();
  316. }
  317. virtual IConstWorkUnit *queryWorkUnit() const
  318. {
  319. return ctx->queryWorkUnit();
  320. }
  321. virtual IRoxieServerContext *queryServerContext()
  322. {
  323. return ctx->queryServerContext();
  324. }
  325. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  326. {
  327. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  328. }
  329. protected:
  330. IRoxieSlaveContext * ctx;
  331. };
  332. //=================================================================================
  333. #define RESULT_FLUSH_THRESHOLD 10000u
  334. #ifdef _DEBUG
  335. #define SOAP_SPLIT_THRESHOLD 100u
  336. #define SOAP_SPLIT_RESERVE 200u
  337. #else
  338. #define SOAP_SPLIT_THRESHOLD 64000u
  339. #define SOAP_SPLIT_RESERVE 65535u
  340. #endif
  341. //=================================================================================
  342. // General activity statistics
  343. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  344. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StKindNone);
  345. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  346. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  347. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  348. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  349. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  350. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  351. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  352. StNumDiskRejected, StKindNone);
  353. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  354. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  355. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  356. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  357. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  358. StNumIndexRowsRead, StKindNone);
  359. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  360. StNumDiskRejected, StKindNone);
  361. static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
  362. //=================================================================================
  363. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  364. {
  365. protected:
  366. IntArray dependencies; // things I am dependent on
  367. IntArray dependencyIndexes; // things I am dependent on
  368. IntArray dependencyControlIds; // things I am dependent on
  369. StringArray dependencyEdgeIds; // How to describe them to the debugger
  370. unsigned dependentCount; // things dependent on me
  371. mutable CriticalSection statsCrit;
  372. mutable __int64 processed;
  373. mutable __int64 started;
  374. mutable __int64 totalCycles;
  375. mutable __int64 localCycles;
  376. public:
  377. IMPLEMENT_IINTERFACE;
  378. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  379. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  380. {
  381. processed = 0;
  382. started = 0;
  383. totalCycles = 0;
  384. localCycles = 0;
  385. dependentCount = 0;
  386. }
  387. ~CRoxieServerActivityFactoryBase()
  388. {
  389. }
  390. StringBuffer &toString(StringBuffer &ret) const
  391. {
  392. return ret.appendf("%p", this);
  393. }
  394. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  395. {
  396. dependencies.append(_source);
  397. dependencyIndexes.append(_sourceIdx);
  398. dependencyControlIds.append(controlId);
  399. dependencyEdgeIds.append(edgeId);
  400. }
  401. virtual void noteDependent(unsigned target)
  402. {
  403. dependentCount++;
  404. }
  405. virtual IntArray &queryDependencies() { return dependencies; }
  406. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  407. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  408. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  409. virtual unsigned queryId() const { return id; }
  410. virtual unsigned querySubgraphId() const { return subgraphId; }
  411. virtual ThorActivityKind getKind() const { return kind; }
  412. virtual IOutputMetaData * queryOutputMeta() const
  413. {
  414. return meta;
  415. }
  416. virtual bool isSink() const
  417. {
  418. return false;
  419. }
  420. virtual bool isFunction() const
  421. {
  422. return false;
  423. }
  424. virtual bool isGraphInvariant() const
  425. {
  426. return false;
  427. }
  428. virtual IHThorArg &getHelper() const
  429. {
  430. return *helperFactory();
  431. }
  432. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  433. {
  434. arg.Release();
  435. throwUnexpected();
  436. }
  437. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  438. {
  439. CActivityFactory::mergeStats(from);
  440. }
  441. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  442. {
  443. dbgassertex(!_idx);
  444. if (_processed)
  445. {
  446. CriticalBlock b(statsCrit);
  447. processed += processed;
  448. }
  449. }
  450. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  451. {
  452. if (_totalCycles.totalCycles || _localCycles)
  453. {
  454. CriticalBlock b(statsCrit);
  455. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  456. totalCycles += _totalCycles.totalCycles;
  457. localCycles += _localCycles;
  458. }
  459. CActivityFactory::mergeStats(fromStats);
  460. }
  461. virtual void noteStarted() const
  462. {
  463. CriticalBlock b(statsCrit);
  464. started ++;
  465. }
  466. virtual void noteStarted(unsigned idx) const
  467. {
  468. throwUnexpected(); // should be implemented/required by multiOutput cases only
  469. }
  470. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  471. {
  472. CriticalBlock b(statsCrit);
  473. if (output == 0)
  474. {
  475. putStatsValue(&edge, "count", "sum", processed);
  476. if (started)
  477. putStatsValue(&edge, "started", "sum", started);
  478. }
  479. else
  480. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  481. }
  482. virtual void getNodeProgressInfo(IPropertyTree &node) const
  483. {
  484. CActivityFactory::getNodeProgressInfo(node);
  485. CriticalBlock b(statsCrit);
  486. if (started)
  487. putStatsValue(&node, "_roxieStarted", "sum", started);
  488. if (totalCycles)
  489. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  490. if (localCycles)
  491. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  492. }
  493. virtual void resetNodeProgressInfo()
  494. {
  495. CActivityFactory::resetNodeProgressInfo();
  496. CriticalBlock b(statsCrit);
  497. processed = 0;
  498. started = 0;
  499. totalCycles = 0;
  500. localCycles = 0;
  501. }
  502. virtual void getActivityMetrics(StringBuffer &reply) const
  503. {
  504. CActivityFactory::getActivityMetrics(reply);
  505. CriticalBlock b(statsCrit);
  506. putStatsValue(reply, "_roxieStarted", "sum", started);
  507. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  508. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  509. }
  510. virtual unsigned __int64 queryLocalCycles() const
  511. {
  512. return localCycles;
  513. }
  514. virtual IQueryFactory &queryQueryFactory() const
  515. {
  516. return CActivityFactory::queryQueryFactory();
  517. }
  518. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  519. {
  520. return CActivityFactory::queryChildQuery(idx, id);
  521. }
  522. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  523. {
  524. CActivityFactory::addChildQuery(id, childQuery);
  525. }
  526. virtual void createChildQueries(IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx) const
  527. {
  528. ForEachItemIn(idx, childQueries)
  529. {
  530. childGraphs.append(*createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx));
  531. }
  532. }
  533. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs) const
  534. {
  535. ForEachItemIn(idx, childGraphs)
  536. {
  537. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  538. childGraphs.item(idx).onCreate(ctx, colocalArg);
  539. }
  540. }
  541. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  542. {
  543. unsigned match = childQueryIndexes.find(childId);
  544. assertex(match != NotFound);
  545. Owned<IActivityGraph> graph = createActivityGraph(NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx);
  546. graph->onCreate(ctx, colocalArg);
  547. return graph.getClear();
  548. }
  549. virtual IRoxieServerSideCache *queryServerSideCache() const
  550. {
  551. return NULL; // Activities that wish to support server-side caching will need to do better....
  552. }
  553. virtual bool getEnableFieldTranslation() const
  554. {
  555. throwUnexpected(); // only implemented by index-related subclasses
  556. }
  557. virtual IDefRecordMeta *queryActivityMeta() const
  558. {
  559. throwUnexpected(); // only implemented by index-related subclasses
  560. }
  561. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  562. {
  563. // Most activities have nothing to say...
  564. }
  565. virtual const StatisticsMapping &queryStatsMapping() const
  566. {
  567. return actStatistics; // Overridden by anyone that needs more
  568. }
  569. };
  570. class CRoxieServerMultiInputInfo
  571. {
  572. private:
  573. UnsignedArray inputs;
  574. UnsignedArray inputIndexes;
  575. public:
  576. void set(unsigned idx, unsigned source, unsigned sourceidx)
  577. {
  578. if (idx==inputs.length())
  579. {
  580. inputs.append(source);
  581. inputIndexes.append(sourceidx);
  582. }
  583. else
  584. {
  585. while (!inputs.isItem(idx))
  586. {
  587. inputs.append(0);
  588. inputIndexes.append(0);
  589. }
  590. inputs.replace(source, idx);
  591. inputIndexes.replace(sourceidx, idx);
  592. }
  593. }
  594. unsigned get(unsigned idx, unsigned &sourceidx) const
  595. {
  596. if (inputs.isItem(idx))
  597. {
  598. sourceidx = inputIndexes.item(idx);
  599. return inputs.item(idx);
  600. }
  601. else
  602. return (unsigned) -1;
  603. }
  604. inline unsigned ordinality() const { return inputs.ordinality(); }
  605. };
  606. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  607. {
  608. private:
  609. CRoxieServerMultiInputInfo inputs;
  610. public:
  611. IMPLEMENT_IINTERFACE;
  612. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  613. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  614. {
  615. }
  616. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  617. {
  618. inputs.set(idx, source, sourceidx);
  619. }
  620. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  621. {
  622. return inputs.get(idx, sourceidx);
  623. }
  624. virtual unsigned numInputs() const { return inputs.ordinality(); }
  625. };
  626. class CWrappedException : public CInterface, implements IException
  627. {
  628. Owned<IException> wrapped;
  629. ThorActivityKind kind;
  630. unsigned queryId;
  631. public:
  632. IMPLEMENT_IINTERFACE;
  633. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  634. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  635. {
  636. }
  637. virtual int errorCode() const { return wrapped->errorCode(); }
  638. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  639. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  640. };
  641. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  642. {
  643. protected:
  644. unsigned input;
  645. unsigned inputidx;
  646. public:
  647. IMPLEMENT_IINTERFACE;
  648. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  649. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  650. {
  651. input = (unsigned) -1;
  652. inputidx = 0;
  653. }
  654. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  655. {
  656. if (idx != 0)
  657. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  658. if (input != -1)
  659. 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__);
  660. input = source;
  661. inputidx = sourceidx;
  662. }
  663. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  664. {
  665. if (!idx)
  666. {
  667. sourceidx = inputidx;
  668. return input;
  669. }
  670. return (unsigned) -1;
  671. }
  672. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  673. };
  674. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  675. {
  676. protected:
  677. unsigned numOutputs;
  678. unsigned __int64 *processedArray;
  679. bool *startedArray;
  680. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  681. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  682. {
  683. numOutputs = 0;
  684. processedArray = NULL;
  685. startedArray = NULL;
  686. }
  687. ~CRoxieServerMultiOutputFactory()
  688. {
  689. delete [] processedArray;
  690. delete [] startedArray;
  691. }
  692. void setNumOutputs(unsigned num)
  693. {
  694. numOutputs = num;
  695. if (!num)
  696. num = 1; // Even sink activities like to track how many records they process
  697. processedArray = new unsigned __int64[num];
  698. startedArray = new bool[num];
  699. for (unsigned i = 0; i < num; i++)
  700. {
  701. processedArray[i] = 0;
  702. startedArray[i] = 0;
  703. }
  704. }
  705. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  706. {
  707. assertex(numOutputs ? idx < numOutputs : idx==0);
  708. CriticalBlock b(statsCrit);
  709. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  710. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  711. }
  712. virtual void resetNodeProgressInfo()
  713. {
  714. CRoxieServerActivityFactory::resetNodeProgressInfo();
  715. CriticalBlock b(statsCrit);
  716. for (unsigned i = 0; i < numOutputs; i++)
  717. {
  718. processedArray[i] = 0;
  719. startedArray[i] = 0;
  720. }
  721. }
  722. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  723. {
  724. assertex(numOutputs ? idx < numOutputs : idx==0);
  725. CriticalBlock b(statsCrit);
  726. processedArray[idx] += _processed;
  727. }
  728. virtual void noteStarted(unsigned idx) const
  729. {
  730. assertex(numOutputs ? idx < numOutputs : idx==0);
  731. CriticalBlock b(statsCrit);
  732. startedArray[idx] = true;
  733. }
  734. };
  735. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  736. {
  737. protected:
  738. bool isInternal;
  739. bool isRoot;
  740. unsigned usageCount;
  741. public:
  742. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  743. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  744. {
  745. usageCount = _usageCount;
  746. isRoot = _isRoot;
  747. isInternal = false; // filled in by derived class constructor
  748. }
  749. virtual bool isSink() const
  750. {
  751. //only a sink if a root activity
  752. 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?
  753. }
  754. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  755. {
  756. // 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
  757. // Just leave it blank is safest.
  758. }
  759. };
  760. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  761. const char *queryStateText(activityState state)
  762. {
  763. switch (state)
  764. {
  765. case STATEreset: return "reset";
  766. case STATEstarted: return "started";
  767. case STATEstopped: return "stopped";
  768. case STATEstarting: return "starting";
  769. default: return "unknown";
  770. }
  771. }
  772. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  773. class CParallelActivityExecutor : public CAsyncFor
  774. {
  775. public:
  776. unsigned parentExtractSize;
  777. const byte * parentExtract;
  778. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  779. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  780. void Do(unsigned i)
  781. {
  782. activities.item(i).execute(parentExtractSize, parentExtract);
  783. }
  784. private:
  785. IRoxieServerActivityCopyArray & activities;
  786. };
  787. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  788. {
  789. protected:
  790. IRoxieInput *input;
  791. IHThorArg &basehelper;
  792. IRoxieSlaveContext *ctx;
  793. const IRoxieServerActivityFactory *factory;
  794. IRoxieServerActivityCopyArray dependencies;
  795. IntArray dependencyIndexes;
  796. IntArray dependencyControlIds;
  797. IArrayOf<IActivityGraph> childGraphs;
  798. CachedOutputMetaData meta;
  799. IHThorArg *colocalParent;
  800. IEngineRowAllocator *rowAllocator;
  801. CriticalSection statecrit;
  802. mutable CRuntimeStatisticCollection stats;
  803. unsigned processed;
  804. ActivityTimeAccumulator totalCycles;
  805. cycle_t localCycles;
  806. unsigned activityId;
  807. activityState state;
  808. bool createPending;
  809. bool debugging;
  810. bool timeActivities;
  811. public:
  812. IMPLEMENT_IINTERFACE;
  813. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  814. : factory(_factory),
  815. basehelper(_factory->getHelper()),
  816. activityId(_factory->queryId()),
  817. stats(_factory ? factory->queryStatsMapping() : actStatistics)
  818. {
  819. input = NULL;
  820. ctx = NULL;
  821. meta.set(basehelper.queryOutputMeta());
  822. processed = 0;
  823. localCycles = 0;
  824. if (factory)
  825. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  826. state=STATEreset;
  827. rowAllocator = NULL;
  828. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  829. colocalParent = NULL;
  830. createPending = true;
  831. timeActivities = defaultTimeActivities;
  832. }
  833. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper), stats(allStatistics)
  834. {
  835. activityId = 0;
  836. input = NULL;
  837. ctx = NULL;
  838. meta.set(basehelper.queryOutputMeta());
  839. processed = 0;
  840. localCycles = 0;
  841. state=STATEreset;
  842. rowAllocator = NULL;
  843. debugging = false;
  844. colocalParent = NULL;
  845. createPending = true;
  846. timeActivities = defaultTimeActivities;
  847. }
  848. ~CRoxieServerActivity()
  849. {
  850. if (traceStartStop)
  851. {
  852. // There was an old comment here stating // Note- CTXLOG may not be safe
  853. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  854. // was released while activities still referenced it.
  855. // However these should now all be fixed
  856. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  857. if (watchActivityId && watchActivityId==activityId)
  858. {
  859. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  860. }
  861. }
  862. if (state!=STATEreset)
  863. {
  864. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  865. state = STATEreset; // bit pointless but there you go...
  866. }
  867. if (factory && !debugging)
  868. {
  869. if (processed)
  870. factory->noteProcessed(0, processed);
  871. factory->mergeActivityStats(stats, totalCycles, localCycles);
  872. }
  873. if (ctx)
  874. {
  875. if (processed)
  876. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed);
  877. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  878. }
  879. basehelper.Release();
  880. ::Release(rowAllocator);
  881. }
  882. virtual const IRoxieContextLogger &queryLogCtx()const
  883. {
  884. return *this;
  885. }
  886. virtual void mergeStats(MemoryBuffer &buf)
  887. {
  888. stats.deserializeMerge(buf);
  889. }
  890. inline void createRowAllocator()
  891. {
  892. if (!rowAllocator)
  893. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  894. }
  895. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  896. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  897. {
  898. if (ctx)
  899. ctx->CTXLOGa(category, prefix, text);
  900. else
  901. DBGLOG("[%s] %s", prefix, text);
  902. }
  903. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  904. {
  905. if (ctx)
  906. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  907. else
  908. {
  909. StringBuffer ss;
  910. ss.appendf("[%s] ERROR", prefix);
  911. if (E)
  912. ss.append(": ").append(E->errorCode());
  913. if (file)
  914. ss.appendf(": %s(%d) ", file, line);
  915. if (E)
  916. E->errorMessage(ss.append(": "));
  917. if (format)
  918. {
  919. ss.append(": ").valist_appendf(format, args);
  920. }
  921. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  922. }
  923. }
  924. virtual void CTXLOGl(LogItem *log) const
  925. {
  926. if (ctx)
  927. ctx->CTXLOGl(log);
  928. else
  929. {
  930. assert(ctx);
  931. log->Release(); // Should never happen
  932. }
  933. }
  934. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  935. {
  936. stats.addStatistic(kind, value);
  937. }
  938. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  939. {
  940. stats.merge(from);
  941. }
  942. virtual const CRuntimeStatisticCollection &queryStats() const
  943. {
  944. return stats;
  945. }
  946. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  947. {
  948. if (ctx)
  949. ctx->getLogPrefix(ret);
  950. return ret.append('@').append(activityId);
  951. }
  952. virtual bool isIntercepted() const
  953. {
  954. return ctx ? ctx->isIntercepted() : false;
  955. }
  956. virtual bool isBlind() const
  957. {
  958. return ctx ? ctx->isBlind() : blindLogging;
  959. }
  960. virtual unsigned queryTraceLevel() const
  961. {
  962. if (ctx)
  963. return ctx->queryTraceLevel();
  964. else
  965. return traceLevel;
  966. }
  967. virtual bool isPassThrough()
  968. {
  969. return false;
  970. }
  971. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  972. {
  973. return ctx->resolveLFN(filename, isOpt);
  974. }
  975. virtual const IResolvedFile *queryVarFileInfo() const
  976. {
  977. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  978. return NULL;
  979. }
  980. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  981. {
  982. throwUnexpected(); // should be implemented in more derived class wherever needed
  983. }
  984. virtual IRoxieSlaveContext *queryContext()
  985. {
  986. return ctx;
  987. }
  988. virtual IRoxieServerActivity *queryActivity() { return this; }
  989. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  990. virtual bool needsAllocator() const { return false; }
  991. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  992. {
  993. ctx = _ctx;
  994. colocalParent = _colocalParent;
  995. createPending = true;
  996. if (needsAllocator())
  997. createRowAllocator();
  998. processed = 0;
  999. if (factory)
  1000. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  1001. if (ctx)
  1002. timeActivities = ctx->queryOptions().timeActivities;
  1003. }
  1004. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1005. {
  1006. //This should only be called after onStart has been called on the helper
  1007. assertex(!createPending);
  1008. assertex(state==STATEstarted);
  1009. unsigned startlen = out.length();
  1010. basehelper.serializeCreateContext(out);
  1011. basehelper.serializeStartContext(out);
  1012. if (queryTraceLevel() > 10)
  1013. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1014. }
  1015. virtual void serializeExtra(MemoryBuffer &out) {}
  1016. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1017. {
  1018. CriticalBlock cb(statecrit);
  1019. if (state != STATEreset && state != STATEstarting)
  1020. {
  1021. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1022. }
  1023. state=STATEstarted;
  1024. #ifdef TRACE_STARTSTOP
  1025. if (traceStartStop)
  1026. {
  1027. CTXLOG("start %p %d", this, activityId);
  1028. if (watchActivityId && watchActivityId==activityId)
  1029. {
  1030. CTXLOG("WATCH: start %p %d", this, activityId);
  1031. }
  1032. }
  1033. #endif
  1034. executeDependencies(parentExtractSize, parentExtract, 0);
  1035. if (input)
  1036. input->start(parentExtractSize, parentExtract, paused);
  1037. ensureCreated();
  1038. basehelper.onStart(parentExtract, NULL);
  1039. if (factory)
  1040. factory->noteStarted();
  1041. }
  1042. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1043. {
  1044. //MORE: Create a filtered list and then use asyncfor
  1045. ForEachItemIn(idx, dependencies)
  1046. {
  1047. if (dependencyControlIds.item(idx) == controlId)
  1048. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1049. }
  1050. }
  1051. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1052. {
  1053. ForEachItemIn(idx, dependencies)
  1054. {
  1055. if (dependencyControlIds.item(idx) == controlId)
  1056. dependencies.item(idx).stop(false);
  1057. }
  1058. }
  1059. virtual unsigned __int64 queryTotalCycles() const
  1060. {
  1061. return totalCycles.totalCycles;
  1062. }
  1063. virtual unsigned __int64 queryLocalCycles() const
  1064. {
  1065. __int64 ret = totalCycles.totalCycles;
  1066. if (input) ret -= input->queryTotalCycles();
  1067. if (ret < 0)
  1068. ret = 0;
  1069. return ret;
  1070. }
  1071. virtual IRoxieInput *queryInput(unsigned idx) const
  1072. {
  1073. if (idx==0)
  1074. return input;
  1075. else
  1076. return NULL;
  1077. }
  1078. inline void ensureCreated()
  1079. {
  1080. if (createPending)
  1081. {
  1082. createPending = false;
  1083. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1084. }
  1085. }
  1086. inline void stop(bool aborting)
  1087. {
  1088. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1089. if (state != STATEstopped)
  1090. {
  1091. CriticalBlock cb(statecrit);
  1092. if (state != STATEstopped)
  1093. {
  1094. #ifdef TRACE_STARTSTOP
  1095. if (traceStartStop)
  1096. {
  1097. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1098. if (watchActivityId && watchActivityId==activityId)
  1099. {
  1100. CTXLOG("WATCH: stop %p %d", this, activityId);
  1101. }
  1102. }
  1103. #endif
  1104. state=STATEstopped;
  1105. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1106. ForEachItemIn(idx, dependencies)
  1107. {
  1108. if (dependencyControlIds.item(idx) == 0)
  1109. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1110. }
  1111. if (input)
  1112. input->stop(aborting);
  1113. }
  1114. }
  1115. }
  1116. inline void reset()
  1117. {
  1118. if (state != STATEreset)
  1119. {
  1120. CriticalBlock cb(statecrit);
  1121. if (state != STATEreset)
  1122. {
  1123. if (state==STATEstarted || state==STATEstarting)
  1124. {
  1125. if (traceStartStop || traceLevel > 2)
  1126. CTXLOG("STATE: activity %d reset without stop", activityId);
  1127. stop(false);
  1128. }
  1129. state = STATEreset;
  1130. #ifdef TRACE_STARTSTOP
  1131. if (traceStartStop)
  1132. {
  1133. CTXLOG("reset %p %d", this, activityId);
  1134. if (watchActivityId && watchActivityId==activityId)
  1135. {
  1136. CTXLOG("WATCH: reset %p %d", this, activityId);
  1137. }
  1138. }
  1139. #endif
  1140. ForEachItemIn(idx, dependencies)
  1141. dependencies.item(idx).reset();
  1142. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1143. if (input)
  1144. input->reset();
  1145. }
  1146. }
  1147. }
  1148. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1149. {
  1150. dependencies.append(source);
  1151. dependencyIndexes.append(sourceIdx);
  1152. dependencyControlIds.append(controlId);
  1153. }
  1154. virtual void resetEOF()
  1155. {
  1156. //would make more sense if the default implementation (and eof member) were in the base class
  1157. }
  1158. // Sink activities should override this....
  1159. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1160. {
  1161. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1162. }
  1163. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1164. {
  1165. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1166. }
  1167. virtual void stopSink(unsigned idx)
  1168. {
  1169. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1170. }
  1171. virtual __int64 evaluate()
  1172. {
  1173. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1174. }
  1175. virtual IRoxieInput * querySelectOutput(unsigned id)
  1176. {
  1177. return NULL;
  1178. }
  1179. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1180. {
  1181. return false;
  1182. }
  1183. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1184. {
  1185. assertex(!idx);
  1186. input = _in;
  1187. }
  1188. virtual IRoxieInput *queryOutput(unsigned idx)
  1189. {
  1190. if (idx == (unsigned) -1)
  1191. idx = 0;
  1192. return idx ? NULL : this;
  1193. }
  1194. virtual IOutputMetaData *queryOutputMeta() const
  1195. {
  1196. return meta.queryOriginal();
  1197. }
  1198. virtual unsigned queryId() const
  1199. {
  1200. return activityId;
  1201. }
  1202. virtual unsigned querySubgraphId() const
  1203. {
  1204. return factory->querySubgraphId();
  1205. }
  1206. virtual void checkAbort()
  1207. {
  1208. ctx->checkAbort();
  1209. }
  1210. IException *makeWrappedException(IException *e)
  1211. {
  1212. StringBuffer msg;
  1213. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1214. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1215. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1216. return e;
  1217. else
  1218. return new CWrappedException(e, activityKind, activityId);
  1219. }
  1220. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1221. {
  1222. }
  1223. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1224. {
  1225. }
  1226. virtual void resetOutputsUsed()
  1227. {
  1228. }
  1229. virtual void noteOutputUsed()
  1230. {
  1231. }
  1232. virtual IRoxieServerSideCache *queryServerSideCache() const
  1233. {
  1234. return factory->queryServerSideCache();
  1235. }
  1236. virtual const IRoxieServerActivityFactory *queryFactory() const
  1237. {
  1238. return factory;
  1239. }
  1240. inline ThorActivityKind getKind() const
  1241. {
  1242. return factory->getKind();
  1243. }
  1244. inline bool isSink() const
  1245. {
  1246. return (factory != NULL) && factory->isSink();
  1247. }
  1248. };
  1249. //=====================================================================================================
  1250. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1251. {
  1252. protected:
  1253. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1254. bool prefiltered;
  1255. bool eof;
  1256. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1257. {
  1258. prefiltered = !any;
  1259. eof = prefiltered;
  1260. if (!prefiltered)
  1261. input->start(parentExtractSize, parentExtract, false);
  1262. else
  1263. {
  1264. if (traceStartStop)
  1265. CTXLOG("lateStart activity stopping input early as prefiltered");
  1266. input->stop(false);
  1267. }
  1268. }
  1269. public:
  1270. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1271. : CRoxieServerActivity(_factory, _probeManager)
  1272. {
  1273. input = NULL;
  1274. prefiltered = false;
  1275. eof = false;
  1276. }
  1277. virtual void stop(bool aborting)
  1278. {
  1279. if (!prefiltered)
  1280. {
  1281. input->stop(aborting);
  1282. }
  1283. else if (traceStartStop)
  1284. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1285. CRoxieServerActivity::stop(aborting);
  1286. }
  1287. virtual IRoxieInput *queryInput(unsigned idx) const
  1288. {
  1289. if (idx==0)
  1290. return input;
  1291. else
  1292. return NULL;
  1293. }
  1294. virtual void reset()
  1295. {
  1296. CRoxieServerActivity::reset();
  1297. input->reset();
  1298. prefiltered = false;
  1299. }
  1300. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1301. {
  1302. assertex(!idx);
  1303. input = _in;
  1304. }
  1305. };
  1306. //=====================================================================================================
  1307. atomic_t nextInstanceId;
  1308. extern unsigned getNextInstanceId()
  1309. {
  1310. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1311. }
  1312. atomic_t nextRuid;
  1313. ruid_t getNextRuid()
  1314. {
  1315. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1316. while (ret < RUID_FIRST)
  1317. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1318. return ret;
  1319. }
  1320. void setStartRuid(unsigned restarts)
  1321. {
  1322. atomic_set(&nextRuid, restarts * 0x10000);
  1323. atomic_set(&nextInstanceId, restarts * 10000);
  1324. }
  1325. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1326. class LimitSkipException : public CInterface, public IException
  1327. {
  1328. int code;
  1329. public:
  1330. LimitSkipException(int _code) { code = _code; }
  1331. IMPLEMENT_IINTERFACE;
  1332. virtual int errorCode() const { return code; }
  1333. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1334. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1335. };
  1336. IException *makeLimitSkipException(bool isKeyed)
  1337. {
  1338. // We need to make sure what we throw is IException not something derived from it....
  1339. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1340. }
  1341. //=================================================================================
  1342. interface IRecordPullerCallback : extends IExceptionHandler
  1343. {
  1344. virtual void processRow(const void *row) = 0;
  1345. virtual void processEOG() = 0;
  1346. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1347. virtual void processDone() = 0;
  1348. };
  1349. class RecordPullerThread : public RestartableThread
  1350. {
  1351. protected:
  1352. IRoxieInput *input;
  1353. IRecordPullerCallback *helper;
  1354. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1355. bool groupAtOnce, eof, eog;
  1356. CriticalSection crit;
  1357. public:
  1358. RecordPullerThread(bool _groupAtOnce)
  1359. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1360. {
  1361. input = NULL;
  1362. helper = NULL;
  1363. eof = eog = FALSE;
  1364. }
  1365. inline unsigned __int64 queryTotalCycles() const
  1366. {
  1367. return input->queryTotalCycles();
  1368. }
  1369. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1370. {
  1371. helper = _helper;
  1372. input = _input;
  1373. }
  1374. IRoxieInput *queryInput() const
  1375. {
  1376. return input;
  1377. }
  1378. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1379. {
  1380. eof = false;
  1381. eog = false;
  1382. input->start(parentExtractSize, parentExtract, paused);
  1383. try
  1384. {
  1385. if (preload && !paused)
  1386. {
  1387. if (traceLevel > 4)
  1388. DBGLOG("Preload fetching first %d records", preload);
  1389. if (groupAtOnce)
  1390. pullGroups(preload);
  1391. else
  1392. pullRecords(preload);
  1393. }
  1394. if (eof)
  1395. {
  1396. if (traceLevel > 4)
  1397. DBGLOG("No need to start puller after preload");
  1398. helper->processDone();
  1399. }
  1400. else
  1401. {
  1402. if (!noThread)
  1403. {
  1404. StringBuffer logPrefix("[");
  1405. if (ctx) ctx->getLogPrefix(logPrefix);
  1406. logPrefix.append("] ");
  1407. RestartableThread::start(logPrefix);
  1408. started.wait();
  1409. }
  1410. }
  1411. }
  1412. catch (IException *e)
  1413. {
  1414. helper->fireException(e);
  1415. }
  1416. catch (...)
  1417. {
  1418. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1419. }
  1420. }
  1421. void stop(bool aborting)
  1422. {
  1423. if (traceStartStop)
  1424. DBGLOG("RecordPullerThread::stop");
  1425. {
  1426. 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.
  1427. input->stop(aborting);
  1428. }
  1429. RestartableThread::join();
  1430. }
  1431. void reset()
  1432. {
  1433. input->reset();
  1434. }
  1435. virtual int run()
  1436. {
  1437. started.signal();
  1438. try
  1439. {
  1440. if (groupAtOnce)
  1441. pullGroups((unsigned) -1);
  1442. else
  1443. pullRecords((unsigned) -1);
  1444. helper->processDone();
  1445. }
  1446. catch (IException *e)
  1447. {
  1448. helper->fireException(e);
  1449. }
  1450. catch (...)
  1451. {
  1452. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1453. }
  1454. return 0;
  1455. }
  1456. void done()
  1457. {
  1458. helper->processDone();
  1459. }
  1460. bool pullRecords(unsigned preload)
  1461. {
  1462. if (eof)
  1463. return false;
  1464. while (preload)
  1465. {
  1466. const void * row;
  1467. {
  1468. CriticalBlock c(crit); // See comments in stop for why this is needed
  1469. row = input->nextInGroup();
  1470. }
  1471. if (row)
  1472. {
  1473. eog = false;
  1474. helper->processRow(row);
  1475. }
  1476. else if (!eog)
  1477. {
  1478. helper->processEOG();
  1479. eog = true;
  1480. }
  1481. else
  1482. {
  1483. eof = true;
  1484. return false;
  1485. }
  1486. if (preload != (unsigned) -1)
  1487. preload--;
  1488. }
  1489. return true;
  1490. }
  1491. void pullGroups(unsigned preload)
  1492. {
  1493. ConstPointerArray thisGroup;
  1494. unsigned rowsDone = 0;
  1495. while (preload && !eof)
  1496. {
  1497. const void *row;
  1498. {
  1499. CriticalBlock c(crit);
  1500. row = input->nextInGroup();
  1501. }
  1502. if (row)
  1503. {
  1504. thisGroup.append(row);
  1505. rowsDone++;
  1506. }
  1507. else if (thisGroup.length())
  1508. {
  1509. helper->processGroup(thisGroup);
  1510. thisGroup.kill();
  1511. if (preload != (unsigned) -1)
  1512. {
  1513. if (preload > rowsDone)
  1514. preload -= rowsDone;
  1515. else
  1516. break;
  1517. }
  1518. rowsDone = 0;
  1519. }
  1520. else
  1521. {
  1522. eof = true;
  1523. break;
  1524. }
  1525. }
  1526. }
  1527. };
  1528. //=================================================================================
  1529. #define READAHEAD_SIZE 1000
  1530. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1531. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1532. {
  1533. QueueOf<const void, true> buffer;
  1534. InterruptableSemaphore ready;
  1535. InterruptableSemaphore space;
  1536. CriticalSection crit;
  1537. bool eof;
  1538. bool disabled;
  1539. RecordPullerThread puller;
  1540. unsigned preload;
  1541. cycle_t totalCycles;
  1542. IRoxieSlaveContext *ctx;
  1543. bool timeActivities;
  1544. public:
  1545. IMPLEMENT_IINTERFACE;
  1546. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1547. {
  1548. eof = false;
  1549. disabled = false;
  1550. ctx = NULL;
  1551. totalCycles = 0;
  1552. timeActivities = defaultTimeActivities;
  1553. }
  1554. void onCreate(IRoxieSlaveContext *_ctx)
  1555. {
  1556. ctx = _ctx;
  1557. disabled = (ctx->queryDebugContext() != NULL);
  1558. if (ctx)
  1559. timeActivities = ctx->queryOptions().timeActivities;
  1560. }
  1561. virtual IRoxieServerActivity *queryActivity()
  1562. {
  1563. return puller.queryInput()->queryActivity();
  1564. }
  1565. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1566. {
  1567. return puller.queryInput()->queryIndexReadActivity();
  1568. }
  1569. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1570. {
  1571. eof = false;
  1572. if (disabled)
  1573. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1574. else
  1575. {
  1576. space.reinit(READAHEAD_SIZE);
  1577. ready.reinit();
  1578. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1579. }
  1580. }
  1581. virtual void stop(bool aborting)
  1582. {
  1583. if (disabled)
  1584. puller.queryInput()->stop(aborting);
  1585. else
  1586. {
  1587. space.interrupt();
  1588. ready.interrupt();
  1589. puller.stop(aborting);
  1590. }
  1591. }
  1592. virtual void reset()
  1593. {
  1594. if (disabled)
  1595. puller.queryInput()->reset();
  1596. else
  1597. {
  1598. puller.reset();
  1599. ForEachItemIn(idx1, buffer)
  1600. ReleaseRoxieRow(buffer.item(idx1));
  1601. buffer.clear();
  1602. }
  1603. }
  1604. virtual void resetEOF()
  1605. {
  1606. throwUnexpected();
  1607. }
  1608. virtual IOutputMetaData * queryOutputMeta() const
  1609. {
  1610. return puller.queryInput()->queryOutputMeta();
  1611. }
  1612. virtual void checkAbort()
  1613. {
  1614. puller.queryInput()->checkAbort();
  1615. }
  1616. void setInput(unsigned idx, IRoxieInput *_in)
  1617. {
  1618. assertex(!idx);
  1619. puller.setInput(this, _in);
  1620. }
  1621. virtual unsigned __int64 queryTotalCycles() const
  1622. {
  1623. return totalCycles;
  1624. }
  1625. virtual unsigned __int64 queryLocalCycles() const
  1626. {
  1627. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1628. if (ret < 0) ret = 0;
  1629. return ret;
  1630. }
  1631. virtual IRoxieInput *queryInput(unsigned idx) const
  1632. {
  1633. return puller.queryInput()->queryInput(idx);
  1634. }
  1635. virtual const void * nextInGroup()
  1636. {
  1637. SimpleActivityTimer t(totalCycles, timeActivities);
  1638. if (disabled)
  1639. return puller.queryInput()->nextInGroup();
  1640. else
  1641. {
  1642. loop
  1643. {
  1644. {
  1645. CriticalBlock b(crit);
  1646. if (eof && !buffer.ordinality())
  1647. return NULL; // eof
  1648. }
  1649. ready.wait();
  1650. const void *ret;
  1651. {
  1652. CriticalBlock b(crit);
  1653. ret = buffer.dequeue();
  1654. }
  1655. space.signal();
  1656. return ret;
  1657. }
  1658. }
  1659. }
  1660. virtual unsigned queryId() const { throwUnexpected(); }
  1661. virtual bool fireException(IException *e)
  1662. {
  1663. // called from puller thread on failure
  1664. ready.interrupt(LINK(e));
  1665. space.interrupt(e);
  1666. return true;
  1667. }
  1668. virtual void processRow(const void *row)
  1669. {
  1670. {
  1671. CriticalBlock b(crit);
  1672. buffer.enqueue(row);
  1673. }
  1674. ready.signal();
  1675. space.wait();
  1676. }
  1677. virtual void processGroup(const ConstPointerArray &rows)
  1678. {
  1679. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1680. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1681. // if group was larger than max(space)
  1682. {
  1683. CriticalBlock b(crit);
  1684. ForEachItemIn(idx, rows)
  1685. buffer.enqueue(rows.item(idx));
  1686. buffer.enqueue(NULL);
  1687. }
  1688. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1689. {
  1690. ready.signal();
  1691. space.wait();
  1692. }
  1693. }
  1694. virtual void processEOG()
  1695. {
  1696. // Used when output is not grouped - just ignore
  1697. }
  1698. virtual void processDone()
  1699. {
  1700. CriticalBlock b(crit);
  1701. eof = true;
  1702. ready.signal();
  1703. }
  1704. };
  1705. //=================================================================================
  1706. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1707. {
  1708. protected:
  1709. IRoxieInput *input1;
  1710. Owned<CRoxieServerReadAheadInput> puller;
  1711. public:
  1712. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1713. : CRoxieServerActivity(_factory, _probeManager)
  1714. {
  1715. input1 = NULL;
  1716. }
  1717. ~CRoxieServerTwoInputActivity()
  1718. {
  1719. }
  1720. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1721. {
  1722. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1723. input1->start(parentExtractSize, parentExtract, paused);
  1724. }
  1725. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1726. {
  1727. if (puller)
  1728. puller->onCreate(_ctx);
  1729. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1730. }
  1731. virtual void stop(bool aborting)
  1732. {
  1733. input1->stop(aborting);
  1734. CRoxieServerActivity::stop(aborting);
  1735. }
  1736. virtual unsigned __int64 queryLocalCycles() const
  1737. {
  1738. __int64 ret;
  1739. __int64 inputCycles = input->queryTotalCycles();
  1740. __int64 input1Cycles = input1->queryTotalCycles();
  1741. if (puller)
  1742. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1743. else
  1744. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  1745. if (ret < 0)
  1746. ret = 0;
  1747. return ret;
  1748. }
  1749. virtual IRoxieInput *queryInput(unsigned idx) const
  1750. {
  1751. switch (idx)
  1752. {
  1753. case 0:
  1754. return input;
  1755. case 1:
  1756. return input1;
  1757. default:
  1758. return NULL;
  1759. }
  1760. }
  1761. virtual void reset()
  1762. {
  1763. CRoxieServerActivity::reset();
  1764. if (input1)
  1765. input1->reset();
  1766. }
  1767. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1768. {
  1769. switch(idx)
  1770. {
  1771. case 0:
  1772. input = _in;
  1773. break;
  1774. case 1:
  1775. input1 = _in;
  1776. break;
  1777. default:
  1778. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1779. }
  1780. }
  1781. };
  1782. //=================================================================================
  1783. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1784. {
  1785. protected:
  1786. unsigned numInputs;
  1787. IRoxieInput **inputArray;
  1788. public:
  1789. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1790. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1791. {
  1792. inputArray = new IRoxieInput*[numInputs];
  1793. for (unsigned i = 0; i < numInputs; i++)
  1794. inputArray[i] = NULL;
  1795. }
  1796. ~CRoxieServerMultiInputBaseActivity()
  1797. {
  1798. delete [] inputArray;
  1799. }
  1800. virtual unsigned __int64 queryLocalCycles() const
  1801. {
  1802. __int64 localCycles = totalCycles.totalCycles;
  1803. for (unsigned i = 0; i < numInputs; i++)
  1804. localCycles -= inputArray[i]->queryTotalCycles();
  1805. if (localCycles < 0)
  1806. localCycles = 0;
  1807. return localCycles;
  1808. }
  1809. virtual IRoxieInput *queryInput(unsigned idx) const
  1810. {
  1811. if (idx < numInputs)
  1812. return inputArray[idx];
  1813. else
  1814. return NULL;
  1815. }
  1816. virtual void reset()
  1817. {
  1818. for (unsigned i = 0; i < numInputs; i++)
  1819. inputArray[i]->reset();
  1820. CRoxieServerActivity::reset();
  1821. }
  1822. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1823. {
  1824. inputArray[idx] = _in;
  1825. }
  1826. };
  1827. //=================================================================================
  1828. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1829. {
  1830. public:
  1831. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1832. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1833. {
  1834. }
  1835. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1836. {
  1837. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1838. for (unsigned i = 0; i < numInputs; i++)
  1839. {
  1840. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1841. }
  1842. }
  1843. virtual void stop(bool aborting)
  1844. {
  1845. for (unsigned i = 0; i < numInputs; i++)
  1846. {
  1847. inputArray[i]->stop(aborting);
  1848. }
  1849. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1850. }
  1851. };
  1852. //=====================================================================================================
  1853. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1854. {
  1855. protected:
  1856. unsigned numOutputs;
  1857. bool executed;
  1858. bool *stopped;
  1859. CriticalSection ecrit;
  1860. Owned<IException> exception;
  1861. public:
  1862. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  1863. : CRoxieServerActivity(_factory, _probeManager), numOutputs(_numOutputs)
  1864. {
  1865. executed = false;
  1866. stopped = new bool[numOutputs];
  1867. for (unsigned s = 0; s < numOutputs; s++)
  1868. stopped[s] = false;
  1869. }
  1870. ~CRoxieServerInternalSinkActivity()
  1871. {
  1872. delete [] stopped;
  1873. }
  1874. virtual void reset()
  1875. {
  1876. for (unsigned s = 0; s < numOutputs; s++)
  1877. stopped[s] = false;
  1878. executed = false;
  1879. exception.clear();
  1880. CRoxieServerActivity::reset();
  1881. }
  1882. virtual IRoxieInput *queryOutput(unsigned idx)
  1883. {
  1884. return NULL;
  1885. }
  1886. virtual void stopSink(unsigned outputIdx)
  1887. {
  1888. if (!stopped[outputIdx])
  1889. {
  1890. stopped[outputIdx] = true;
  1891. for (unsigned s = 0; s < numOutputs; s++)
  1892. if (!stopped[s])
  1893. return;
  1894. stop(false); // all outputs stopped - stop parent.
  1895. }
  1896. }
  1897. virtual const void *nextInGroup()
  1898. {
  1899. throwUnexpected(); // I am nobody's input
  1900. }
  1901. virtual void onExecute() = 0;
  1902. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1903. {
  1904. CriticalBlock b(ecrit);
  1905. if (exception)
  1906. throw exception.getLink();
  1907. if (!executed)
  1908. {
  1909. try
  1910. {
  1911. start(parentExtractSize, parentExtract, false);
  1912. {
  1913. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  1914. onExecute();
  1915. }
  1916. stop(false);
  1917. executed = true;
  1918. }
  1919. catch (IException *E)
  1920. {
  1921. exception.set(E); // (or maybe makeWrappedException?)
  1922. stop(true);
  1923. throw;
  1924. }
  1925. catch (...)
  1926. {
  1927. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1928. stop(true);
  1929. throw;
  1930. }
  1931. }
  1932. }
  1933. };
  1934. //=================================================================================
  1935. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1936. {
  1937. protected:
  1938. Owned<IMessageResult> result;
  1939. Owned<IRoxieQueryPacket> packet;
  1940. Linked<IRoxieServerQueryPacket> continuation;
  1941. unsigned hash;
  1942. unsigned seq;
  1943. unsigned lastDebugSequence;
  1944. Owned<IRoxieQueryPacket> lastDebugResponse;
  1945. ILRUChain *prev;
  1946. ILRUChain *next;
  1947. bool delayed;
  1948. public:
  1949. IMPLEMENT_IINTERFACE;
  1950. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1951. {
  1952. hash = 0;
  1953. seq = 0;
  1954. prev = NULL;
  1955. next = NULL;
  1956. delayed = false;
  1957. lastDebugSequence = 0;
  1958. }
  1959. virtual IRoxieQueryPacket *queryPacket() const
  1960. {
  1961. return packet;
  1962. }
  1963. virtual bool isContinuation() const
  1964. {
  1965. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1966. }
  1967. virtual bool isDelayed() const
  1968. {
  1969. return delayed;
  1970. }
  1971. virtual bool isEnd() const
  1972. {
  1973. return false;
  1974. }
  1975. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1976. {
  1977. return false;
  1978. }
  1979. virtual bool hasResult() const
  1980. {
  1981. return result != NULL;
  1982. }
  1983. virtual bool hasContinuation() const
  1984. {
  1985. return continuation != NULL;
  1986. }
  1987. virtual void setDelayed(bool _delayed)
  1988. {
  1989. delayed = _delayed;
  1990. }
  1991. virtual void setPacket(IRoxieQueryPacket *_packet)
  1992. {
  1993. packet.setown(_packet);
  1994. }
  1995. virtual void setSequence(unsigned _seq)
  1996. {
  1997. assertex(!IsShared());
  1998. seq = _seq;
  1999. }
  2000. virtual unsigned getSequence() const
  2001. {
  2002. return seq;
  2003. }
  2004. IMessageResult *getResult()
  2005. {
  2006. return result.getLink();
  2007. }
  2008. IMessageResult *queryResult()
  2009. {
  2010. return result;
  2011. }
  2012. void setResult(IMessageResult *r)
  2013. {
  2014. result.setown(r);
  2015. }
  2016. IRoxieServerQueryPacket *queryContinuation()
  2017. {
  2018. return continuation;
  2019. }
  2020. void setContinuation(IRoxieServerQueryPacket *c)
  2021. {
  2022. continuation.setown(c);
  2023. }
  2024. virtual unsigned queryHash() const
  2025. {
  2026. return hash;
  2027. }
  2028. virtual void setHash(unsigned _hash)
  2029. {
  2030. hash = _hash;
  2031. }
  2032. virtual ILRUChain *queryPrev() const { return prev; }
  2033. virtual ILRUChain *queryNext() const { return next; }
  2034. virtual void setPrev(ILRUChain *p) { prev = p; }
  2035. virtual void setNext(ILRUChain *n) { next = n; }
  2036. virtual void unchain()
  2037. {
  2038. if (prev && next)
  2039. {
  2040. prev->setNext(next);
  2041. next->setPrev(prev);
  2042. }
  2043. next = NULL;
  2044. prev = NULL;
  2045. }
  2046. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2047. {
  2048. if (sequence == lastDebugSequence)
  2049. return lastDebugResponse.getLink();
  2050. else if (sequence > lastDebugSequence)
  2051. {
  2052. lastDebugResponse.clear();
  2053. return NULL;
  2054. }
  2055. else
  2056. throwUnexpected();
  2057. }
  2058. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2059. {
  2060. lastDebugSequence = sequence;
  2061. lastDebugResponse.set(response);
  2062. }
  2063. };
  2064. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2065. {
  2066. public:
  2067. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2068. {
  2069. }
  2070. virtual bool isEnd() const
  2071. {
  2072. return true;
  2073. }
  2074. };
  2075. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2076. {
  2077. unsigned __int64 rowLimit;
  2078. unsigned __int64 keyedLimit;
  2079. unsigned __int64 stopAfter;
  2080. public:
  2081. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2082. {
  2083. rowLimit = _rowLimit;
  2084. keyedLimit = _keyedLimit;
  2085. stopAfter = _stopAfter;
  2086. }
  2087. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2088. {
  2089. _rowLimit = rowLimit;
  2090. _keyedLimit = keyedLimit;
  2091. _stopAfter = stopAfter;
  2092. return true;
  2093. }
  2094. };
  2095. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2096. {
  2097. protected:
  2098. unsigned cacheTableSize;
  2099. unsigned cacheTableSpace;
  2100. IRoxieServerQueryPacket **cacheTable;
  2101. mutable ILRUChain *prev;
  2102. mutable ILRUChain *next;
  2103. mutable CriticalSection crit;
  2104. virtual ILRUChain *queryPrev() const { return prev; }
  2105. virtual ILRUChain *queryNext() const { return next; }
  2106. virtual void setPrev(ILRUChain *p) { prev = p; }
  2107. virtual void setNext(ILRUChain *n) { next = n; }
  2108. virtual void unchain()
  2109. {
  2110. prev->setNext(next);
  2111. next->setPrev(prev);
  2112. next = NULL;
  2113. prev = NULL;
  2114. }
  2115. void moveToHead(IRoxieServerQueryPacket *mru)
  2116. {
  2117. mru->unchain();
  2118. mru->setNext(next);
  2119. next->setPrev(mru);
  2120. mru->setPrev(this);
  2121. next = mru;
  2122. }
  2123. IRoxieServerQueryPacket *removeLRU()
  2124. {
  2125. if (next==this)
  2126. assertex(next != this);
  2127. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2128. goer->unchain(); // NOTE - this will modify the value of next
  2129. return goer;
  2130. }
  2131. void removeEntry(IRoxieServerQueryPacket *goer)
  2132. {
  2133. unsigned v = goer->queryHash() % cacheTableSize;
  2134. loop
  2135. {
  2136. IRoxieServerQueryPacket *found = cacheTable[v];
  2137. assertex(found);
  2138. if (found == goer)
  2139. {
  2140. cacheTable[v] = NULL;
  2141. unsigned vn = v;
  2142. loop
  2143. {
  2144. vn++;
  2145. if (vn==cacheTableSize) vn = 0;
  2146. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2147. if (!found2)
  2148. break;
  2149. unsigned vm = found2->queryHash() % cacheTableSize;
  2150. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2151. {
  2152. cacheTable[v] = found2;
  2153. v = vn;
  2154. cacheTable[v] = NULL;
  2155. }
  2156. }
  2157. cacheTableSpace++;
  2158. break;
  2159. }
  2160. v++;
  2161. if (v==cacheTableSize)
  2162. v = 0;
  2163. }
  2164. goer->Release();
  2165. }
  2166. public:
  2167. CRoxieServerSideCache(unsigned _cacheSize)
  2168. {
  2169. cacheTableSize = (_cacheSize*4)/3;
  2170. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2171. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2172. cacheTableSpace = _cacheSize;
  2173. prev = this;
  2174. next = this;
  2175. }
  2176. ~CRoxieServerSideCache()
  2177. {
  2178. for (unsigned i = 0; i < cacheTableSize; i++)
  2179. {
  2180. ::Release(cacheTable[i]);
  2181. }
  2182. delete [] cacheTable;
  2183. }
  2184. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2185. {
  2186. unsigned hash = p->hash();
  2187. unsigned et = hash % cacheTableSize;
  2188. if (traceServerSideCache)
  2189. {
  2190. StringBuffer s;
  2191. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2192. }
  2193. CriticalBlock b(crit);
  2194. loop
  2195. {
  2196. IRoxieServerQueryPacket *found = cacheTable[et];
  2197. if (!found)
  2198. return NULL;
  2199. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2200. {
  2201. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2202. if (traceServerSideCache)
  2203. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2204. logctx.noteStatistic(StNumServerCacheHits, 1);
  2205. return NULL;
  2206. // 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....
  2207. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2208. //ret->setResult(found->getResult());
  2209. //return ret;
  2210. }
  2211. et++;
  2212. if (et == cacheTableSize)
  2213. et = 0;
  2214. }
  2215. }
  2216. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2217. {
  2218. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2219. {
  2220. unsigned hash = out->queryPacket()->hash();
  2221. out->setHash(hash);
  2222. unsigned et = hash % cacheTableSize;
  2223. if (traceServerSideCache)
  2224. {
  2225. StringBuffer s;
  2226. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2227. }
  2228. CriticalBlock b(crit);
  2229. loop
  2230. {
  2231. IRoxieServerQueryPacket *found = cacheTable[et];
  2232. if (!found)
  2233. {
  2234. if (cacheTableSpace)
  2235. {
  2236. out->setResult(LINK(in));
  2237. cacheTable[et] = LINK(out);
  2238. cacheTableSpace--;
  2239. moveToHead(out);
  2240. break;
  2241. }
  2242. else
  2243. {
  2244. IRoxieServerQueryPacket *goer = removeLRU();
  2245. removeEntry(goer);
  2246. et = hash % cacheTableSize;
  2247. continue;
  2248. }
  2249. }
  2250. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2251. {
  2252. moveToHead(found);
  2253. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2254. // multiple copies of a slave query are in-flight at once.
  2255. }
  2256. et++;
  2257. if (et == cacheTableSize)
  2258. et = 0;
  2259. }
  2260. }
  2261. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2262. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2263. }
  2264. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2265. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2266. // more than make up for it
  2267. };
  2268. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2269. {
  2270. ConstPointerArray &data;
  2271. Linked<IMessageResult> result;
  2272. public:
  2273. IMPLEMENT_IINTERFACE;
  2274. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2275. : data(_data), result(_result)
  2276. {
  2277. }
  2278. virtual bool atEOF() const
  2279. {
  2280. return data.length()==0;
  2281. }
  2282. virtual bool isSerialized() const
  2283. {
  2284. return false;
  2285. }
  2286. virtual const void * getNext(int length)
  2287. {
  2288. if (!data.length())
  2289. return NULL;
  2290. const void *ret = data.item(0);
  2291. data.remove(0);
  2292. return ret;
  2293. }
  2294. };
  2295. // MORE - should possibly move more over to the lazy version used in indexread?
  2296. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2297. {
  2298. ConstPointerArray data;
  2299. IRowManager &rowManager;
  2300. bool variableSize;
  2301. public:
  2302. IMPLEMENT_IINTERFACE;
  2303. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2304. {
  2305. }
  2306. ~CRowArrayMessageResult()
  2307. {
  2308. ReleaseRoxieRowSet(data);
  2309. }
  2310. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2311. {
  2312. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2313. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2314. }
  2315. virtual const void *getMessageHeader(unsigned &length) const
  2316. {
  2317. throwUnexpected(); // should never get called - I don't have a header available
  2318. length = 0;
  2319. return NULL;
  2320. }
  2321. virtual const void *getMessageMetadata(unsigned &length) const
  2322. {
  2323. length = 0;
  2324. return NULL;
  2325. }
  2326. virtual void discard() const
  2327. {
  2328. throwUnexpected();
  2329. }
  2330. void append(const void *row)
  2331. {
  2332. data.append(row);
  2333. }
  2334. };
  2335. void throwRemoteException(IMessageUnpackCursor *extra)
  2336. {
  2337. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2338. if (rowlen)
  2339. {
  2340. char *xml = (char *) extra->getNext(*rowlen);
  2341. ReleaseRoxieRow(rowlen);
  2342. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2343. ReleaseRoxieRow(xml);
  2344. unsigned code = p->getPropInt("Code", 0);
  2345. const char *msg = p->queryProp("Message");
  2346. if (!msg)
  2347. msg = xml;
  2348. throw MakeStringException(code, "%s", msg);
  2349. }
  2350. throwUnexpected();
  2351. }
  2352. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2353. {
  2354. friend class CRemoteResultMerger;
  2355. class CRemoteResultMerger
  2356. {
  2357. class HeapEntry : public CInterface
  2358. {
  2359. private:
  2360. CRemoteResultAdaptor &adaptor;
  2361. IMessageUnpackCursor *cursor;
  2362. public:
  2363. const void *current;
  2364. bool isLast;
  2365. bool lastIsComplete;
  2366. IRoxieServerQueryPacket *packet;
  2367. unsigned seq;
  2368. public:
  2369. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2370. {
  2371. cursor = _cursor;
  2372. lastIsComplete = _lastIsComplete;
  2373. return next();
  2374. }
  2375. public:
  2376. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2377. {
  2378. cursor = NULL;
  2379. current = NULL;
  2380. isLast = false;
  2381. lastIsComplete = true;
  2382. }
  2383. ~HeapEntry()
  2384. {
  2385. ::Release(packet);
  2386. ::Release(cursor);
  2387. ReleaseRoxieRow(current);
  2388. }
  2389. bool isCompleteMatch() const
  2390. {
  2391. if (!isLast || lastIsComplete)
  2392. return true;
  2393. else
  2394. return false;
  2395. }
  2396. const void *next()
  2397. {
  2398. if (cursor)
  2399. {
  2400. ReleaseClearRoxieRow(current);
  2401. current = adaptor.getRow(cursor);
  2402. isLast = cursor->atEOF();
  2403. if (!current)
  2404. {
  2405. cursor->Release();
  2406. cursor = NULL;
  2407. }
  2408. }
  2409. return current;
  2410. }
  2411. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2412. {
  2413. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2414. unsigned skipped = 0;
  2415. loop
  2416. {
  2417. int c = compare->docompare(current, seek, numFields);
  2418. //If larger than the seek values, then we may be allowed to return an inexact match,
  2419. //if equal then it is required to be an exact match,
  2420. if (c > 0)
  2421. {
  2422. if (!requireExactMatch || isCompleteMatch())
  2423. break;
  2424. }
  2425. else if ((c == 0) && isCompleteMatch())
  2426. break;
  2427. skipped++;
  2428. if (!next())
  2429. break;
  2430. }
  2431. return skipped;
  2432. }
  2433. };
  2434. CRemoteResultAdaptor &adaptor;
  2435. CIArrayOf<HeapEntry> heapEntries;
  2436. UnsignedArray heap;
  2437. IRowManager *rowManager;
  2438. unsigned numPending;
  2439. unsigned numFields;
  2440. bool endSeen;
  2441. bool remakePending;
  2442. IRangeCompare *compare;
  2443. bool deferredContinuation;
  2444. inline int doCompare(unsigned l, unsigned r)
  2445. {
  2446. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2447. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2448. return ret;
  2449. }
  2450. void makeHeap()
  2451. {
  2452. /* Permute blocks to establish the heap property
  2453. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2454. The children of p must both be greater than or equal to p
  2455. The parent of a child c is given by p = (c-1)/2
  2456. */
  2457. unsigned i;
  2458. unsigned n = heap.length();
  2459. unsigned *s = heap.getArray();
  2460. for (i=1; i<n; i++)
  2461. {
  2462. unsigned r = s[i];
  2463. int c = i; /* child */
  2464. while (c > 0)
  2465. {
  2466. int p = (c-1)/2; /* parent */
  2467. if ( doCompare( s[c], s[p] ) >= 0 )
  2468. break;
  2469. s[c] = s[p];
  2470. s[p] = r;
  2471. c = p;
  2472. }
  2473. }
  2474. remakePending = false;
  2475. }
  2476. void remakeHeap()
  2477. {
  2478. /* The row associated with block[0] will have changed
  2479. This code restores the heap property
  2480. */
  2481. unsigned p = 0; /* parent */
  2482. unsigned n = heap.length();
  2483. unsigned *s = heap.getArray();
  2484. while (1)
  2485. {
  2486. unsigned c = p*2 + 1; /* child */
  2487. if ( c >= n )
  2488. break;
  2489. /* Select smaller child */
  2490. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2491. /* If child is greater or equal than parent then we are done */
  2492. if ( doCompare( s[c], s[p] ) >= 0 )
  2493. break;
  2494. /* Swap parent and child */
  2495. unsigned r = s[c];
  2496. s[c] = s[p];
  2497. s[p] = r;
  2498. /* child becomes parent */
  2499. p = c;
  2500. }
  2501. remakePending = false;
  2502. }
  2503. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2504. {
  2505. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2506. IMessageResult *result = p->queryResult();
  2507. assertex(result);
  2508. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2509. {
  2510. heapEntries.append(h);
  2511. heap.append(heap.ordinality());
  2512. }
  2513. else
  2514. h.Release();
  2515. }
  2516. void removeHeap(unsigned idx)
  2517. {
  2518. heapEntries.remove(idx);
  2519. ForEachItemIn(i, heap)
  2520. {
  2521. unsigned v = heap.item(i);
  2522. assertex(v != idx);
  2523. if (v > idx)
  2524. heap.replace(v-1, i);
  2525. }
  2526. }
  2527. bool isCompleteMatchFlag(IMessageResult *result)
  2528. {
  2529. unsigned metaLen;
  2530. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2531. if (metaLen)
  2532. {
  2533. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2534. if (continuationLen >= sizeof(bool))
  2535. {
  2536. metaInfo += sizeof(unsigned short);
  2537. return *(bool *) metaInfo;
  2538. }
  2539. }
  2540. return true; // if no continuation info, last row was complete.
  2541. }
  2542. public:
  2543. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2544. {
  2545. init(NULL, NULL);
  2546. }
  2547. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2548. {
  2549. if (meta)
  2550. {
  2551. numFields = meta->getNumFields();
  2552. compare = meta->queryCompare();
  2553. }
  2554. else
  2555. {
  2556. numFields = 0;
  2557. compare = NULL;
  2558. }
  2559. rowManager = _rowManager;
  2560. numPending = 0;
  2561. endSeen = false;
  2562. remakePending = false;
  2563. deferredContinuation = false;
  2564. }
  2565. void reset()
  2566. {
  2567. heapEntries.kill();
  2568. heap.kill();
  2569. numPending = 0;
  2570. endSeen = false;
  2571. remakePending = false;
  2572. deferredContinuation = false;
  2573. }
  2574. inline bool noteEndSeen()
  2575. {
  2576. bool hadSeen = endSeen;
  2577. if (!endSeen)
  2578. makeHeap();
  2579. endSeen = true;
  2580. return !hadSeen;
  2581. }
  2582. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2583. {
  2584. if (!p->isContinuation())
  2585. append(p, seq);
  2586. else
  2587. {
  2588. ForEachItemIn(idx, heapEntries)
  2589. {
  2590. HeapEntry &h = heapEntries.item(idx);
  2591. if (h.packet == p)
  2592. {
  2593. IMessageResult *result = p->queryResult();
  2594. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2595. {
  2596. heap.zap(idx);
  2597. removeHeap(idx);
  2598. }
  2599. numPending--;
  2600. if (!numPending)
  2601. makeHeap();
  2602. return;
  2603. }
  2604. }
  2605. }
  2606. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2607. return;
  2608. }
  2609. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2610. {
  2611. HeapEntry &entry = heapEntries.item(idx);
  2612. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2613. if (!entry.current)
  2614. {
  2615. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2616. if (continuation)
  2617. {
  2618. continuation->Link();
  2619. entry.packet->Release();
  2620. entry.packet = continuation;
  2621. if (continuation->hasResult())
  2622. {
  2623. IMessageResult *result = continuation->queryResult();
  2624. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2625. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2626. }
  2627. else
  2628. {
  2629. if (continuation->isDelayed())
  2630. {
  2631. continuation->setDelayed(false);
  2632. MemoryBuffer serializedSkip;
  2633. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2634. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2635. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2636. adaptor.sentsome.signal();
  2637. }
  2638. numPending++;
  2639. }
  2640. }
  2641. else
  2642. {
  2643. heap.zap(idx);
  2644. removeHeap(idx);
  2645. idx--;
  2646. }
  2647. }
  2648. return skipped;
  2649. }
  2650. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2651. {
  2652. // We discard all rows < seekval from all entries in heap
  2653. // If this results in additional slave requests, we return NULL so that we can wait for them
  2654. // If not, we rebuild the heap (if any were skipped) and return the first row
  2655. deferredContinuation = false;
  2656. if (heap.length())
  2657. {
  2658. unsigned skipped = 0;
  2659. unsigned idx = 0;
  2660. while(heapEntries.isItem(idx))
  2661. {
  2662. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2663. idx++;
  2664. }
  2665. if (numPending)
  2666. return NULL; // can't answer yet, need more results from slaves
  2667. else
  2668. {
  2669. if (skipped)
  2670. makeHeap();
  2671. return next(wasCompleteMatch, stepExtra);
  2672. }
  2673. }
  2674. else
  2675. return NULL;
  2676. }
  2677. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2678. {
  2679. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2680. if (continuation)
  2681. {
  2682. if (continuation->isDelayed() && canDefer)
  2683. {
  2684. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2685. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2686. deferredContinuation = true;
  2687. }
  2688. else
  2689. {
  2690. deferredContinuation = false;
  2691. continuation->Link();
  2692. topEntry.packet->Release();
  2693. topEntry.packet = continuation;
  2694. if (continuation->hasResult())
  2695. {
  2696. IMessageResult *result = continuation->queryResult();
  2697. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2698. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2699. }
  2700. else
  2701. {
  2702. if (continuation->isDelayed()) // has the continuation been requested yet?
  2703. {
  2704. continuation->Link();
  2705. topEntry.packet->Release();
  2706. topEntry.packet = continuation;
  2707. continuation->setDelayed(false);
  2708. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2709. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2710. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2711. adaptor.sentsome.signal();
  2712. }
  2713. numPending++; // we are waiting for one that is already in flight
  2714. }
  2715. }
  2716. return true; // next not known yet
  2717. }
  2718. else
  2719. return false;
  2720. }
  2721. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2722. {
  2723. OwnedConstRoxieRow ret;
  2724. if (heap.length())
  2725. {
  2726. if (deferredContinuation)
  2727. {
  2728. unsigned top = heap.item(0);
  2729. HeapEntry &topEntry = heapEntries.item(top);
  2730. doContinuation(topEntry, false);
  2731. return NULL;
  2732. }
  2733. if (remakePending)
  2734. remakeHeap();
  2735. unsigned top = heap.item(0);
  2736. HeapEntry &topEntry = heapEntries.item(top);
  2737. ret.set(topEntry.current);
  2738. wasCompleteMatch = topEntry.isCompleteMatch();
  2739. const void *next = topEntry.next();
  2740. if (!next)
  2741. {
  2742. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2743. {
  2744. unsigned last = heap.popGet();
  2745. if (heap.length())
  2746. heap.replace(last, 0);
  2747. removeHeap(top);
  2748. }
  2749. }
  2750. remakePending = true;
  2751. }
  2752. return ret.getClear();
  2753. }
  2754. bool ready()
  2755. {
  2756. return endSeen && numPending == 0;
  2757. }
  2758. };
  2759. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2760. {
  2761. if (serverSideCache && !debugContext)
  2762. {
  2763. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2764. if (ret)
  2765. {
  2766. p->Release();
  2767. cached = true;
  2768. return ret;
  2769. }
  2770. }
  2771. cached = false;
  2772. return new CRoxieServerQueryPacket(p);
  2773. }
  2774. #ifdef _DEBUG
  2775. void dumpPending()
  2776. {
  2777. CriticalBlock b(pendingCrit);
  2778. ForEachItemIn(idx, pending)
  2779. {
  2780. IRoxieServerQueryPacket &p = pending.item(idx);
  2781. StringBuffer s;
  2782. unsigned __int64 dummy;
  2783. if (p.isEnd())
  2784. s.append("END");
  2785. else if (p.isLimit(dummy, dummy, dummy))
  2786. s.append("LIMIT");
  2787. else
  2788. {
  2789. IRoxieQueryPacket *i = p.queryPacket();
  2790. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2791. if (i)
  2792. {
  2793. RoxiePacketHeader &header = i->queryHeader();
  2794. header.toString(s);
  2795. }
  2796. }
  2797. DBGLOG("Pending %d %s", idx, s.str());
  2798. }
  2799. }
  2800. #endif
  2801. void abortPending()
  2802. {
  2803. CriticalBlock b(pendingCrit);
  2804. ForEachItemIn(idx, pending)
  2805. {
  2806. IRoxieServerQueryPacket &p = pending.item(idx);
  2807. if (!p.hasResult())
  2808. {
  2809. IRoxieQueryPacket *i = p.queryPacket();
  2810. if (i)
  2811. {
  2812. RoxiePacketHeader &header = i->queryHeader();
  2813. ROQ->sendAbort(header, activity.queryLogCtx());
  2814. }
  2815. }
  2816. }
  2817. pending.kill();
  2818. }
  2819. void checkDelayed()
  2820. {
  2821. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2822. {
  2823. bool allDelayed = true;
  2824. CriticalBlock b(pendingCrit);
  2825. unsigned sendIdx = (unsigned) -1;
  2826. ForEachItemIn(idx, pending)
  2827. {
  2828. IRoxieServerQueryPacket &p = pending.item(idx);
  2829. if (p.queryPacket())
  2830. {
  2831. if (p.isDelayed())
  2832. {
  2833. if (sendIdx == (unsigned) -1)
  2834. sendIdx = idx;
  2835. }
  2836. else if (!p.hasResult())
  2837. {
  2838. allDelayed = false;
  2839. break;
  2840. }
  2841. }
  2842. }
  2843. if (allDelayed && sendIdx != (unsigned) -1)
  2844. {
  2845. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2846. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2847. pending.item(sendIdx).setDelayed(false);
  2848. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2849. sentsome.signal();
  2850. }
  2851. }
  2852. else if (deferredStart)
  2853. {
  2854. CriticalBlock b(pendingCrit);
  2855. ForEachItemIn(idx, pending)
  2856. {
  2857. IRoxieServerQueryPacket &p = pending.item(idx);
  2858. if (p.isDelayed())
  2859. {
  2860. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2861. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2862. p.setDelayed(false);
  2863. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2864. sentsome.signal();
  2865. }
  2866. }
  2867. deferredStart = false;
  2868. }
  2869. }
  2870. void retryPending()
  2871. {
  2872. CriticalBlock b(pendingCrit);
  2873. checkDelayed();
  2874. ForEachItemIn(idx, pending)
  2875. {
  2876. IRoxieServerQueryPacket &p = pending.item(idx);
  2877. if (!p.hasResult() && !p.isDelayed())
  2878. {
  2879. IRoxieQueryPacket *i = p.queryPacket();
  2880. if (i)
  2881. {
  2882. if (!i->queryHeader().retry())
  2883. {
  2884. StringBuffer s;
  2885. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2886. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2887. throw E;
  2888. }
  2889. if (!localSlave)
  2890. {
  2891. ROQ->sendPacket(i, activity.queryLogCtx());
  2892. atomic_inc(&retriesSent);
  2893. }
  2894. }
  2895. }
  2896. }
  2897. }
  2898. class ChannelBuffer
  2899. {
  2900. protected:
  2901. unsigned bufferLeft;
  2902. MemoryBuffer buffer;
  2903. char *nextBuf;
  2904. unsigned overflowSequence;
  2905. unsigned channel; // == bonded channel
  2906. bool needsFlush;
  2907. InterruptableSemaphore flowController;
  2908. const CRemoteResultAdaptor &owner;
  2909. CriticalSection crit;
  2910. public:
  2911. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2912. {
  2913. overflowSequence = 0;
  2914. needsFlush = false;
  2915. bufferLeft = 0;
  2916. nextBuf = NULL;
  2917. }
  2918. void init(unsigned minSize)
  2919. {
  2920. assertex(!buffer.length());
  2921. if (minSize < MIN_PAYLOAD_SIZE)
  2922. minSize = MIN_PAYLOAD_SIZE;
  2923. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2924. unsigned bufferSize = headerSize+minSize;
  2925. if (bufferSize < mtu_size)
  2926. bufferSize = mtu_size;
  2927. buffer.reserveTruncate(bufferSize);
  2928. bufferLeft = bufferSize - headerSize;
  2929. assertex(buffer.toByteArray());
  2930. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2931. needsFlush = false;
  2932. }
  2933. inline IRoxieQueryPacket *flush()
  2934. {
  2935. CriticalBlock cb(crit);
  2936. Owned<IRoxieQueryPacket> ret;
  2937. if (needsFlush)
  2938. {
  2939. buffer.setLength(nextBuf - buffer.toByteArray());
  2940. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2941. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2942. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2943. byte * tgt = (byte*)(h+1);
  2944. owner.copyHeader(tgt, channel);
  2945. ret.setown(createRoxiePacket(buffer));
  2946. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2947. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2948. else
  2949. overflowSequence++;
  2950. needsFlush = false;
  2951. bufferLeft = 0;
  2952. if (owner.flowControlled)
  2953. {
  2954. CriticalUnblock cub(crit);
  2955. while (!flowController.wait(1000))
  2956. {
  2957. StringBuffer s;
  2958. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2959. }
  2960. }
  2961. }
  2962. return ret.getClear();
  2963. }
  2964. inline void signal()
  2965. {
  2966. if (owner.flowControlled)
  2967. flowController.signal();
  2968. }
  2969. inline void interrupt(IException *e)
  2970. {
  2971. flowController.interrupt(e);
  2972. }
  2973. inline void *getBuffer(unsigned size)
  2974. {
  2975. CriticalBlock cb(crit);
  2976. if (bufferLeft >= size)
  2977. {
  2978. needsFlush = true;
  2979. void * ret = nextBuf;
  2980. nextBuf += size;
  2981. bufferLeft -= size;
  2982. return ret;
  2983. }
  2984. else if (!needsFlush)
  2985. {
  2986. init(size);
  2987. return getBuffer(size);
  2988. }
  2989. else if (owner.mergeOrder)
  2990. {
  2991. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2992. }
  2993. else
  2994. return NULL; // will force it to flush and start a new packet
  2995. }
  2996. };
  2997. private:
  2998. friend class CRemoteResultMerger;
  2999. bool allread;
  3000. bool contextCached;
  3001. bool preserveOrder;
  3002. InterruptableSemaphore sentsome;
  3003. Owned <IMessageCollator> mc;
  3004. Owned<IMessageUnpackCursor> mu;
  3005. Owned<IMessageResult> mr;
  3006. ChannelBuffer **buffers;
  3007. IHThorArg &helper;
  3008. unsigned __int64 stopAfter;
  3009. unsigned resendSequence;
  3010. IHThorArg *colocalArg;
  3011. IArrayOf<IRoxieServerQueryPacket> pending;
  3012. CriticalSection pendingCrit;
  3013. IRoxieServerSideCache *serverSideCache;
  3014. unsigned sentSequence;
  3015. Owned<IOutputRowDeserializer> deserializer;
  3016. Owned<IEngineRowAllocator> rowAllocator;
  3017. CRemoteResultMerger merger;
  3018. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3019. MemoryBuffer tempRowBuffer;
  3020. Owned<ISerialStream> bufferStream;
  3021. CThorStreamDeserializerSource rowSource;
  3022. protected:
  3023. IRowManager *rowManager;
  3024. IRoxieInput *owner;
  3025. unsigned __int64 rowLimit;
  3026. unsigned __int64 keyedLimit;
  3027. IRoxieServerErrorHandler *errorHandler;
  3028. CachedOutputMetaData meta;
  3029. public:
  3030. ISteppingMeta *mergeOrder;
  3031. IRoxieSlaveContext *ctx;
  3032. IDebuggableContext *debugContext;
  3033. IRoxieServerActivity &activity;
  3034. unsigned parentExtractSize;
  3035. const byte * parentExtract;
  3036. bool flowControlled;
  3037. bool deferredStart;
  3038. MemoryBuffer logInfo;
  3039. MemoryBuffer cachedContext;
  3040. const RemoteActivityId &remoteId;
  3041. ruid_t ruid;
  3042. mutable CriticalSection buffersCrit;
  3043. unsigned processed;
  3044. cycle_t totalCycles;
  3045. bool timeActivities;
  3046. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3047. const void *getRow(IMessageUnpackCursor *mu)
  3048. {
  3049. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3050. return mu->getNext(meta.getFixedSize());
  3051. else
  3052. {
  3053. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3054. if (rowlen)
  3055. {
  3056. RecordLengthType len = *rowlen;
  3057. ReleaseRoxieRow(rowlen);
  3058. const void *slaveRec = mu->getNext(len);
  3059. if (deserializer && mu->isSerialized())
  3060. {
  3061. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3062. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3063. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3064. ReleaseRoxieRow(slaveRec);
  3065. return rowBuilder.finalizeRowClear(outsize);
  3066. }
  3067. else
  3068. return slaveRec;
  3069. }
  3070. else
  3071. return NULL;
  3072. }
  3073. }
  3074. private:
  3075. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3076. {
  3077. CriticalBlock cb(buffersCrit);
  3078. ChannelBuffer *b = buffers[channel];
  3079. if (!b && force)
  3080. {
  3081. if (!contextCached)
  3082. {
  3083. logInfo.clear();
  3084. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3085. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3086. const QueryOptions &options = ctx->queryOptions();
  3087. if (activity.queryLogCtx().isIntercepted())
  3088. loggingFlags |= LOGGING_INTERCEPTED;
  3089. if (options.timeActivities)
  3090. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3091. if (activity.queryLogCtx().isBlind())
  3092. loggingFlags |= LOGGING_BLIND;
  3093. if (options.checkingHeap)
  3094. loggingFlags |= LOGGING_CHECKINGHEAP;
  3095. if (ctx->queryWorkUnit())
  3096. loggingFlags |= LOGGING_WUID;
  3097. if (debugContext)
  3098. {
  3099. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3100. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3101. MemoryBuffer bpInfo;
  3102. debugContext->serialize(bpInfo);
  3103. bpInfo.append((__uint64)(memsize_t) &activity);
  3104. logInfo.append((unsigned short) bpInfo.length());
  3105. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3106. }
  3107. else
  3108. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3109. StringBuffer logPrefix;
  3110. activity.queryLogCtx().getLogPrefix(logPrefix);
  3111. logInfo.append(logPrefix);
  3112. activity.serializeCreateStartContext(cachedContext.clear());
  3113. activity.serializeExtra(cachedContext);
  3114. if (activity.queryVarFileInfo())
  3115. {
  3116. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3117. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3118. }
  3119. contextCached = true;
  3120. }
  3121. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3122. }
  3123. return b;
  3124. }
  3125. void processRow(const void *got)
  3126. {
  3127. processed++;
  3128. if (processed > rowLimit)
  3129. {
  3130. ReleaseRoxieRow(got);
  3131. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3132. throwUnexpected();
  3133. }
  3134. else if (processed > keyedLimit)
  3135. {
  3136. ReleaseRoxieRow(got);
  3137. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3138. throwUnexpected();
  3139. }
  3140. }
  3141. public:
  3142. IMPLEMENT_IINTERFACE;
  3143. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3144. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3145. {
  3146. rowLimit = (unsigned __int64) -1;
  3147. keyedLimit = (unsigned __int64) -1;
  3148. contextCached = false;
  3149. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3150. buffers = new ChannelBuffer*[numChannels+1];
  3151. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3152. parentExtractSize = 0;
  3153. parentExtract = NULL;
  3154. debugContext = NULL;
  3155. owner = NULL;
  3156. mergeOrder = NULL;
  3157. deferredStart = false;
  3158. processed = 0;
  3159. sentSequence = 0;
  3160. resendSequence = 0;
  3161. totalCycles = 0;
  3162. serverSideCache = activity.queryServerSideCache();
  3163. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3164. rowSource.setStream(bufferStream);
  3165. timeActivities = defaultTimeActivities;
  3166. }
  3167. ~CRemoteResultAdaptor()
  3168. {
  3169. if (mc)
  3170. {
  3171. ROQ->queryReceiveManager()->detachCollator(mc);
  3172. mc.clear();
  3173. }
  3174. for (unsigned channel = 0; channel <= numChannels; channel++)
  3175. {
  3176. delete(buffers[channel]);
  3177. }
  3178. delete [] buffers;
  3179. }
  3180. void setMeta(IOutputMetaData *newmeta)
  3181. {
  3182. meta.set(newmeta);
  3183. }
  3184. virtual IRoxieServerActivity *queryActivity()
  3185. {
  3186. return &activity;
  3187. }
  3188. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3189. {
  3190. return NULL;
  3191. }
  3192. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3193. {
  3194. mergeOrder = _mergeOrder;
  3195. deferredStart = true;
  3196. }
  3197. void send(IRoxieQueryPacket *p)
  3198. {
  3199. if (p)
  3200. {
  3201. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3202. assertex(p->queryHeader().uid==ruid);
  3203. // MORE: Maybe we should base the fastlane flag on some other
  3204. // criteria !! (i.e A Roxie server prediction based on the
  3205. // activity type/activity behaviour/expected reply size .. etc).
  3206. //
  3207. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3208. // But this could still cause too many reply packets on the fatlane
  3209. // (higher priority output Q), which may cause the activities on the
  3210. // low priority output Q to not get service on time.
  3211. if ((colocalArg == 0) && // not a child query activity??
  3212. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3213. (p->queryHeader().overflowSequence == 0) &&
  3214. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3215. p->queryHeader().retries |= ROXIE_FASTLANE;
  3216. if (p->queryHeader().channel)
  3217. {
  3218. bool cached = false;
  3219. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3220. if (deferredStart)
  3221. rsqp->setDelayed(true);
  3222. rsqp->setSequence(sentSequence++);
  3223. {
  3224. CriticalBlock b(pendingCrit);
  3225. pending.append(*rsqp);
  3226. }
  3227. if (!deferredStart)
  3228. {
  3229. if (!cached)
  3230. ROQ->sendPacket(p, activity.queryLogCtx());
  3231. sentsome.signal();
  3232. }
  3233. }
  3234. else
  3235. {
  3236. // 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
  3237. // Need to add first, then send
  3238. unsigned i;
  3239. bool allCached = true;
  3240. for (i = 1; i <= numChannels; i++)
  3241. {
  3242. IRoxieQueryPacket *q = p->clonePacket(i);
  3243. bool thisChannelCached;
  3244. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3245. if (!thisChannelCached)
  3246. allCached = false;
  3247. rsqp->setSequence(sentSequence++);
  3248. if (deferredStart)
  3249. {
  3250. rsqp->setDelayed(true);
  3251. }
  3252. {
  3253. CriticalBlock b(pendingCrit);
  3254. pending.append(*rsqp);
  3255. }
  3256. if (!deferredStart)
  3257. sentsome.signal();
  3258. }
  3259. if (!allCached && !deferredStart)
  3260. ROQ->sendPacket(p, activity.queryLogCtx());
  3261. buffers[0]->signal(); // since replies won't come back on that channel...
  3262. p->Release();
  3263. }
  3264. }
  3265. }
  3266. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3267. {
  3268. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3269. size += sizeof(PartNoType);
  3270. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3271. char *buffer = (char *) b->getBuffer(size);
  3272. if (!buffer)
  3273. {
  3274. send(b->flush());
  3275. buffer = (char *) b->getBuffer(size);
  3276. }
  3277. PartNoType sp;
  3278. sp.partNo = partNo;
  3279. sp.fileNo = fileNo;
  3280. memcpy(buffer, &sp, sizeof(sp));
  3281. buffer += sizeof(sp);
  3282. return buffer;
  3283. }
  3284. void injectResult(IMessageResult *result)
  3285. {
  3286. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3287. f->setSequence(sentSequence++);
  3288. f->setResult(result);
  3289. CriticalBlock b(pendingCrit);
  3290. pending.append(*f);
  3291. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3292. }
  3293. void flush()
  3294. {
  3295. for (unsigned channel = 0; channel <= numChannels; channel++)
  3296. {
  3297. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3298. if (b)
  3299. send(b->flush());
  3300. }
  3301. }
  3302. void interruptBuffers(IException *e)
  3303. {
  3304. for (unsigned channel = 0; channel <= numChannels; channel++)
  3305. {
  3306. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3307. if (b)
  3308. b->interrupt(LINK(e));
  3309. }
  3310. }
  3311. void senddone()
  3312. {
  3313. CriticalBlock b(pendingCrit);
  3314. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3315. sentsome.signal();
  3316. }
  3317. bool fireException(IException *e)
  3318. {
  3319. {
  3320. CriticalBlock b(pendingCrit);
  3321. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3322. }
  3323. interruptBuffers(e);
  3324. if (mc)
  3325. mc->interrupt(LINK(e));
  3326. sentsome.interrupt(e);
  3327. return true;
  3328. }
  3329. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3330. {
  3331. owner = _owner;
  3332. errorHandler = _errorHandler;
  3333. ctx = _ctx;
  3334. debugContext = ctx->queryDebugContext();
  3335. colocalArg = _colocalArg;
  3336. if (meta.needsSerializeDisk())
  3337. {
  3338. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3339. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3340. }
  3341. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3342. deferredStart = true;
  3343. if (ctx)
  3344. timeActivities = ctx->queryOptions().timeActivities;
  3345. }
  3346. virtual unsigned queryId() const
  3347. {
  3348. return owner->queryId();
  3349. }
  3350. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3351. {
  3352. #ifdef TRACE_STARTSTOP
  3353. if (traceStartStop)
  3354. activity.queryLogCtx().CTXLOG("RRAonstart");
  3355. #endif
  3356. sentsome.reinit();
  3357. ruid = getNextRuid();
  3358. rowManager = &ctx->queryRowManager();
  3359. if (mergeOrder)
  3360. merger.init(mergeOrder, rowManager);
  3361. if (mc)
  3362. {
  3363. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3364. }
  3365. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3366. allread = false;
  3367. mu.clear();
  3368. contextCached = false;
  3369. processed = 0;
  3370. resendSequence = 0;
  3371. sentSequence = 0;
  3372. for (unsigned channel = 0; channel <= numChannels; channel++)
  3373. {
  3374. delete(buffers[channel]);
  3375. buffers[channel] = NULL;
  3376. }
  3377. flush();
  3378. parentExtractSize = _parentExtractSize;
  3379. parentExtract = _parentExtract;
  3380. }
  3381. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3382. {
  3383. #ifdef TRACE_STARTSTOP
  3384. if (traceStartStop)
  3385. activity.queryLogCtx().CTXLOG("RRAstart");
  3386. #endif
  3387. owner->start(parentExtractSize, parentExtract, paused);
  3388. }
  3389. void checkAbort()
  3390. {
  3391. owner->checkAbort();
  3392. }
  3393. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3394. {
  3395. if (ctx->queryProbeManager())
  3396. {
  3397. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3398. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3399. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3400. }
  3401. {
  3402. CriticalBlock b(pendingCrit);
  3403. if (pending.length())
  3404. {
  3405. #ifdef _DEBUG
  3406. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3407. #endif
  3408. assertex(pending.length()==0);
  3409. }
  3410. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3411. }
  3412. sentsome.signal();
  3413. rowLimit = _rowLimit;
  3414. keyedLimit = _keyedLimit;
  3415. stopAfter = _stopAfter;
  3416. }
  3417. virtual void stop(bool aborting)
  3418. {
  3419. #ifdef TRACE_STARTSTOP
  3420. if (traceStartStop)
  3421. activity.queryLogCtx().CTXLOG("RRAstop");
  3422. #endif
  3423. onStop(aborting);
  3424. owner->stop(aborting);
  3425. }
  3426. void onStop(bool aborting)
  3427. {
  3428. #ifdef TRACE_STARTSTOP
  3429. if (traceStartStop)
  3430. activity.queryLogCtx().CTXLOG("RRAonstop");
  3431. #endif
  3432. abortPending();
  3433. interruptBuffers(NULL);
  3434. sentsome.interrupt();
  3435. if (mc) // May not be set if start() chain threw exception
  3436. mc->interrupt();
  3437. }
  3438. virtual void reset()
  3439. {
  3440. #ifdef TRACE_STARTSTOP
  3441. if (traceStartStop)
  3442. activity.queryLogCtx().CTXLOG("RRAreset");
  3443. #endif
  3444. owner->reset();
  3445. onReset();
  3446. }
  3447. virtual void resetEOF()
  3448. {
  3449. throwUnexpected();
  3450. }
  3451. virtual void onReset()
  3452. {
  3453. #ifdef TRACE_STARTSTOP
  3454. if (traceStartStop)
  3455. activity.queryLogCtx().CTXLOG("RRAonreset");
  3456. #endif
  3457. if (mc)
  3458. ROQ->queryReceiveManager()->detachCollator(mc);
  3459. merger.reset();
  3460. pending.kill();
  3461. if (mc && ctx)
  3462. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3463. mc.clear(); // Or we won't free memory for graphs that get recreated
  3464. mu.clear(); //ditto
  3465. deferredStart = false;
  3466. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3467. }
  3468. virtual IOutputMetaData * queryOutputMeta() const
  3469. {
  3470. return helper.queryOutputMeta();
  3471. }
  3472. virtual unsigned __int64 queryTotalCycles() const
  3473. {
  3474. return totalCycles;
  3475. }
  3476. virtual unsigned __int64 queryLocalCycles() const
  3477. {
  3478. return owner->queryLocalCycles();
  3479. }
  3480. virtual IRoxieInput *queryInput(unsigned idx) const
  3481. {
  3482. return owner->queryInput(idx);
  3483. }
  3484. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3485. {
  3486. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3487. {
  3488. StringBuffer recstr;
  3489. unsigned i;
  3490. for (i = 0; i < seekLen; i++)
  3491. {
  3492. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3493. }
  3494. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3495. }
  3496. assertex(mergeOrder);
  3497. if (deferredStart)
  3498. {
  3499. CriticalBlock b(pendingCrit);
  3500. ForEachItemIn(idx, pending)
  3501. {
  3502. IRoxieServerQueryPacket &p = pending.item(idx);
  3503. if (p.isDelayed())
  3504. {
  3505. p.setDelayed(false);
  3506. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3507. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3508. MemoryBuffer serializedSkip;
  3509. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3510. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3511. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3512. sentsome.signal();
  3513. }
  3514. }
  3515. deferredStart = false;
  3516. }
  3517. SimpleActivityTimer t(totalCycles, timeActivities);
  3518. if (processed==stopAfter)
  3519. return NULL;
  3520. if (allread)
  3521. return NULL;
  3522. loop
  3523. {
  3524. if (merger.ready())
  3525. {
  3526. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3527. if (got)
  3528. {
  3529. processRow(got);
  3530. return got;
  3531. }
  3532. }
  3533. if (!reload()) // MORE - should pass the seek info here...
  3534. return NULL;
  3535. }
  3536. }
  3537. virtual const void *nextInGroup()
  3538. {
  3539. // If we are merging then we need to do a heapsort on all
  3540. SimpleActivityTimer t(totalCycles, timeActivities);
  3541. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3542. {
  3543. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3544. }
  3545. loop
  3546. {
  3547. checkDelayed();
  3548. if (processed==stopAfter)
  3549. return NULL;
  3550. if (allread)
  3551. return NULL;
  3552. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3553. const void *got = NULL;
  3554. if (mergeOrder && merger.ready())
  3555. {
  3556. bool matched = true;
  3557. got = merger.next(matched, dummySmartStepExtra);
  3558. }
  3559. else if (mu)
  3560. got = getRow(mu);
  3561. if (got)
  3562. {
  3563. processRow(got);
  3564. return got;
  3565. }
  3566. if (!reload())
  3567. return NULL;
  3568. }
  3569. }
  3570. bool reload()
  3571. {
  3572. // Wait for something to be returned from a slave....
  3573. mu.clear();
  3574. sentsome.wait();
  3575. // must be at least an endMarker on the queue since sentsome was signalled
  3576. {
  3577. CriticalBlock b(pendingCrit);
  3578. IRoxieServerQueryPacket &top = pending.item(0);
  3579. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3580. {
  3581. pending.remove(0);
  3582. return true;
  3583. }
  3584. else if (top.isEnd())
  3585. {
  3586. pending.remove(0);
  3587. allread = true;
  3588. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3589. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3590. return false;
  3591. }
  3592. else if (mergeOrder)
  3593. {
  3594. unsigned idx = 0;
  3595. bool added = false;
  3596. while (pending.isItem(idx))
  3597. {
  3598. IRoxieServerQueryPacket &item = pending.item(idx);
  3599. if (item.isEnd())
  3600. {
  3601. if (merger.noteEndSeen())
  3602. {
  3603. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3604. added = true;
  3605. }
  3606. break;
  3607. }
  3608. else if (item.hasResult())
  3609. {
  3610. merger.noteResult(&item, item.getSequence());
  3611. pending.remove(idx);
  3612. added = true;
  3613. }
  3614. else if (item.isContinuation())
  3615. idx++;
  3616. else
  3617. break;
  3618. }
  3619. if (added)
  3620. return true;
  3621. }
  3622. else if (top.hasResult())
  3623. {
  3624. mr.setown(pending.item(0).getResult());
  3625. mu.setown(mr->getCursor(rowManager));
  3626. pending.remove(0);
  3627. return true;
  3628. }
  3629. }
  3630. getNextUnpacker();
  3631. return true;
  3632. }
  3633. void getNextUnpacker()
  3634. {
  3635. mu.clear();
  3636. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3637. loop
  3638. {
  3639. checkDelayed();
  3640. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3641. owner->checkAbort();
  3642. bool anyActivity;
  3643. if (ctxTraceLevel > 5)
  3644. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3645. mr.setown(mc->getNextResult(timeout, anyActivity));
  3646. if (ctxTraceLevel > 6)
  3647. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3648. owner->checkAbort();
  3649. if (mr)
  3650. {
  3651. unsigned roxieHeaderLen;
  3652. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3653. #ifdef _DEBUG
  3654. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3655. #endif
  3656. if (ctxTraceLevel > 5)
  3657. {
  3658. StringBuffer s;
  3659. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3660. }
  3661. CriticalBlock b(pendingCrit);
  3662. unsigned idx = 0;
  3663. IRoxieServerQueryPacket *original = NULL;
  3664. IRoxieQueryPacket *op;
  3665. while (pending.isItem(idx))
  3666. {
  3667. original = &pending.item(idx);
  3668. op = original->queryPacket();
  3669. if (op && header.matchPacket(op->queryHeader()))
  3670. break;
  3671. original = NULL;
  3672. idx++;
  3673. }
  3674. if (!original || original->hasResult())
  3675. {
  3676. switch (header.activityId)
  3677. {
  3678. case ROXIE_FILECALLBACK:
  3679. {
  3680. // tell slave to abort
  3681. //if (ctxTraceLevel > 5)
  3682. {
  3683. StringBuffer s;
  3684. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3685. }
  3686. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3687. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3688. if (len)
  3689. {
  3690. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3691. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3692. const char *rowdata = (const char *) row.get();
  3693. // bool isOpt = * (bool *) rowdata;
  3694. // bool isLocal = * (bool *) (rowdata+1);
  3695. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3696. }
  3697. else
  3698. throwUnexpected();
  3699. break;
  3700. }
  3701. // MORE - ROXIE_ALIVE perhaps should go here too
  3702. default:
  3703. if (ctxTraceLevel > 3)
  3704. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3705. mr->discard();
  3706. break;
  3707. }
  3708. mr.clear();
  3709. }
  3710. else
  3711. {
  3712. atomic_inc(&resultsReceived);
  3713. switch (header.activityId)
  3714. {
  3715. case ROXIE_DEBUGCALLBACK:
  3716. {
  3717. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3718. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3719. if (len)
  3720. {
  3721. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3722. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3723. char *rowdata = (char *) row.get();
  3724. if (ctxTraceLevel > 5)
  3725. {
  3726. StringBuffer s;
  3727. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3728. }
  3729. MemoryBuffer slaveInfo;
  3730. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3731. unsigned debugSequence;
  3732. slaveInfo.read(debugSequence);
  3733. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3734. if (!reply)
  3735. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3736. if (reply)
  3737. {
  3738. original->setDebugResponse(debugSequence, reply);
  3739. ROQ->sendPacket(reply, activity.queryLogCtx());
  3740. }
  3741. }
  3742. else
  3743. throwUnexpected();
  3744. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3745. // Leave original message on pending queue in original location - this is not a reply to it.
  3746. break;
  3747. }
  3748. case ROXIE_FILECALLBACK:
  3749. {
  3750. // we need to send back to the slave a message containing the file info requested.
  3751. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3752. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3753. if (len)
  3754. {
  3755. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3756. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3757. const char *rowdata = (const char *) row.get();
  3758. bool isOpt = * (bool *) rowdata;
  3759. bool isLocal = * (bool *) (rowdata+1);
  3760. const char *lfn = rowdata+2;
  3761. if (ctxTraceLevel > 5)
  3762. {
  3763. StringBuffer s;
  3764. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3765. }
  3766. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3767. }
  3768. else
  3769. throwUnexpected();
  3770. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3771. // Leave original message on pending queue in original location - this is not a reply to it.
  3772. break;
  3773. }
  3774. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3775. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3776. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3777. throwUnexpected();
  3778. case ROXIE_LIMIT_EXCEEDED:
  3779. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3780. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3781. throwUnexpected();
  3782. case ROXIE_TRACEINFO:
  3783. {
  3784. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3785. loop
  3786. {
  3787. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3788. if (rowlen)
  3789. {
  3790. char *logInfo = (char *) extra->getNext(*rowlen);
  3791. MemoryBuffer buf;
  3792. buf.setBuffer(*rowlen, logInfo, false);
  3793. switch ((TracingCategory) *logInfo)
  3794. {
  3795. case LOG_TRACING:
  3796. case LOG_ERROR:
  3797. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3798. break;
  3799. case LOG_STATVALUES:
  3800. buf.skip(1);
  3801. activity.mergeStats(buf);
  3802. break;
  3803. case LOG_CHILDCOUNT:
  3804. case LOG_CHILDSTATS:
  3805. unsigned graphId, childId;
  3806. buf.skip(1);
  3807. buf.read(graphId);
  3808. buf.read(childId);
  3809. if (*logInfo == LOG_CHILDCOUNT)
  3810. {
  3811. unsigned childProcessed;
  3812. unsigned idx;
  3813. buf.read(childProcessed);
  3814. buf.read(idx);
  3815. if (traceLevel > 5)
  3816. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d for child %d subgraph %d", childProcessed, idx, childId, graphId);
  3817. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed);
  3818. }
  3819. else
  3820. {
  3821. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  3822. CRuntimeStatisticCollection childStats(allStatistics);
  3823. childStats.deserialize(buf);
  3824. if (traceLevel > 5)
  3825. {
  3826. StringBuffer s;
  3827. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  3828. }
  3829. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  3830. }
  3831. }
  3832. ReleaseRoxieRow(rowlen);
  3833. ReleaseRoxieRow(logInfo);
  3834. }
  3835. else
  3836. break;
  3837. }
  3838. break;
  3839. }
  3840. case ROXIE_EXCEPTION:
  3841. if (ctxTraceLevel > 1)
  3842. {
  3843. StringBuffer s;
  3844. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3845. }
  3846. op->queryHeader().noteException(header.retries);
  3847. if (op->queryHeader().allChannelsFailed())
  3848. {
  3849. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3850. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3851. throwRemoteException(exceptionData);
  3852. }
  3853. // Leave it on pending queue in original location
  3854. break;
  3855. case ROXIE_ALIVE:
  3856. if (ctxTraceLevel > 4)
  3857. {
  3858. StringBuffer s;
  3859. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3860. }
  3861. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3862. // Leave it on pending queue in original location
  3863. break;
  3864. default:
  3865. if (header.retries & ROXIE_RETRIES_MASK)
  3866. atomic_inc(&retriesNeeded);
  3867. unsigned metaLen;
  3868. const void *metaData = mr->getMessageMetadata(metaLen);
  3869. if (metaLen)
  3870. {
  3871. // We got back first chunk but there is more.
  3872. // resend the packet, with the cursor info provided.
  3873. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3874. if (ctxTraceLevel > 1)
  3875. {
  3876. StringBuffer s;
  3877. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3878. }
  3879. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3880. {
  3881. StringBuffer s;
  3882. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3883. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3884. throwUnexpected();
  3885. }
  3886. MemoryBuffer nextQuery;
  3887. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3888. nextQuery.append(metaLen, metaData);
  3889. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3890. nextQuery.append(op->getContextLength(), op->queryContextData());
  3891. if (resendSequence == CONTINUESEQUENCE_MAX)
  3892. {
  3893. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3894. resendSequence = 1;
  3895. }
  3896. else
  3897. resendSequence++;
  3898. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3899. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3900. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3901. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3902. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3903. fqp->setSequence(original->getSequence());
  3904. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3905. original->setContinuation(LINK(fqp));
  3906. if (mergeOrder)
  3907. fqp->setDelayed(true);
  3908. else
  3909. {
  3910. ROQ->sendPacket(resend, activity.queryLogCtx());
  3911. sentsome.signal();
  3912. }
  3913. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3914. }
  3915. else
  3916. {
  3917. if (serverSideCache)
  3918. serverSideCache->noteCachedResult(original, mr);
  3919. }
  3920. unsigned channel = header.channel;
  3921. {
  3922. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3923. if (b)
  3924. b->signal();
  3925. }
  3926. original->setResult(mr.getClear());
  3927. sentsome.signal();
  3928. return;
  3929. }
  3930. }
  3931. }
  3932. else
  3933. {
  3934. if (!anyActivity && !localSlave)
  3935. {
  3936. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3937. retryPending();
  3938. }
  3939. }
  3940. }
  3941. }
  3942. inline unsigned headerLength() const
  3943. {
  3944. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3945. }
  3946. void copyHeader(byte *tgt, unsigned channel) const
  3947. {
  3948. unsigned len = logInfo.length();
  3949. memcpy(tgt, logInfo.toByteArray(), len);
  3950. tgt += len;
  3951. *(unsigned *) tgt = parentExtractSize;
  3952. tgt += sizeof(unsigned);
  3953. memcpy(tgt, parentExtract, parentExtractSize);
  3954. tgt += parentExtractSize;
  3955. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3956. tgt += cachedContext.length();
  3957. }
  3958. };
  3959. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3960. {
  3961. Owned <IException> exception;
  3962. bool skipping;
  3963. ConstPointerArray buff;
  3964. unsigned index;
  3965. bool pulled;
  3966. void pullInput()
  3967. {
  3968. try
  3969. {
  3970. if (exception)
  3971. throw exception.getClear();
  3972. unsigned __int64 count = 0;
  3973. loop
  3974. {
  3975. const void * next = CRemoteResultAdaptor::nextInGroup();
  3976. if (next == NULL)
  3977. {
  3978. next = CRemoteResultAdaptor::nextInGroup();
  3979. if(next == NULL)
  3980. break;
  3981. buff.append(NULL);
  3982. }
  3983. count++;
  3984. if (count > rowLimit)
  3985. {
  3986. ReleaseRoxieRow(next);
  3987. ReleaseRoxieRowSet(buff);
  3988. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3989. throwUnexpected();
  3990. }
  3991. else if (count > keyedLimit)
  3992. {
  3993. ReleaseRoxieRow(next);
  3994. ReleaseRoxieRowSet(buff);
  3995. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3996. throwUnexpected();
  3997. }
  3998. buff.append(next);
  3999. }
  4000. }
  4001. catch (IException *E)
  4002. {
  4003. if (QUERYINTERFACE(E, LimitSkipException))
  4004. {
  4005. Owned<IException> cleanup = E;
  4006. ReleaseRoxieRowSet(buff);
  4007. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4008. if (onfail)
  4009. buff.append(onfail);
  4010. }
  4011. else
  4012. throw;
  4013. }
  4014. pulled = true;
  4015. }
  4016. public:
  4017. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4018. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4019. {
  4020. skipping = _skipping;
  4021. index = 0;
  4022. pulled = false;
  4023. }
  4024. void setException(IException *E)
  4025. {
  4026. exception.setown(E);
  4027. }
  4028. virtual void onReset()
  4029. {
  4030. while (buff.isItem(index))
  4031. ReleaseRoxieRow(buff.item(index++));
  4032. buff.kill();
  4033. pulled = false;
  4034. exception.clear();
  4035. CRemoteResultAdaptor::onReset();
  4036. }
  4037. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4038. {
  4039. index = 0;
  4040. pulled = false;
  4041. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4042. }
  4043. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4044. {
  4045. // 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
  4046. if (exception)
  4047. throw exception.getClear();
  4048. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4049. }
  4050. virtual const void *nextInGroup()
  4051. {
  4052. if (skipping)
  4053. {
  4054. if(!pulled)
  4055. pullInput();
  4056. if(buff.isItem(index))
  4057. {
  4058. const void * next = buff.item(index++);
  4059. if(next)
  4060. processed++;
  4061. return next;
  4062. }
  4063. return NULL;
  4064. }
  4065. else
  4066. {
  4067. if (exception)
  4068. throw exception.getClear();
  4069. return CRemoteResultAdaptor::nextInGroup();
  4070. }
  4071. }
  4072. };
  4073. //=================================================================================
  4074. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4075. {
  4076. IHThorApplyArg &helper;
  4077. public:
  4078. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4079. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4080. {
  4081. }
  4082. virtual void onExecute()
  4083. {
  4084. helper.start();
  4085. loop
  4086. {
  4087. const void * next = input->nextInGroup();
  4088. if (!next)
  4089. {
  4090. next = input->nextInGroup();
  4091. if (!next)
  4092. break;
  4093. }
  4094. helper.apply(next);
  4095. ReleaseRoxieRow(next);
  4096. }
  4097. helper.end();
  4098. }
  4099. };
  4100. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4101. {
  4102. bool isRoot;
  4103. public:
  4104. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4105. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4106. {
  4107. }
  4108. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4109. {
  4110. return new CRoxieServerApplyActivity(this, _probeManager);
  4111. }
  4112. virtual bool isSink() const
  4113. {
  4114. return isRoot;
  4115. }
  4116. };
  4117. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4118. {
  4119. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4120. }
  4121. //=================================================================================
  4122. class CRoxieServerNullActivity : public CRoxieServerActivity
  4123. {
  4124. public:
  4125. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4126. : CRoxieServerActivity(_factory, _probeManager)
  4127. {
  4128. }
  4129. virtual const void *nextInGroup()
  4130. {
  4131. return NULL;
  4132. }
  4133. };
  4134. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4135. {
  4136. return new CRoxieServerNullActivity(_factory, _probeManager);
  4137. }
  4138. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4139. {
  4140. public:
  4141. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4142. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4143. {
  4144. }
  4145. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4146. {
  4147. return new CRoxieServerNullActivity(this, _probeManager);
  4148. }
  4149. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4150. {
  4151. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4152. }
  4153. };
  4154. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4155. {
  4156. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4157. }
  4158. //=================================================================================
  4159. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4160. {
  4161. public:
  4162. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4163. : CRoxieServerActivity(_factory, _probeManager)
  4164. {
  4165. }
  4166. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4167. {
  4168. return input->gatherConjunctions(collector);
  4169. }
  4170. virtual void resetEOF()
  4171. {
  4172. input->resetEOF();
  4173. }
  4174. virtual const void *nextInGroup()
  4175. {
  4176. const void * next = input->nextInGroup();
  4177. if (next)
  4178. processed++;
  4179. return next;
  4180. }
  4181. virtual bool isPassThrough()
  4182. {
  4183. return true;
  4184. }
  4185. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4186. {
  4187. ActivityTimer t(totalCycles, timeActivities);
  4188. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4189. if (next)
  4190. processed++;
  4191. return next;
  4192. }
  4193. IInputSteppingMeta * querySteppingMeta()
  4194. {
  4195. return input->querySteppingMeta();
  4196. }
  4197. };
  4198. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4199. {
  4200. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4201. }
  4202. //=================================================================================
  4203. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4204. {
  4205. protected:
  4206. bool eof;
  4207. bool first;
  4208. public:
  4209. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4210. : CRoxieServerActivity(_factory, _probeManager)
  4211. {
  4212. eof = false;
  4213. first = true;
  4214. }
  4215. ~CRoxieServerChildBaseActivity()
  4216. {
  4217. }
  4218. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4219. {
  4220. eof = false;
  4221. first = true;
  4222. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4223. }
  4224. };
  4225. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4226. {
  4227. public:
  4228. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4229. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4230. {
  4231. }
  4232. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4233. {
  4234. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4235. }
  4236. };
  4237. //=================================================================================
  4238. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4239. {
  4240. IHThorChildIteratorArg &helper;
  4241. public:
  4242. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4243. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4244. {
  4245. }
  4246. virtual bool needsAllocator() const { return true; }
  4247. virtual const void *nextInGroup()
  4248. {
  4249. ActivityTimer t(totalCycles, timeActivities);
  4250. if (eof)
  4251. return NULL;
  4252. bool ok;
  4253. if (first)
  4254. {
  4255. ok = helper.first();
  4256. first = false;
  4257. }
  4258. else
  4259. ok = helper.next();
  4260. try
  4261. {
  4262. while (ok)
  4263. {
  4264. processed++;
  4265. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4266. unsigned outSize = helper.transform(rowBuilder);
  4267. if (outSize)
  4268. return rowBuilder.finalizeRowClear(outSize);
  4269. ok = helper.next();
  4270. }
  4271. }
  4272. catch (IException *E)
  4273. {
  4274. throw makeWrappedException(E);
  4275. }
  4276. eof = true;
  4277. return NULL;
  4278. }
  4279. };
  4280. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4281. {
  4282. public:
  4283. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4284. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4285. {
  4286. }
  4287. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4288. {
  4289. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4290. }
  4291. };
  4292. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4293. {
  4294. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4295. }
  4296. //=================================================================================
  4297. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4298. {
  4299. IHThorChildNormalizeArg &helper;
  4300. public:
  4301. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4302. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4303. {
  4304. }
  4305. virtual bool needsAllocator() const { return true; }
  4306. virtual const void *nextInGroup()
  4307. {
  4308. ActivityTimer t(totalCycles, timeActivities);
  4309. if (eof)
  4310. return NULL;
  4311. bool ok;
  4312. if (first)
  4313. {
  4314. ok = helper.first();
  4315. first = false;
  4316. }
  4317. else
  4318. ok = helper.next();
  4319. if (ok)
  4320. {
  4321. try
  4322. {
  4323. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4324. do {
  4325. unsigned outSize = helper.transform(rowBuilder);
  4326. if (outSize)
  4327. {
  4328. processed++;
  4329. return rowBuilder.finalizeRowClear(outSize);
  4330. }
  4331. ok = helper.next();
  4332. }
  4333. while (ok);
  4334. }
  4335. catch (IException *E)
  4336. {
  4337. throw makeWrappedException(E);
  4338. }
  4339. }
  4340. eof = true;
  4341. return NULL;
  4342. }
  4343. };
  4344. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4345. {
  4346. public:
  4347. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4348. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4349. {
  4350. }
  4351. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4352. {
  4353. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4354. }
  4355. };
  4356. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4357. {
  4358. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4359. }
  4360. //=================================================================================
  4361. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4362. {
  4363. IHThorChildAggregateArg &helper;
  4364. public:
  4365. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4366. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4367. {
  4368. }
  4369. virtual bool needsAllocator() const { return true; }
  4370. virtual const void *nextInGroup()
  4371. {
  4372. ActivityTimer t(totalCycles, timeActivities);
  4373. if (eof)
  4374. return NULL;
  4375. eof = true;
  4376. processed++;
  4377. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4378. helper.clearAggregate(rowBuilder);
  4379. helper.processRows(rowBuilder);
  4380. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4381. return rowBuilder.finalizeRowClear(finalSize);
  4382. }
  4383. };
  4384. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4385. {
  4386. public:
  4387. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4388. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4389. {
  4390. }
  4391. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4392. {
  4393. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4394. }
  4395. };
  4396. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4397. {
  4398. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4399. }
  4400. //=================================================================================
  4401. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4402. {
  4403. IHThorChildGroupAggregateArg &helper;
  4404. RowAggregator aggregated;
  4405. public:
  4406. IMPLEMENT_IINTERFACE
  4407. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4408. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4409. aggregated(helper, helper)
  4410. {
  4411. }
  4412. void processRow(const void * next)
  4413. {
  4414. aggregated.addRow(next);
  4415. }
  4416. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4417. {
  4418. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4419. aggregated.start(rowAllocator);
  4420. }
  4421. virtual void reset()
  4422. {
  4423. aggregated.reset();
  4424. CRoxieServerChildBaseActivity::reset();
  4425. }
  4426. virtual bool needsAllocator() const { return true; }
  4427. virtual const void *nextInGroup()
  4428. {
  4429. ActivityTimer t(totalCycles, timeActivities);
  4430. if (eof)
  4431. return NULL;
  4432. if (first)
  4433. {
  4434. helper.processRows(this);
  4435. first = false;
  4436. }
  4437. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4438. if (next)
  4439. {
  4440. processed++;
  4441. return next->finalizeRowClear();
  4442. }
  4443. eof = true;
  4444. return NULL;
  4445. }
  4446. };
  4447. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4448. {
  4449. public:
  4450. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4451. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4452. {
  4453. }
  4454. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4455. {
  4456. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4457. }
  4458. };
  4459. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4460. {
  4461. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4462. }
  4463. //=================================================================================
  4464. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4465. {
  4466. IHThorChildThroughNormalizeArg &helper;
  4467. const void * lastInput;
  4468. unsigned numProcessedLastGroup;
  4469. bool ok;
  4470. public:
  4471. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4472. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4473. {
  4474. lastInput = NULL;
  4475. numProcessedLastGroup = 0;
  4476. ok = false;
  4477. }
  4478. virtual void stop(bool aborting)
  4479. {
  4480. CRoxieServerChildBaseActivity::stop(aborting);
  4481. ReleaseRoxieRow(lastInput);
  4482. lastInput = NULL;
  4483. }
  4484. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4485. {
  4486. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4487. numProcessedLastGroup = processed;
  4488. ok = false;
  4489. }
  4490. virtual bool needsAllocator() const { return true; }
  4491. virtual const void *nextInGroup()
  4492. {
  4493. ActivityTimer t(totalCycles, timeActivities);
  4494. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4495. loop
  4496. {
  4497. if (ok)
  4498. ok = helper.next();
  4499. while (!ok)
  4500. {
  4501. ReleaseRoxieRow(lastInput);
  4502. lastInput = input->nextInGroup();
  4503. if (!lastInput)
  4504. {
  4505. if (numProcessedLastGroup != processed)
  4506. {
  4507. numProcessedLastGroup = processed;
  4508. return NULL;
  4509. }
  4510. lastInput = input->nextInGroup();
  4511. if (!lastInput)
  4512. return NULL;
  4513. }
  4514. ok = helper.first(lastInput);
  4515. }
  4516. try
  4517. {
  4518. do
  4519. {
  4520. unsigned outSize = helper.transform(rowBuilder);
  4521. if (outSize)
  4522. {
  4523. processed++;
  4524. return rowBuilder.finalizeRowClear(outSize);
  4525. }
  4526. ok = helper.next();
  4527. } while (ok);
  4528. }
  4529. catch (IException *E)
  4530. {
  4531. throw makeWrappedException(E);
  4532. }
  4533. }
  4534. }
  4535. };
  4536. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4537. {
  4538. public:
  4539. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4540. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4541. {
  4542. }
  4543. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4544. {
  4545. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4546. }
  4547. };
  4548. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4549. {
  4550. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4551. }
  4552. //=================================================================================
  4553. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  4554. {
  4555. IHThorDistributionArg &helper;
  4556. public:
  4557. CRoxieServerDistributionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4558. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  4559. {
  4560. }
  4561. virtual void onExecute()
  4562. {
  4563. MemoryAttr ma;
  4564. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  4565. helper.clearAggregate(accumulator);
  4566. OwnedConstRoxieRow nextrec(input->nextInGroup());
  4567. loop
  4568. {
  4569. if (!nextrec)
  4570. {
  4571. nextrec.setown(input->nextInGroup());
  4572. if (!nextrec)
  4573. break;
  4574. }
  4575. helper.process(accumulator, nextrec);
  4576. nextrec.setown(input->nextInGroup());
  4577. }
  4578. StringBuffer result;
  4579. result.append("<XML>");
  4580. helper.gatherResult(accumulator, result);
  4581. result.append("</XML>");
  4582. helper.sendResult(result.length(), result.str());
  4583. helper.destruct(accumulator);
  4584. }
  4585. };
  4586. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  4587. {
  4588. bool isRoot;
  4589. public:
  4590. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4591. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4592. {
  4593. }
  4594. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4595. {
  4596. return new CRoxieServerDistributionActivity(this, _probeManager);
  4597. }
  4598. virtual bool isSink() const
  4599. {
  4600. return isRoot;
  4601. }
  4602. };
  4603. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4604. {
  4605. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4606. }
  4607. //=================================================================================
  4608. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4609. {
  4610. IHThorLinkedRawIteratorArg &helper;
  4611. public:
  4612. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4613. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4614. {
  4615. }
  4616. virtual const void *nextInGroup()
  4617. {
  4618. ActivityTimer t(totalCycles, timeActivities);
  4619. const void *ret =helper.next();
  4620. if (ret)
  4621. {
  4622. LinkRoxieRow(ret);
  4623. processed++;
  4624. }
  4625. return ret;
  4626. }
  4627. };
  4628. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4629. {
  4630. public:
  4631. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4632. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4633. {
  4634. }
  4635. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4636. {
  4637. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4638. }
  4639. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4640. {
  4641. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4642. }
  4643. };
  4644. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4645. {
  4646. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4647. }
  4648. //=================================================================================
  4649. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4650. {
  4651. public:
  4652. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4653. : CRoxieServerActivity(_factory, _probeManager)
  4654. {
  4655. }
  4656. virtual const void *nextInGroup()
  4657. {
  4658. throwUnexpected();
  4659. }
  4660. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4661. {
  4662. try
  4663. {
  4664. start(parentExtractSize, parentExtract, false);
  4665. {
  4666. ActivityTimer t(totalCycles, timeActivities);
  4667. MemoryBuffer result;
  4668. IRecordSize * inputMeta = input->queryOutputMeta();
  4669. loop
  4670. {
  4671. const void *nextrec = input->nextInGroup();
  4672. if (!nextrec)
  4673. {
  4674. nextrec = input->nextInGroup();
  4675. if (!nextrec)
  4676. break;
  4677. }
  4678. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4679. ReleaseRoxieRow(nextrec);
  4680. }
  4681. retSize = result.length();
  4682. ret = result.detach();
  4683. }
  4684. stop(false);
  4685. reset();
  4686. }
  4687. catch(IException *E)
  4688. {
  4689. ctx->notifyAbort(E);
  4690. stop(true);
  4691. reset();
  4692. throw;
  4693. }
  4694. catch(...)
  4695. {
  4696. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4697. ctx->notifyAbort(E);
  4698. stop(true);
  4699. reset();
  4700. throw;
  4701. }
  4702. }
  4703. };
  4704. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4705. {
  4706. bool isRoot;
  4707. public:
  4708. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4709. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4710. {
  4711. }
  4712. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4713. {
  4714. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4715. }
  4716. virtual bool isSink() const
  4717. {
  4718. return isRoot;
  4719. }
  4720. };
  4721. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4722. {
  4723. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4724. }
  4725. //=================================================================================
  4726. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4727. {
  4728. IHThorInlineTableArg &helper;
  4729. __uint64 curRow;
  4730. __uint64 numRows;
  4731. public:
  4732. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4733. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4734. {
  4735. curRow = 0;
  4736. numRows = 0;
  4737. }
  4738. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4739. {
  4740. curRow = 0;
  4741. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4742. numRows = helper.numRows();
  4743. }
  4744. virtual bool needsAllocator() const { return true; }
  4745. virtual const void *nextInGroup()
  4746. {
  4747. ActivityTimer t(totalCycles, timeActivities);
  4748. // Filtering empty rows, returns the next valid row
  4749. while (curRow < numRows)
  4750. {
  4751. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4752. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4753. if (outSize)
  4754. {
  4755. processed++;
  4756. return rowBuilder.finalizeRowClear(outSize);
  4757. }
  4758. }
  4759. return NULL;
  4760. }
  4761. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4762. {
  4763. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4764. }
  4765. };
  4766. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4767. {
  4768. public:
  4769. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4770. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4771. {
  4772. }
  4773. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4774. {
  4775. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4776. }
  4777. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4778. {
  4779. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4780. }
  4781. };
  4782. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4783. {
  4784. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4785. }
  4786. //=================================================================================
  4787. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4788. {
  4789. IHThorWorkunitReadArg &helper;
  4790. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4791. public:
  4792. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4793. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4794. {
  4795. }
  4796. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4797. {
  4798. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4799. if (!ctx->queryServerContext())
  4800. {
  4801. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4802. }
  4803. }
  4804. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4805. {
  4806. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4807. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4808. OwnedRoxieString fromWuid(helper.getWUID());
  4809. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4810. // MORE _ should that be in onCreate?
  4811. }
  4812. virtual void reset()
  4813. {
  4814. CriticalBlock b(statecrit);
  4815. wuReader.clear();
  4816. CRoxieServerActivity::reset();
  4817. };
  4818. virtual bool needsAllocator() const { return true; }
  4819. virtual const void *nextInGroup()
  4820. {
  4821. CriticalBlock b(statecrit);
  4822. ActivityTimer t(totalCycles, timeActivities);
  4823. if (!wuReader)
  4824. return NULL;
  4825. const void *ret = wuReader->nextInGroup();
  4826. if (ret)
  4827. processed++;
  4828. return ret;
  4829. }
  4830. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4831. {
  4832. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4833. }
  4834. };
  4835. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4836. {
  4837. public:
  4838. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4839. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4840. {
  4841. }
  4842. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4843. {
  4844. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4845. }
  4846. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4847. {
  4848. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4849. }
  4850. };
  4851. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4852. {
  4853. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4854. }
  4855. //=================================================================================
  4856. interface ILocalGraphEx : public IEclGraphResults
  4857. {
  4858. public:
  4859. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4860. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4861. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4862. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4863. };
  4864. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4865. {
  4866. public:
  4867. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4868. IMPLEMENT_IINTERFACE
  4869. virtual IOutputMetaData * queryOutputMeta() const
  4870. {
  4871. return input->queryOutputMeta();
  4872. }
  4873. virtual unsigned queryId() const
  4874. {
  4875. return input->queryId();
  4876. }
  4877. virtual unsigned __int64 queryTotalCycles() const
  4878. {
  4879. return input->queryTotalCycles();
  4880. }
  4881. virtual unsigned __int64 queryLocalCycles() const
  4882. {
  4883. return input->queryLocalCycles();
  4884. }
  4885. virtual IRoxieInput *queryInput(unsigned idx) const
  4886. {
  4887. return input->queryInput(idx);
  4888. }
  4889. virtual IRoxieServerActivity *queryActivity()
  4890. {
  4891. return input->queryActivity();
  4892. }
  4893. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4894. {
  4895. return input->queryIndexReadActivity();
  4896. }
  4897. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4898. {
  4899. CriticalBlock procedure(cs);
  4900. input->start(parentExtractSize, parentExtract, paused);
  4901. }
  4902. virtual void stop(bool aborting)
  4903. {
  4904. CriticalBlock procedure(cs);
  4905. input->stop(aborting);
  4906. }
  4907. virtual void reset()
  4908. {
  4909. CriticalBlock procedure(cs);
  4910. input->reset();
  4911. }
  4912. virtual void resetEOF()
  4913. {
  4914. CriticalBlock procedure(cs);
  4915. input->resetEOF();
  4916. }
  4917. virtual void checkAbort()
  4918. {
  4919. CriticalBlock procedure(cs);
  4920. input->checkAbort();
  4921. }
  4922. virtual const void *nextInGroup()
  4923. {
  4924. CriticalBlock procedure(cs);
  4925. return input->nextInGroup();
  4926. }
  4927. virtual bool nextGroup(ConstPointerArray & group)
  4928. {
  4929. CriticalBlock procedure(cs);
  4930. return input->nextGroup(group);
  4931. }
  4932. private:
  4933. CriticalSection cs;
  4934. Linked<IRoxieInput> input;
  4935. };
  4936. //=================================================================================
  4937. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4938. {
  4939. public:
  4940. IMPLEMENT_IINTERFACE;
  4941. CPseudoRoxieInput()
  4942. {
  4943. }
  4944. virtual unsigned __int64 queryTotalCycles() const
  4945. {
  4946. return 0;
  4947. }
  4948. virtual unsigned __int64 queryLocalCycles() const
  4949. {
  4950. return 0;
  4951. }
  4952. virtual IRoxieInput *queryInput(unsigned idx) const
  4953. {
  4954. return NULL;
  4955. }
  4956. virtual IRoxieServerActivity *queryActivity()
  4957. {
  4958. throwUnexpected();
  4959. }
  4960. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4961. {
  4962. throwUnexpected();
  4963. }
  4964. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4965. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4966. virtual void stop(bool aborting) { }
  4967. virtual void reset() { }
  4968. virtual void checkAbort() { }
  4969. virtual unsigned queryId() const { throwUnexpected(); }
  4970. virtual void resetEOF() { }
  4971. };
  4972. class CIndirectRoxieInput : public CPseudoRoxieInput
  4973. {
  4974. public:
  4975. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4976. {
  4977. }
  4978. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4979. {
  4980. input->start(parentExtractSize, parentExtract, paused);
  4981. }
  4982. virtual void stop(bool aborting)
  4983. {
  4984. input->stop(aborting);
  4985. }
  4986. virtual void reset()
  4987. {
  4988. input->reset();
  4989. }
  4990. virtual void checkAbort()
  4991. {
  4992. input->checkAbort();
  4993. }
  4994. virtual const void * nextInGroup()
  4995. {
  4996. return input->nextInGroup();
  4997. }
  4998. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4999. {
  5000. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5001. }
  5002. virtual unsigned __int64 queryTotalCycles() const
  5003. {
  5004. return input->queryTotalCycles();
  5005. }
  5006. virtual unsigned __int64 queryLocalCycles() const
  5007. {
  5008. return input->queryLocalCycles();
  5009. }
  5010. virtual IRoxieInput *queryInput(unsigned idx) const
  5011. {
  5012. return input->queryInput(idx);
  5013. }
  5014. virtual unsigned queryId() const
  5015. {
  5016. return input->queryId();
  5017. }
  5018. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5019. {
  5020. return input->gatherConjunctions(collector);
  5021. }
  5022. virtual void resetEOF()
  5023. {
  5024. input->resetEOF();
  5025. }
  5026. virtual unsigned numConcreteOutputs() const
  5027. {
  5028. return input->numConcreteOutputs();
  5029. }
  5030. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  5031. {
  5032. return input->queryConcreteInput(idx);
  5033. }
  5034. virtual IOutputMetaData * queryOutputMeta() const
  5035. {
  5036. return input->queryOutputMeta();
  5037. }
  5038. virtual IRoxieServerActivity *queryActivity()
  5039. {
  5040. return input->queryActivity();
  5041. }
  5042. void setInput(IRoxieInput * _input)
  5043. {
  5044. input = _input;
  5045. }
  5046. protected:
  5047. IRoxieInput * input;
  5048. };
  5049. class CExtractMapperInput : public CIndirectRoxieInput
  5050. {
  5051. unsigned savedParentExtractSize;
  5052. const byte * savedParentExtract;
  5053. public:
  5054. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  5055. {
  5056. savedParentExtractSize = 0;
  5057. savedParentExtract = NULL;
  5058. }
  5059. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5060. {
  5061. input->start(savedParentExtractSize, savedParentExtract, paused);
  5062. }
  5063. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5064. {
  5065. savedParentExtractSize = _savedParentExtractSize;
  5066. savedParentExtract = _savedParentExtract;
  5067. }
  5068. };
  5069. class CGraphResult : public CInterface, implements IGraphResult
  5070. {
  5071. CriticalSection cs;
  5072. byte **rowset;
  5073. size32_t count;
  5074. bool complete;
  5075. void clear()
  5076. {
  5077. CriticalBlock func(cs);
  5078. rtlReleaseRowset(count, rowset);
  5079. rowset = NULL;
  5080. count = 0;
  5081. complete = false;
  5082. }
  5083. public:
  5084. IMPLEMENT_IINTERFACE
  5085. CGraphResult()
  5086. {
  5087. complete = false; // dummy result is not supposed to be used...
  5088. rowset = NULL;
  5089. count = 0;
  5090. }
  5091. CGraphResult(size32_t _count, byte **_rowset)
  5092. : count(_count), rowset(_rowset)
  5093. {
  5094. complete = true;
  5095. }
  5096. ~CGraphResult()
  5097. {
  5098. clear();
  5099. }
  5100. // interface IGraphResult
  5101. virtual IRoxieInput * createIterator()
  5102. {
  5103. if (!complete)
  5104. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5105. return new CGraphResultIterator(this);
  5106. }
  5107. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5108. {
  5109. if (!complete)
  5110. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5111. result = rtlLinkRowset(rowset);
  5112. countResult = count;
  5113. }
  5114. virtual const void * getLinkedRowResult()
  5115. {
  5116. if (!complete)
  5117. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5118. if (count != 1)
  5119. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5120. const void * ret = rowset[0];
  5121. LinkRoxieRow(ret);
  5122. return ret;
  5123. }
  5124. //other
  5125. const void * getRow(unsigned i)
  5126. {
  5127. CriticalBlock func(cs);
  5128. if (i >= count)
  5129. return NULL;
  5130. const void * ret = rowset[i];
  5131. if (ret) LinkRoxieRow(ret);
  5132. return ret;
  5133. }
  5134. protected:
  5135. class CGraphResultIterator : public CPseudoRoxieInput
  5136. {
  5137. unsigned i;
  5138. Linked<CGraphResult> result;
  5139. public:
  5140. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5141. IMPLEMENT_IINTERFACE
  5142. public:
  5143. virtual const void * nextInGroup()
  5144. {
  5145. return result->getRow(i++);
  5146. }
  5147. };
  5148. };
  5149. //=================================================================================
  5150. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5151. {
  5152. IHThorLocalResultReadArg &helper;
  5153. Owned<IRoxieInput> iter;
  5154. ILocalGraphEx * graph;
  5155. unsigned graphId;
  5156. unsigned sequence;
  5157. public:
  5158. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5159. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5160. {
  5161. graph = NULL;
  5162. sequence = 0;
  5163. }
  5164. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5165. {
  5166. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5167. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5168. sequence = helper.querySequence();
  5169. }
  5170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5171. {
  5172. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5173. iter.setown(graph->createResultIterator(sequence));
  5174. }
  5175. virtual void reset()
  5176. {
  5177. CriticalBlock b(statecrit);
  5178. iter.clear();
  5179. CRoxieServerActivity::reset();
  5180. };
  5181. virtual const void *nextInGroup()
  5182. {
  5183. CriticalBlock b(statecrit);
  5184. ActivityTimer t(totalCycles, timeActivities);
  5185. if (!iter)
  5186. return NULL;
  5187. const void * next = iter->nextInGroup();
  5188. if (next)
  5189. {
  5190. processed++;
  5191. atomic_inc(&rowsIn);
  5192. }
  5193. return next;
  5194. }
  5195. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5196. {
  5197. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5198. }
  5199. };
  5200. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5201. {
  5202. unsigned graphId;
  5203. public:
  5204. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5205. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5206. {
  5207. }
  5208. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5209. {
  5210. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5211. }
  5212. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5213. {
  5214. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5215. }
  5216. };
  5217. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5218. {
  5219. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5220. }
  5221. //=================================================================================
  5222. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5223. {
  5224. IHThorLocalResultReadArg &helper;
  5225. Owned<IRoxieInput> streamInput;
  5226. unsigned sequence;
  5227. public:
  5228. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5229. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5230. {
  5231. sequence = 0;
  5232. }
  5233. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5234. {
  5235. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5236. sequence = helper.querySequence();
  5237. }
  5238. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5239. {
  5240. assertex(streamInput != NULL);
  5241. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5242. streamInput->start(parentExtractSize, parentExtract, paused);
  5243. }
  5244. virtual void stop(bool aborting)
  5245. {
  5246. CRoxieServerActivity::stop(aborting);
  5247. streamInput->stop(aborting);
  5248. }
  5249. virtual void reset()
  5250. {
  5251. streamInput->reset();
  5252. CRoxieServerActivity::reset();
  5253. };
  5254. virtual const void *nextInGroup()
  5255. {
  5256. ActivityTimer t(totalCycles, timeActivities);
  5257. const void * next = streamInput->nextInGroup();
  5258. if (next)
  5259. {
  5260. processed++;
  5261. atomic_inc(&rowsIn);
  5262. }
  5263. return next;
  5264. }
  5265. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5266. {
  5267. if (id == sequence)
  5268. {
  5269. streamInput.set(_input);
  5270. return true;
  5271. }
  5272. return false;
  5273. }
  5274. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5275. {
  5276. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5277. }
  5278. };
  5279. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5280. {
  5281. public:
  5282. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5283. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5284. {
  5285. }
  5286. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5287. {
  5288. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5289. }
  5290. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5291. {
  5292. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5293. }
  5294. };
  5295. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5296. {
  5297. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5298. }
  5299. //=====================================================================================================
  5300. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5301. {
  5302. IHThorLocalResultWriteArg &helper;
  5303. ILocalGraphEx * graph;
  5304. unsigned graphId;
  5305. public:
  5306. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5307. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5308. {
  5309. graph = NULL;
  5310. }
  5311. virtual bool needsAllocator() const { return true; }
  5312. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5313. {
  5314. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5315. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5316. }
  5317. virtual void onExecute()
  5318. {
  5319. RtlLinkedDatasetBuilder builder(rowAllocator);
  5320. input->readAll(builder);
  5321. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5322. graph->setResult(helper.querySequence(), result);
  5323. }
  5324. virtual const void *nextInGroup()
  5325. {
  5326. return input->nextInGroup(); // I can act as a passthrough input
  5327. }
  5328. IRoxieInput * querySelectOutput(unsigned id)
  5329. {
  5330. if (id == helper.querySequence())
  5331. {
  5332. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5333. return LINK(this);
  5334. }
  5335. return NULL;
  5336. }
  5337. };
  5338. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5339. {
  5340. unsigned graphId;
  5341. public:
  5342. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5343. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5344. {
  5345. isInternal = true;
  5346. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5347. }
  5348. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5349. {
  5350. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId, usageCount);
  5351. }
  5352. };
  5353. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5354. {
  5355. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5356. }
  5357. //=====================================================================================================
  5358. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5359. {
  5360. IHThorDictionaryResultWriteArg &helper;
  5361. ILocalGraphEx * graph;
  5362. unsigned graphId;
  5363. public:
  5364. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  5365. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5366. {
  5367. graph = NULL;
  5368. }
  5369. virtual bool needsAllocator() const { return true; }
  5370. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5371. {
  5372. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5373. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5374. }
  5375. virtual void onExecute()
  5376. {
  5377. unsigned sequence = helper.querySequence();
  5378. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5379. loop
  5380. {
  5381. const void *row = input->nextInGroup();
  5382. if (!row)
  5383. {
  5384. row = input->nextInGroup();
  5385. if (!row)
  5386. break;
  5387. }
  5388. builder.appendOwn(row);
  5389. processed++;
  5390. }
  5391. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5392. graph->setResult(helper.querySequence(), result);
  5393. }
  5394. virtual const void *nextInGroup()
  5395. {
  5396. return input->nextInGroup(); // I can act as a passthrough input
  5397. }
  5398. IRoxieInput * querySelectOutput(unsigned id)
  5399. {
  5400. if (id == helper.querySequence())
  5401. {
  5402. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5403. return LINK(this);
  5404. }
  5405. return NULL;
  5406. }
  5407. };
  5408. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5409. {
  5410. unsigned graphId;
  5411. public:
  5412. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5413. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5414. {
  5415. isInternal = true;
  5416. }
  5417. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5418. {
  5419. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, usageCount, graphId);
  5420. }
  5421. };
  5422. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5423. {
  5424. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5425. }
  5426. //=================================================================================
  5427. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5428. {
  5429. protected:
  5430. IHThorGraphLoopResultReadArg &helper;
  5431. Owned<IRoxieInput> iter;
  5432. ILocalGraphEx * graph;
  5433. unsigned graphId;
  5434. unsigned sequence;
  5435. public:
  5436. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5437. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5438. {
  5439. graph = NULL;
  5440. sequence = 0;
  5441. }
  5442. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5443. {
  5444. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5445. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5446. }
  5447. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5448. {
  5449. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5450. if (iter)
  5451. iter->start(parentExtractSize, parentExtract, paused);
  5452. else
  5453. {
  5454. sequence = helper.querySequence();
  5455. if ((int)sequence >= 0)
  5456. {
  5457. try
  5458. {
  5459. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5460. }
  5461. catch (IException * E)
  5462. {
  5463. throw makeWrappedException(E);
  5464. }
  5465. }
  5466. }
  5467. }
  5468. virtual void stop(bool aborting)
  5469. {
  5470. if (iter)
  5471. iter->stop(aborting);
  5472. CRoxieServerActivity::stop(aborting);
  5473. }
  5474. virtual void reset()
  5475. {
  5476. CriticalBlock b(statecrit);
  5477. if (iter)
  5478. iter->reset();
  5479. iter.clear();
  5480. CRoxieServerActivity::reset();
  5481. };
  5482. virtual const void *nextInGroup()
  5483. {
  5484. CriticalBlock b(statecrit);
  5485. ActivityTimer t(totalCycles, timeActivities);
  5486. const void * next = iter ? iter->nextInGroup() : NULL;
  5487. if (next)
  5488. {
  5489. processed++;
  5490. atomic_inc(&rowsIn);
  5491. }
  5492. return next;
  5493. }
  5494. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5495. {
  5496. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5497. }
  5498. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5499. {
  5500. ensureCreated();
  5501. basehelper.onStart(parentExtract, NULL);
  5502. processor.noteUseIteration(helper.querySequence());
  5503. }
  5504. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5505. {
  5506. //helper already initialised from the gratherIterationUsage() call.
  5507. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5508. }
  5509. virtual IInputSteppingMeta * querySteppingMeta()
  5510. {
  5511. assertex(iter);
  5512. return iter->querySteppingMeta();
  5513. }
  5514. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5515. {
  5516. assertex(iter);
  5517. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5518. }
  5519. };
  5520. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5521. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5522. {
  5523. public:
  5524. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5525. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5526. {
  5527. sequence = _sequence;
  5528. }
  5529. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5530. {
  5531. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5532. if ((int)sequence >= 0)
  5533. {
  5534. try
  5535. {
  5536. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5537. }
  5538. catch (IException * E)
  5539. {
  5540. throw makeWrappedException(E);
  5541. }
  5542. }
  5543. }
  5544. };
  5545. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5546. {
  5547. unsigned graphId;
  5548. public:
  5549. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5550. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5551. {
  5552. }
  5553. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5554. {
  5555. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5556. }
  5557. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5558. {
  5559. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5560. }
  5561. };
  5562. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5563. {
  5564. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5565. }
  5566. //=====================================================================================================
  5567. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5568. {
  5569. IHThorGraphLoopResultWriteArg &helper;
  5570. ILocalGraphEx * graph;
  5571. unsigned graphId;
  5572. public:
  5573. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5574. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5575. {
  5576. graph = NULL;
  5577. }
  5578. virtual bool needsAllocator() const { return true; }
  5579. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5580. {
  5581. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5582. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5583. }
  5584. virtual void onExecute()
  5585. {
  5586. RtlLinkedDatasetBuilder builder(rowAllocator);
  5587. input->readAll(builder);
  5588. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5589. graph->setGraphLoopResult(result);
  5590. }
  5591. virtual IRoxieInput *queryOutput(unsigned idx)
  5592. {
  5593. if (idx==0)
  5594. return this;
  5595. else
  5596. return NULL;
  5597. }
  5598. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5599. {
  5600. return input->gatherConjunctions(collector);
  5601. }
  5602. virtual void resetEOF()
  5603. {
  5604. input->resetEOF();
  5605. }
  5606. virtual const void *nextInGroup()
  5607. {
  5608. const void * next = input->nextInGroup();
  5609. if (next)
  5610. processed++;
  5611. return next;
  5612. }
  5613. virtual bool isPassThrough()
  5614. {
  5615. return true;
  5616. }
  5617. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5618. {
  5619. ActivityTimer t(totalCycles, timeActivities);
  5620. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5621. if (next)
  5622. processed++;
  5623. return next;
  5624. }
  5625. IInputSteppingMeta * querySteppingMeta()
  5626. {
  5627. return input->querySteppingMeta();
  5628. }
  5629. virtual IOutputMetaData * queryOutputMeta() const
  5630. {
  5631. return input->queryOutputMeta();
  5632. }
  5633. };
  5634. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5635. {
  5636. unsigned graphId;
  5637. public:
  5638. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5639. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5640. {
  5641. isInternal = true;
  5642. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5643. }
  5644. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5645. {
  5646. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId, usageCount);
  5647. }
  5648. };
  5649. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5650. {
  5651. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5652. }
  5653. #if 0
  5654. //=====================================================================================================
  5655. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5656. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5657. {
  5658. next = NULL;
  5659. }
  5660. void CHThorLocalResultSpillActivity::ready()
  5661. {
  5662. CHThorSimpleActivityBase::ready();
  5663. next = input->nextInGroup();
  5664. grouped = input->isGrouped();
  5665. rowdata.clear();
  5666. }
  5667. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5668. {
  5669. const void * ret = next;
  5670. next = input->nextInGroup();
  5671. if (!ret && !next)
  5672. return NULL;
  5673. if (ret)
  5674. {
  5675. size32_t thisSize = outputMeta->getRecordSize(ret);
  5676. rowdata.append(thisSize, ret);
  5677. if (grouped)
  5678. rowdata.append(next == NULL);
  5679. }
  5680. return ret;
  5681. }
  5682. void CHThorLocalResultSpillActivity::done()
  5683. {
  5684. loop
  5685. {
  5686. const void * ret = nextInGroup();
  5687. if (!ret)
  5688. {
  5689. ret = nextInGroup();
  5690. if (!ret)
  5691. break;
  5692. }
  5693. ReleaseRoxieRow(ret);
  5694. }
  5695. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5696. CHThorSimpleActivityBase::done();
  5697. }
  5698. #endif
  5699. //=================================================================================
  5700. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5701. {
  5702. protected:
  5703. IHThorDedupArg &helper;
  5704. unsigned numKept;
  5705. unsigned numToKeep;
  5706. public:
  5707. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5708. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5709. {
  5710. numKept = 0;
  5711. numToKeep = 0;
  5712. }
  5713. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5714. {
  5715. numKept = 0;
  5716. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5717. numToKeep = helper.numToKeep();
  5718. }
  5719. };
  5720. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5721. {
  5722. IRangeCompare * stepCompare;
  5723. const void *prev;
  5724. public:
  5725. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5726. : CRoxieServerDedupActivity(_factory, _probeManager)
  5727. {
  5728. prev = NULL;
  5729. stepCompare = NULL;
  5730. }
  5731. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5732. {
  5733. prev = NULL;
  5734. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5735. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5736. stepCompare = NULL;
  5737. if (stepMeta)
  5738. stepCompare = stepMeta->queryCompare();
  5739. }
  5740. virtual void reset()
  5741. {
  5742. ReleaseClearRoxieRow(prev);
  5743. CRoxieServerDedupActivity::reset();
  5744. }
  5745. virtual const void * nextInGroup()
  5746. {
  5747. ActivityTimer t(totalCycles, timeActivities);
  5748. const void * next;
  5749. loop
  5750. {
  5751. next = input->nextInGroup();
  5752. if (!prev || !next || !helper.matches(prev,next))
  5753. {
  5754. numKept = 0;
  5755. break;
  5756. }
  5757. if (numKept < numToKeep-1)
  5758. {
  5759. numKept++;
  5760. break;
  5761. }
  5762. ReleaseRoxieRow(next);
  5763. }
  5764. ReleaseRoxieRow(prev);
  5765. prev = next;
  5766. if (next)
  5767. {
  5768. LinkRoxieRow(next);
  5769. processed++;
  5770. }
  5771. return next;
  5772. }
  5773. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5774. {
  5775. ActivityTimer t(totalCycles, timeActivities);
  5776. const void * next;
  5777. loop
  5778. {
  5779. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5780. //If the record was an in-exact match from the index then return it immediately
  5781. //and don't cause it to dedup following legal records.
  5782. if (!wasCompleteMatch)
  5783. {
  5784. assertex(stepExtra.returnMismatches());
  5785. return next;
  5786. }
  5787. if (!prev || !next || !helper.matches(prev,next))
  5788. {
  5789. numKept = 0;
  5790. break;
  5791. }
  5792. if (numKept < numToKeep-1)
  5793. {
  5794. numKept++;
  5795. break;
  5796. }
  5797. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5798. if (stepExtra.returnMismatches())
  5799. {
  5800. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5801. //condition to advance
  5802. if (stepCompare->docompare(next, seek, numFields) != 0)
  5803. {
  5804. wasCompleteMatch = false;
  5805. break;
  5806. }
  5807. }
  5808. ReleaseRoxieRow(next);
  5809. }
  5810. ReleaseRoxieRow(prev);
  5811. prev = next;
  5812. if (next)
  5813. {
  5814. LinkRoxieRow(next);
  5815. processed++;
  5816. }
  5817. return next;
  5818. }
  5819. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5820. {
  5821. return input->gatherConjunctions(collector);
  5822. }
  5823. virtual void resetEOF()
  5824. {
  5825. input->resetEOF();
  5826. }
  5827. IInputSteppingMeta * querySteppingMeta()
  5828. {
  5829. return input->querySteppingMeta();
  5830. }
  5831. };
  5832. //=================================================================================
  5833. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5834. {
  5835. const void *kept;
  5836. bool first;
  5837. public:
  5838. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5839. : CRoxieServerDedupActivity(_factory, _probeManager)
  5840. {
  5841. kept = NULL;
  5842. first = true;
  5843. }
  5844. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5845. {
  5846. first = true;
  5847. kept = NULL;
  5848. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5849. }
  5850. virtual void reset()
  5851. {
  5852. ReleaseClearRoxieRow(kept);
  5853. CRoxieServerActivity::reset();
  5854. }
  5855. virtual const void * nextInGroup()
  5856. {
  5857. ActivityTimer t(totalCycles, timeActivities);
  5858. if (first)
  5859. {
  5860. kept = input->nextInGroup();
  5861. first = false;
  5862. }
  5863. const void * next;
  5864. loop
  5865. {
  5866. next = input->nextInGroup();
  5867. if (!kept || !next || !helper.matches(kept,next))
  5868. {
  5869. numKept = 0;
  5870. break;
  5871. }
  5872. if (numKept < numToKeep-1)
  5873. {
  5874. numKept++;
  5875. break;
  5876. }
  5877. ReleaseRoxieRow(kept);
  5878. kept = next;
  5879. }
  5880. const void * ret = kept;
  5881. kept = next;
  5882. // CTXLOG("dedup returns %p", ret);
  5883. if (ret) processed++;
  5884. return ret;
  5885. }
  5886. };
  5887. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5888. {
  5889. IHThorDedupArg &helper;
  5890. unsigned survivorIndex;
  5891. ConstPointerArray survivors;
  5892. bool keepLeft;
  5893. bool eof;
  5894. bool first;
  5895. ICompare *primaryCompare;
  5896. public:
  5897. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5898. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5899. {
  5900. keepLeft = _keepLeft;
  5901. primaryCompare = helper.queryComparePrimary();
  5902. eof = false;
  5903. first = true;
  5904. survivorIndex = 0;
  5905. }
  5906. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5907. {
  5908. eof = false;
  5909. first = true;
  5910. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5911. }
  5912. virtual void reset()
  5913. {
  5914. #ifdef _DEBUG
  5915. while (survivors.isItem(survivorIndex))
  5916. {
  5917. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5918. }
  5919. #endif
  5920. survivors.kill();
  5921. eof = false;
  5922. first = true;
  5923. CRoxieServerActivity::reset();
  5924. }
  5925. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5926. {
  5927. for (unsigned idxL = first; idxL < last; idxL++)
  5928. {
  5929. const void * left = group.item(idxL);
  5930. if (left)
  5931. {
  5932. for (unsigned idxR = first; idxR < last; idxR++)
  5933. {
  5934. const void * right = group.item(idxR);
  5935. if ((idxL != idxR) && right)
  5936. {
  5937. if (helper.matches(left, right))
  5938. {
  5939. if (keepLeft)
  5940. {
  5941. group.replace(NULL, idxR);
  5942. ReleaseRoxieRow(right);
  5943. }
  5944. else
  5945. {
  5946. group.replace(NULL, idxL);
  5947. ReleaseRoxieRow(left);
  5948. break;
  5949. }
  5950. }
  5951. }
  5952. }
  5953. }
  5954. }
  5955. }
  5956. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5957. {
  5958. for (unsigned idxL = first; idxL < last; idxL++)
  5959. {
  5960. void * left = *(index[idxL]);
  5961. if (left)
  5962. {
  5963. for (unsigned idxR = first; idxR < last; idxR++)
  5964. {
  5965. void * right = *(index[idxR]);
  5966. if ((idxL != idxR) && right)
  5967. {
  5968. if (helper.matches(left, right))
  5969. {
  5970. if (keepLeft)
  5971. {
  5972. *(index[idxR]) = NULL;
  5973. ReleaseRoxieRow(right);
  5974. }
  5975. else
  5976. {
  5977. *(index[idxL]) = NULL;
  5978. ReleaseRoxieRow(left);
  5979. break;
  5980. }
  5981. }
  5982. }
  5983. }
  5984. }
  5985. }
  5986. }
  5987. bool calcNextDedupAll()
  5988. {
  5989. survivors.kill();
  5990. survivorIndex = 0;
  5991. ConstPointerArray group;
  5992. if (eof || !input->nextGroup(group))
  5993. {
  5994. eof = true;
  5995. return false;
  5996. }
  5997. unsigned max = group.ordinality();
  5998. if (primaryCompare)
  5999. {
  6000. //hard, if not impossible, to hit this code once optimisations in place
  6001. MemoryAttr indexbuff(max*sizeof(void **));
  6002. void *** index = (void ***)indexbuff.bufferBase();
  6003. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  6004. unsigned first = 0;
  6005. for (unsigned idx = 1; idx < max; idx++)
  6006. {
  6007. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  6008. {
  6009. dedupRangeIndirect(first, idx, index);
  6010. first = idx;
  6011. }
  6012. }
  6013. dedupRangeIndirect(first, max, index);
  6014. for(unsigned idx2=0; idx2<max; ++idx2)
  6015. {
  6016. void * cur = *(index[idx2]);
  6017. if(cur)
  6018. survivors.append(cur);
  6019. }
  6020. }
  6021. else
  6022. {
  6023. dedupRange(0, max, group);
  6024. for(unsigned idx=0; idx<max; ++idx)
  6025. {
  6026. const void * cur = group.item(idx);
  6027. if(cur)
  6028. survivors.append(cur);
  6029. }
  6030. }
  6031. return true;
  6032. }
  6033. virtual const void *nextInGroup()
  6034. {
  6035. ActivityTimer t(totalCycles, timeActivities);
  6036. if (first)
  6037. {
  6038. calcNextDedupAll();
  6039. first = false;
  6040. }
  6041. while (survivors.isItem(survivorIndex))
  6042. {
  6043. const void *ret = survivors.item(survivorIndex++);
  6044. if (ret)
  6045. {
  6046. processed++;
  6047. return ret;
  6048. }
  6049. }
  6050. calcNextDedupAll();
  6051. return NULL;
  6052. }
  6053. };
  6054. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6055. {
  6056. bool compareAll;
  6057. bool keepLeft;
  6058. public:
  6059. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6060. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6061. {
  6062. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6063. compareAll = helper->compareAll();
  6064. keepLeft = helper->keepLeft();
  6065. }
  6066. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6067. {
  6068. if (compareAll)
  6069. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  6070. else if (keepLeft)
  6071. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  6072. else
  6073. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  6074. }
  6075. };
  6076. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6077. {
  6078. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6079. }
  6080. //=================================================================================
  6081. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6082. {
  6083. bool eof;
  6084. IHThorHashDedupArg &helper;
  6085. class HashDedupElement
  6086. {
  6087. public:
  6088. HashDedupElement(unsigned _hash, const void *_keyRow)
  6089. : hash(_hash), keyRow(_keyRow)
  6090. {
  6091. }
  6092. ~HashDedupElement()
  6093. {
  6094. ReleaseRoxieRow(keyRow);
  6095. }
  6096. inline unsigned queryHash() const
  6097. {
  6098. return hash;
  6099. }
  6100. inline const void *queryRow() const
  6101. {
  6102. return keyRow;
  6103. }
  6104. private:
  6105. unsigned hash;
  6106. const void *keyRow;
  6107. };
  6108. class HashDedupTable : public SuperHashTable
  6109. {
  6110. public:
  6111. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6112. : helper(_helper),
  6113. activityId(_activityId),
  6114. keySize(helper.queryKeySize())
  6115. {
  6116. }
  6117. virtual ~HashDedupTable() { releaseAll(); }
  6118. virtual unsigned getHashFromElement(const void *et) const
  6119. {
  6120. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6121. return element->queryHash();
  6122. }
  6123. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6124. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6125. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6126. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6127. {
  6128. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6129. if (fphash != element->queryHash())
  6130. return false;
  6131. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6132. }
  6133. virtual void onAdd(void *et) {}
  6134. virtual void onRemove(void *et)
  6135. {
  6136. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6137. delete element;
  6138. }
  6139. void onCreate(IRoxieSlaveContext *ctx)
  6140. {
  6141. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6142. }
  6143. void reset()
  6144. {
  6145. kill();
  6146. }
  6147. bool insert(const void * row)
  6148. {
  6149. unsigned hash = helper.queryHash()->hash(row);
  6150. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6151. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6152. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6153. if (find(hash, keyRow.get()))
  6154. return false;
  6155. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6156. return true;
  6157. }
  6158. private:
  6159. IHThorHashDedupArg & helper;
  6160. CachedOutputMetaData keySize;
  6161. Owned<IEngineRowAllocator> keyRowAllocator;
  6162. unsigned activityId;
  6163. } table;
  6164. public:
  6165. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6166. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6167. {
  6168. eof = false;
  6169. }
  6170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6171. {
  6172. eof = false;
  6173. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6174. }
  6175. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6176. {
  6177. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6178. table.onCreate(ctx);
  6179. }
  6180. virtual void reset()
  6181. {
  6182. table.reset();
  6183. eof = false;
  6184. CRoxieServerActivity::reset();
  6185. }
  6186. virtual const void *nextInGroup()
  6187. {
  6188. ActivityTimer t(totalCycles, timeActivities);
  6189. while(!eof)
  6190. {
  6191. const void * next = input->nextInGroup();
  6192. if(!next)
  6193. {
  6194. if (table.count() == 0)
  6195. eof = true;
  6196. table.reset();
  6197. return NULL;
  6198. }
  6199. if(table.insert(next))
  6200. return next;
  6201. else
  6202. ReleaseRoxieRow(next);
  6203. }
  6204. return NULL;
  6205. }
  6206. };
  6207. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6208. {
  6209. public:
  6210. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6211. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6212. {
  6213. }
  6214. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6215. {
  6216. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6217. }
  6218. };
  6219. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6220. {
  6221. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6222. }
  6223. //=================================================================================
  6224. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6225. {
  6226. IHThorRollupArg &helper;
  6227. OwnedConstRoxieRow left;
  6228. OwnedConstRoxieRow prev;
  6229. OwnedConstRoxieRow right;
  6230. bool readFirstRow;
  6231. public:
  6232. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6233. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6234. {
  6235. readFirstRow = false;
  6236. }
  6237. ~CRoxieServerRollupActivity()
  6238. {
  6239. }
  6240. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6241. {
  6242. readFirstRow = false;
  6243. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6244. }
  6245. virtual void reset()
  6246. {
  6247. left.clear();
  6248. prev.clear();
  6249. right.clear();
  6250. CRoxieServerActivity::reset();
  6251. }
  6252. virtual bool needsAllocator() const { return true; }
  6253. virtual const void * nextInGroup()
  6254. {
  6255. ActivityTimer t(totalCycles, timeActivities);
  6256. if (!readFirstRow)
  6257. {
  6258. left.setown(input->nextInGroup());
  6259. prev.set(left);
  6260. readFirstRow = true;
  6261. }
  6262. loop
  6263. {
  6264. right.setown(input->nextInGroup());
  6265. if(!prev || !right || !helper.matches(prev,right))
  6266. {
  6267. const void * ret = left.getClear();
  6268. if(ret)
  6269. processed++;
  6270. left.setown(right.getClear());
  6271. prev.set(left);
  6272. return ret;
  6273. }
  6274. try
  6275. {
  6276. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6277. unsigned outSize = helper.transform(rowBuilder, left, right);
  6278. if (outSize)
  6279. left.setown(rowBuilder.finalizeRowClear(outSize));
  6280. if (helper.getFlags() & RFrolledismatchleft)
  6281. prev.set(left);
  6282. else
  6283. prev.set(right);
  6284. }
  6285. catch(IException * E)
  6286. {
  6287. throw makeWrappedException(E);
  6288. }
  6289. }
  6290. }
  6291. };
  6292. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6293. {
  6294. public:
  6295. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6296. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6297. {
  6298. }
  6299. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6300. {
  6301. return new CRoxieServerRollupActivity(this, _probeManager);
  6302. }
  6303. };
  6304. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6305. {
  6306. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6307. }
  6308. //=================================================================================
  6309. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6310. {
  6311. IHThorNormalizeArg &helper;
  6312. unsigned numThisRow;
  6313. unsigned curRow;
  6314. const void *buffer;
  6315. unsigned numProcessedLastGroup;
  6316. public:
  6317. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6318. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6319. {
  6320. buffer = NULL;
  6321. numThisRow = 0;
  6322. curRow = 0;
  6323. numProcessedLastGroup = 0;
  6324. }
  6325. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6326. {
  6327. numThisRow = 0;
  6328. curRow = 0;
  6329. numProcessedLastGroup = 0;
  6330. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6331. }
  6332. virtual void reset()
  6333. {
  6334. ReleaseClearRoxieRow(buffer);
  6335. CRoxieServerActivity::reset();
  6336. }
  6337. virtual bool needsAllocator() const { return true; }
  6338. virtual const void * nextInGroup()
  6339. {
  6340. ActivityTimer t(totalCycles, timeActivities);
  6341. loop
  6342. {
  6343. while (curRow == numThisRow)
  6344. {
  6345. if (buffer)
  6346. ReleaseClearRoxieRow(buffer);
  6347. buffer = input->nextInGroup();
  6348. if (!buffer && (processed == numProcessedLastGroup))
  6349. buffer = input->nextInGroup();
  6350. if (!buffer)
  6351. {
  6352. numProcessedLastGroup = processed;
  6353. return NULL;
  6354. }
  6355. curRow = 0;
  6356. numThisRow = helper.numExpandedRows(buffer);
  6357. }
  6358. try
  6359. {
  6360. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6361. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6362. if (actualSize != 0)
  6363. {
  6364. processed++;
  6365. return rowBuilder.finalizeRowClear(actualSize);
  6366. }
  6367. }
  6368. catch (IException *E)
  6369. {
  6370. throw makeWrappedException(E);
  6371. }
  6372. }
  6373. }
  6374. };
  6375. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6376. {
  6377. public:
  6378. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6379. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6380. {
  6381. }
  6382. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6383. {
  6384. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6385. }
  6386. };
  6387. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6388. {
  6389. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6390. }
  6391. //=================================================================================
  6392. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6393. {
  6394. IHThorNormalizeChildArg &helper;
  6395. unsigned numThisRow;
  6396. unsigned curRow;
  6397. const void *buffer;
  6398. unsigned numProcessedLastGroup;
  6399. INormalizeChildIterator * cursor;
  6400. const void * curChildRow;
  6401. bool advanceInput()
  6402. {
  6403. loop
  6404. {
  6405. ReleaseClearRoxieRow(buffer);
  6406. buffer = input->nextInGroup();
  6407. if (!buffer && (processed == numProcessedLastGroup))
  6408. buffer = input->nextInGroup();
  6409. if (!buffer)
  6410. {
  6411. numProcessedLastGroup = processed;
  6412. return false;
  6413. }
  6414. curChildRow = cursor->first(buffer);
  6415. if (curChildRow)
  6416. {
  6417. curRow = 0;
  6418. return true;
  6419. }
  6420. }
  6421. }
  6422. public:
  6423. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6424. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6425. {
  6426. buffer = NULL;
  6427. cursor = NULL;
  6428. numThisRow = 0;
  6429. curRow = 0;
  6430. numProcessedLastGroup = 0;
  6431. curChildRow = NULL;
  6432. }
  6433. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6434. {
  6435. numThisRow = 0;
  6436. curRow = 0;
  6437. numProcessedLastGroup = 0;
  6438. curChildRow = NULL;
  6439. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6440. cursor = helper.queryIterator();
  6441. }
  6442. virtual void stop(bool aborting)
  6443. {
  6444. CRoxieServerActivity::stop(aborting);
  6445. }
  6446. virtual void reset()
  6447. {
  6448. cursor = NULL;
  6449. ReleaseClearRoxieRow(buffer);
  6450. CRoxieServerActivity::reset();
  6451. }
  6452. virtual bool needsAllocator() const { return true; }
  6453. const void *nextInGroup()
  6454. {
  6455. ActivityTimer t(totalCycles, timeActivities);
  6456. loop
  6457. {
  6458. if (!buffer)
  6459. {
  6460. if (!advanceInput())
  6461. return NULL;
  6462. }
  6463. try
  6464. {
  6465. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6466. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6467. curChildRow = cursor->next();
  6468. if (!curChildRow)
  6469. ReleaseClearRoxieRow(buffer);
  6470. if (outSize != 0)
  6471. {
  6472. processed++;
  6473. return rowBuilder.finalizeRowClear(outSize);
  6474. }
  6475. }
  6476. catch (IException *E)
  6477. {
  6478. throw makeWrappedException(E);
  6479. }
  6480. }
  6481. }
  6482. };
  6483. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6484. {
  6485. public:
  6486. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6488. {
  6489. }
  6490. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6491. {
  6492. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6493. }
  6494. };
  6495. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6496. {
  6497. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6498. }
  6499. //=================================================================================
  6500. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6501. {
  6502. IHThorNormalizeLinkedChildArg &helper;
  6503. OwnedConstRoxieRow curParent;
  6504. OwnedConstRoxieRow curChild;
  6505. unsigned numProcessedLastGroup;
  6506. bool advanceInput()
  6507. {
  6508. loop
  6509. {
  6510. curParent.setown(input->nextInGroup());
  6511. if (!curParent && (processed == numProcessedLastGroup))
  6512. curParent.setown(input->nextInGroup());
  6513. if (!curParent)
  6514. {
  6515. numProcessedLastGroup = processed;
  6516. return false;
  6517. }
  6518. curChild.set(helper.first(curParent));
  6519. if (curChild)
  6520. return true;
  6521. }
  6522. }
  6523. public:
  6524. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6525. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6526. {
  6527. numProcessedLastGroup = 0;
  6528. }
  6529. ~CRoxieServerNormalizeLinkedChildActivity()
  6530. {
  6531. }
  6532. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6533. {
  6534. numProcessedLastGroup = 0;
  6535. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6536. }
  6537. virtual void reset()
  6538. {
  6539. curParent.clear();
  6540. curChild.clear();
  6541. CRoxieServerActivity::reset();
  6542. }
  6543. const void *nextInGroup()
  6544. {
  6545. ActivityTimer t(totalCycles, timeActivities);
  6546. loop
  6547. {
  6548. if (!curParent)
  6549. {
  6550. if (!advanceInput())
  6551. return NULL;
  6552. }
  6553. try
  6554. {
  6555. const void *ret = curChild.getClear();
  6556. curChild.set(helper.next());
  6557. if (!curChild)
  6558. curParent.clear();
  6559. if (ret)
  6560. {
  6561. processed++;
  6562. return ret;
  6563. }
  6564. }
  6565. catch (IException *E)
  6566. {
  6567. throw makeWrappedException(E);
  6568. }
  6569. }
  6570. }
  6571. };
  6572. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6573. {
  6574. public:
  6575. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6576. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6577. {
  6578. }
  6579. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6580. {
  6581. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6582. }
  6583. };
  6584. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6585. {
  6586. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6587. }
  6588. //=================================================================================
  6589. interface ISortAlgorithm : extends IInterface
  6590. {
  6591. virtual void prepare(IRoxieInput *input) = 0;
  6592. virtual const void *next() = 0;
  6593. virtual void reset() = 0;
  6594. };
  6595. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6596. {
  6597. protected:
  6598. unsigned curIndex;
  6599. ConstPointerArray sorted;
  6600. ICompare *compare;
  6601. public:
  6602. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6603. {
  6604. curIndex = 0;
  6605. }
  6606. virtual void prepare(IRoxieInput *input)
  6607. {
  6608. curIndex = 0;
  6609. if (input->nextGroup(sorted))
  6610. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6611. }
  6612. virtual const void *next()
  6613. {
  6614. if (sorted.isItem(curIndex))
  6615. return sorted.item(curIndex++);
  6616. return NULL;
  6617. }
  6618. virtual void reset()
  6619. {
  6620. while (sorted.isItem(curIndex))
  6621. ReleaseRoxieRow(sorted.item(curIndex++));
  6622. curIndex = 0;
  6623. sorted.kill();
  6624. }
  6625. };
  6626. class CStableQuickSortAlgorithm : public CQuickSortAlgorithm
  6627. {
  6628. public:
  6629. CStableQuickSortAlgorithm(ICompare *_compare) : CQuickSortAlgorithm(_compare)
  6630. {
  6631. }
  6632. virtual void prepare(IRoxieInput *input)
  6633. {
  6634. curIndex = 0;
  6635. if (input->nextGroup(sorted))
  6636. {
  6637. unsigned numRows = sorted.ordinality();
  6638. void **rows = const_cast<void * *>(sorted.getArray());
  6639. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6640. void **temp = (void **) tempAttr.bufferBase();
  6641. memcpy(temp, rows, numRows*sizeof(void **));
  6642. qsortvecstable(temp, numRows, *compare, (void ***)rows);
  6643. for (unsigned i = 0; i < numRows; i++)
  6644. {
  6645. *rows = **((void ***)rows);
  6646. rows++;
  6647. }
  6648. }
  6649. }
  6650. };
  6651. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6652. {
  6653. enum {
  6654. InitialSortElements = 0,
  6655. //The number of rows that can be added without entering a critical section, and therefore also the number
  6656. //of rows that might not get freed when memory gets tight.
  6657. CommitStep=32
  6658. };
  6659. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6660. roxiemem::RoxieSimpleInputRowArray sorted;
  6661. ICompare *compare;
  6662. IRoxieSlaveContext * ctx;
  6663. Owned<IDiskMerger> diskMerger;
  6664. Owned<IRowStream> diskReader;
  6665. IOutputMetaData *rowMeta;
  6666. unsigned activityId;
  6667. bool stable;
  6668. public:
  6669. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId, bool _stable)
  6670. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep, _activityId),
  6671. ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId), stable(_stable)
  6672. {
  6673. ctx->queryRowManager().addRowBuffer(this);
  6674. }
  6675. ~CSpillingQuickSortAlgorithm()
  6676. {
  6677. ctx->queryRowManager().removeRowBuffer(this);
  6678. diskReader.clear();
  6679. }
  6680. virtual void prepare(IRoxieInput *input)
  6681. {
  6682. loop
  6683. {
  6684. const void * next = input->nextInGroup();
  6685. if (!next)
  6686. break;
  6687. if (!rowsToSort.append(next))
  6688. {
  6689. {
  6690. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6691. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6692. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6693. //rows first).
  6694. if (rowsToSort.numCommitted() != 0)
  6695. {
  6696. rowsToSort.flush();
  6697. spillRows();
  6698. }
  6699. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6700. //spillRows() cannot shift active row pointer since it can be called from any thread
  6701. rowsToSort.flush();
  6702. }
  6703. if (!rowsToSort.append(next))
  6704. {
  6705. ReleaseRoxieRow(next);
  6706. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6707. }
  6708. }
  6709. }
  6710. rowsToSort.flush();
  6711. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6712. if (diskMerger)
  6713. {
  6714. spillRows();
  6715. rowsToSort.kill();
  6716. diskReader.setown(diskMerger->merge(compare));
  6717. }
  6718. else
  6719. {
  6720. unsigned numRows = rowsToSort.numCommitted();
  6721. if (numRows)
  6722. {
  6723. void ** rows = const_cast<void * *>(rowsToSort.getBlock(numRows));
  6724. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6725. if (stable)
  6726. {
  6727. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6728. void **temp = (void **) tempAttr.bufferBase();
  6729. memcpy(temp, rows, numRows*sizeof(void **));
  6730. qsortvecstable(temp, numRows, *compare, (void ***)rows);
  6731. for (unsigned i = 0; i < numRows; i++)
  6732. {
  6733. *rows = **((void ***)rows);
  6734. rows++;
  6735. }
  6736. }
  6737. else
  6738. qsortvec(rows, numRows, *compare);
  6739. }
  6740. sorted.transferFrom(rowsToSort);
  6741. }
  6742. }
  6743. virtual const void *next()
  6744. {
  6745. if(diskReader)
  6746. return diskReader->nextRow();
  6747. return sorted.dequeue();
  6748. }
  6749. virtual void reset()
  6750. {
  6751. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6752. //fewer heap allocations with not freeing up the memory from large group sorts.
  6753. rowsToSort.clearRows();
  6754. sorted.kill();
  6755. //Disk reader must be cleared before the merger - or the files may still be locked.
  6756. diskReader.clear();
  6757. diskMerger.clear();
  6758. }
  6759. //interface roxiemem::IBufferedRowCallback
  6760. virtual unsigned getSpillCost() const
  6761. {
  6762. //Spill global sorts before grouped sorts
  6763. if (rowMeta->isGrouped())
  6764. return 20;
  6765. return 10;
  6766. }
  6767. virtual bool freeBufferedRows(bool critical)
  6768. {
  6769. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6770. return spillRows();
  6771. }
  6772. protected:
  6773. bool spillRows()
  6774. {
  6775. unsigned numRows = rowsToSort.numCommitted();
  6776. if (numRows == 0)
  6777. return false;
  6778. const void * * rows = rowsToSort.getBlock(numRows);
  6779. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6780. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6781. for (unsigned i= 0; i < numRows; i++)
  6782. {
  6783. out->putRow(rows[i]);
  6784. }
  6785. rowsToSort.noteSpilled(numRows);
  6786. return true;
  6787. }
  6788. IDiskMerger * queryMerger()
  6789. {
  6790. if (!diskMerger)
  6791. {
  6792. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6793. StringBuffer spillBasename;
  6794. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%" I64F "u", seq);
  6795. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6796. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6797. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6798. }
  6799. return diskMerger;
  6800. }
  6801. };
  6802. #define INSERTION_SORT_BLOCKSIZE 1024
  6803. class SortedBlock : public CInterface, implements IInterface
  6804. {
  6805. unsigned sequence;
  6806. const void **rows;
  6807. unsigned length;
  6808. unsigned pos;
  6809. SortedBlock(const SortedBlock &);
  6810. public:
  6811. IMPLEMENT_IINTERFACE;
  6812. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6813. {
  6814. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6815. length = 0;
  6816. pos = 0;
  6817. }
  6818. ~SortedBlock()
  6819. {
  6820. while (pos < length)
  6821. ReleaseRoxieRow(rows[pos++]);
  6822. ReleaseRoxieRow(rows);
  6823. }
  6824. int compareTo(SortedBlock *r, ICompare *compare)
  6825. {
  6826. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6827. if (!rc)
  6828. rc = sequence - r->sequence;
  6829. return rc;
  6830. }
  6831. const void *next()
  6832. {
  6833. if (pos < length)
  6834. return rows[pos++];
  6835. else
  6836. return NULL;
  6837. }
  6838. inline bool eof()
  6839. {
  6840. return pos==length;
  6841. }
  6842. bool insert(const void *next, ICompare *_compare )
  6843. {
  6844. unsigned b = length;
  6845. if (b == INSERTION_SORT_BLOCKSIZE)
  6846. return false;
  6847. else if (b < 7)
  6848. {
  6849. while (b)
  6850. {
  6851. if (_compare->docompare(next, rows[b-1]) >= 0)
  6852. break;
  6853. b--;
  6854. }
  6855. if (b != length)
  6856. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6857. rows[b] = next;
  6858. length++;
  6859. return true;
  6860. }
  6861. else
  6862. {
  6863. unsigned int a = 0;
  6864. while ((int)a<b)
  6865. {
  6866. int i = (a+b)/2;
  6867. int rc = _compare->docompare(next, rows[i]);
  6868. if (rc>=0)
  6869. a = i+1;
  6870. else
  6871. b = i;
  6872. }
  6873. if (a != length)
  6874. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6875. rows[a] = next;
  6876. length++;
  6877. return true;
  6878. }
  6879. }
  6880. };
  6881. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6882. {
  6883. SortedBlock *curBlock;
  6884. unsigned blockNo;
  6885. IArrayOf<SortedBlock> blocks;
  6886. unsigned activityId;
  6887. IRowManager *rowManager;
  6888. ICompare *compare;
  6889. void newBlock()
  6890. {
  6891. blocks.append(*curBlock);
  6892. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6893. }
  6894. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6895. {
  6896. return l.compareTo(&r, compare);
  6897. }
  6898. void makeHeap()
  6899. {
  6900. /* Permute blocks to establish the heap property
  6901. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6902. The children of p must both be greater than or equal to p
  6903. The parent of a child c is given by p = (c-1)/2
  6904. */
  6905. unsigned i;
  6906. unsigned n = blocks.length();
  6907. SortedBlock **s = blocks.getArray();
  6908. for (i=1; i<n; i++)
  6909. {
  6910. SortedBlock * r = s[i];
  6911. int c = i; /* child */
  6912. while (c > 0)
  6913. {
  6914. int p = (c-1)/2; /* parent */
  6915. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6916. break;
  6917. s[c] = s[p];
  6918. s[p] = r;
  6919. c = p;
  6920. }
  6921. }
  6922. }
  6923. void remakeHeap()
  6924. {
  6925. /* The row associated with block[0] will have changed
  6926. This code restores the heap property
  6927. */
  6928. unsigned p = 0; /* parent */
  6929. unsigned n = blocks.length();
  6930. SortedBlock **s = blocks.getArray();
  6931. while (1)
  6932. {
  6933. unsigned c = p*2 + 1; /* child */
  6934. if ( c >= n )
  6935. break;
  6936. /* Select smaller child */
  6937. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6938. /* If child is greater or equal than parent then we are done */
  6939. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6940. break;
  6941. /* Swap parent and child */
  6942. SortedBlock *r = s[c];
  6943. s[c] = s[p];
  6944. s[p] = r;
  6945. /* child becomes parent */
  6946. p = c;
  6947. }
  6948. }
  6949. public:
  6950. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6951. : compare(_compare)
  6952. {
  6953. rowManager = _rowManager;
  6954. activityId = _activityId;
  6955. curBlock = NULL;
  6956. blockNo = 0;
  6957. }
  6958. virtual void reset()
  6959. {
  6960. blocks.kill();
  6961. delete curBlock;
  6962. curBlock = NULL;
  6963. blockNo = 0;
  6964. }
  6965. virtual void prepare(IRoxieInput *input)
  6966. {
  6967. blockNo = 0;
  6968. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6969. loop
  6970. {
  6971. const void *next = input->nextInGroup();
  6972. if (!next)
  6973. break;
  6974. if (!curBlock->insert(next, compare))
  6975. {
  6976. newBlock();
  6977. curBlock->insert(next, compare);
  6978. }
  6979. }
  6980. if (blockNo > 1)
  6981. {
  6982. blocks.append(*curBlock);
  6983. curBlock = NULL;
  6984. makeHeap();
  6985. }
  6986. }
  6987. virtual const void * next()
  6988. {
  6989. const void *ret;
  6990. if (blockNo==1) // single block case..
  6991. {
  6992. ret = curBlock->next();
  6993. }
  6994. else if (blocks.length())
  6995. {
  6996. SortedBlock &top = blocks.item(0);
  6997. ret = top.next();
  6998. if (top.eof())
  6999. blocks.replace(blocks.popGet(), 0);
  7000. remakeHeap();
  7001. }
  7002. else
  7003. ret = NULL;
  7004. return ret;
  7005. }
  7006. };
  7007. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  7008. {
  7009. unsigned curIndex;
  7010. ConstPointerArray sorted;
  7011. bool inputAlreadySorted;
  7012. IntArray sequences;
  7013. bool eof;
  7014. ICompare *compare;
  7015. #ifdef _CHECK_HEAPSORT
  7016. void checkHeap() const
  7017. {
  7018. unsigned n = sorted.ordinality();
  7019. if (n)
  7020. {
  7021. ICompare *_compare = compare;
  7022. void **s = sorted.getArray();
  7023. int *sq = sequences.getArray();
  7024. unsigned p;
  7025. #if 0
  7026. CTXLOG("------------------------%d entries-----------------", n);
  7027. for (p = 0; p < n; p++)
  7028. {
  7029. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  7030. }
  7031. #endif
  7032. for (p = 0; p < n; p++)
  7033. {
  7034. unsigned c = p*2+1;
  7035. if (c<n)
  7036. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7037. c++;
  7038. if (c<n)
  7039. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7040. }
  7041. }
  7042. }
  7043. #else
  7044. inline void checkHeap() const {}
  7045. #endif
  7046. const void *removeHeap()
  7047. {
  7048. unsigned n = sorted.ordinality();
  7049. if (n)
  7050. {
  7051. const void *ret = sorted.item(0);
  7052. if (n > 1 && ret)
  7053. {
  7054. ICompare *_compare = compare;
  7055. const void **s = sorted.getArray();
  7056. int *sq = sequences.getArray();
  7057. unsigned v = 0; // vacancy
  7058. loop
  7059. {
  7060. unsigned c = 2*v + 1;
  7061. if (c < n)
  7062. {
  7063. unsigned f = c; // favourite to fill it
  7064. c++;
  7065. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  7066. f = c;
  7067. sq[v] = sq[f];
  7068. if ((s[v] = s[f]) != NULL)
  7069. v = f;
  7070. else
  7071. break;
  7072. }
  7073. else
  7074. {
  7075. s[v] = NULL;
  7076. break;
  7077. }
  7078. }
  7079. }
  7080. checkHeap();
  7081. return ret;
  7082. }
  7083. else
  7084. return NULL;
  7085. }
  7086. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  7087. {
  7088. int rc = _compare->docompare(s[l], s[r]);
  7089. if (!rc)
  7090. rc = sq[l] - sq[r];
  7091. return rc;
  7092. }
  7093. void insertHeap(const void *next)
  7094. {
  7095. // Upside-down heap sort
  7096. // Maintain a heap where every parent is lower than each of its children
  7097. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  7098. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  7099. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  7100. // Nice features:
  7101. // 1. Deterministic
  7102. // 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
  7103. // 3. Already sorted case can be spotted at zero cost while reading.
  7104. // 4. If you don't read all the results, you don't have to complete the sort
  7105. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  7106. unsigned n = sorted.ordinality();
  7107. sorted.append(next);
  7108. sequences.append(n);
  7109. if (!n)
  7110. return;
  7111. ICompare *_compare = compare;
  7112. const void **s = sorted.getArray();
  7113. if (inputAlreadySorted)
  7114. {
  7115. if (_compare->docompare(next, s[n-1]) >= 0)
  7116. return;
  7117. else
  7118. {
  7119. // MORE - could delay creating sequences until now...
  7120. inputAlreadySorted = false;
  7121. }
  7122. }
  7123. int *sq = sequences.getArray();
  7124. unsigned q = n;
  7125. while (n)
  7126. {
  7127. unsigned parent = (n-1) / 2;
  7128. const void *p = s[parent];
  7129. if (_compare->docompare(p, next) <= 0)
  7130. break;
  7131. s[n] = p;
  7132. sq[n] = sq[parent];
  7133. s[parent] = next;
  7134. sq[parent] = q;
  7135. n = parent;
  7136. }
  7137. }
  7138. public:
  7139. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  7140. {
  7141. inputAlreadySorted = true;
  7142. curIndex = 0;
  7143. eof = false;
  7144. }
  7145. virtual void reset()
  7146. {
  7147. eof = false;
  7148. if (inputAlreadySorted)
  7149. {
  7150. while (sorted.isItem(curIndex))
  7151. ReleaseRoxieRow(sorted.item(curIndex++));
  7152. sorted.kill();
  7153. }
  7154. else
  7155. {
  7156. ReleaseRoxieRowSet(sorted);
  7157. }
  7158. inputAlreadySorted = true;
  7159. sequences.kill();
  7160. }
  7161. virtual void prepare(IRoxieInput *input)
  7162. {
  7163. inputAlreadySorted = true;
  7164. curIndex = 0;
  7165. eof = false;
  7166. assertex(sorted.ordinality()==0);
  7167. const void *next = input->nextInGroup();
  7168. if (!next)
  7169. {
  7170. eof = true;
  7171. return;
  7172. }
  7173. loop
  7174. {
  7175. insertHeap(next);
  7176. next = input->nextInGroup();
  7177. if (!next)
  7178. break;
  7179. }
  7180. checkHeap();
  7181. }
  7182. virtual const void * next()
  7183. {
  7184. if (inputAlreadySorted)
  7185. {
  7186. if (sorted.isItem(curIndex))
  7187. {
  7188. return sorted.item(curIndex++);
  7189. }
  7190. else
  7191. return NULL;
  7192. }
  7193. else
  7194. return removeHeap();
  7195. }
  7196. };
  7197. typedef enum {heapSort, insertionSort, quickSort, stableQuickSort, spillingQuickSort, stableSpillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7198. class CRoxieServerSortActivity : public CRoxieServerActivity
  7199. {
  7200. protected:
  7201. IHThorSortArg &helper;
  7202. ICompare *compare;
  7203. Owned<ISortAlgorithm> sorter;
  7204. bool readInput;
  7205. RoxieSortAlgorithm sortAlgorithm;
  7206. unsigned sortFlags;
  7207. public:
  7208. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7209. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7210. {
  7211. compare = helper.queryCompare();
  7212. readInput = false;
  7213. }
  7214. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7215. {
  7216. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7217. switch (sortAlgorithm)
  7218. {
  7219. case heapSort:
  7220. sorter.setown(new CHeapSortAlgorithm(compare));
  7221. break;
  7222. case insertionSort:
  7223. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7224. break;
  7225. case quickSort:
  7226. sorter.setown(new CQuickSortAlgorithm(compare));
  7227. break;
  7228. case stableQuickSort:
  7229. sorter.setown(new CStableQuickSortAlgorithm(compare));
  7230. break;
  7231. case spillingQuickSort:
  7232. case stableSpillingQuickSort:
  7233. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, sortAlgorithm==stableSpillingQuickSort));
  7234. break;
  7235. case unknownSort:
  7236. sorter.clear(); // create it later....
  7237. break;
  7238. default:
  7239. throwUnexpected();
  7240. break;
  7241. }
  7242. }
  7243. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7244. {
  7245. assertex(!readInput);
  7246. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7247. }
  7248. virtual void reset()
  7249. {
  7250. if (sorter)
  7251. sorter->reset();
  7252. readInput = false;
  7253. CRoxieServerActivity::reset();
  7254. }
  7255. virtual const void * nextInGroup()
  7256. {
  7257. ActivityTimer t(totalCycles, timeActivities);
  7258. if (!readInput)
  7259. {
  7260. if (sortAlgorithm == unknownSort)
  7261. {
  7262. sorter.clear();
  7263. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7264. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7265. if (useAlgorithm)
  7266. {
  7267. if (stricmp(useAlgorithm, "quicksort")==0)
  7268. {
  7269. switch (sortFlags & (TAFstable|TAFspill))
  7270. {
  7271. case 0: sortAlgorithm = quickSort; break;
  7272. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7273. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7274. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7275. }
  7276. }
  7277. else if (stricmp(useAlgorithm, "heapsort")==0)
  7278. sorter.setown(new CHeapSortAlgorithm(compare));
  7279. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7280. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7281. else
  7282. {
  7283. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7284. if (sortFlags & TAFspill)
  7285. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, (sortFlags & TAFstable) != 0));
  7286. else if (sortFlags & TAFunstable)
  7287. sorter.setown(new CQuickSortAlgorithm(compare));
  7288. else
  7289. sorter.setown(new CHeapSortAlgorithm(compare));
  7290. }
  7291. }
  7292. else
  7293. 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...
  7294. }
  7295. sorter->prepare(input);
  7296. readInput = true;
  7297. }
  7298. const void *ret = sorter->next();
  7299. if (ret)
  7300. processed++;
  7301. else
  7302. {
  7303. sorter->reset();
  7304. readInput = false; // ready for next group
  7305. }
  7306. return ret;
  7307. }
  7308. };
  7309. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7310. {
  7311. RoxieSortAlgorithm sortAlgorithm;
  7312. unsigned sortFlags;
  7313. bool forceSpill;
  7314. public:
  7315. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7316. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7317. {
  7318. forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  7319. if (forceSpill)
  7320. {
  7321. sortAlgorithm = stableSpillingQuickSort;
  7322. sortFlags = TAFstable|TAFspill;
  7323. }
  7324. else
  7325. {
  7326. sortAlgorithm = heapSort;
  7327. sortFlags = TAFstable;
  7328. }
  7329. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7330. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7331. if (sortMethod)
  7332. {
  7333. sortFlags = sortMethod->getAlgorithmFlags();
  7334. if (forceSpill)
  7335. sortFlags |= TAFspill;
  7336. if (sortFlags & TAFspill)
  7337. sortAlgorithm = stableSpillingQuickSort;
  7338. else if (sortFlags & TAFunstable)
  7339. sortAlgorithm = quickSort;
  7340. if (!(sortFlags & TAFconstant))
  7341. sortAlgorithm = unknownSort;
  7342. else
  7343. {
  7344. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7345. if (useAlgorithm)
  7346. {
  7347. if (stricmp(useAlgorithm, "quicksort")==0)
  7348. {
  7349. switch (sortFlags & (TAFstable|TAFspill))
  7350. {
  7351. case 0: sortAlgorithm = quickSort; break;
  7352. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7353. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7354. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7355. }
  7356. }
  7357. else if (stricmp(useAlgorithm, "heapsort")==0)
  7358. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7359. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7360. sortAlgorithm = insertionSort;
  7361. else
  7362. {
  7363. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7364. if (sortFlags & TAFunstable)
  7365. sortAlgorithm = quickSort;
  7366. else
  7367. sortAlgorithm = heapSort;
  7368. }
  7369. }
  7370. }
  7371. }
  7372. }
  7373. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7374. {
  7375. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7376. }
  7377. };
  7378. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7379. {
  7380. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7381. }
  7382. //=====================================================================================================
  7383. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7384. {
  7385. IHThorSortedArg &helper;
  7386. ICompare * compare;
  7387. const void *prev;
  7388. IRangeCompare * stepCompare;
  7389. public:
  7390. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7391. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7392. {
  7393. prev = NULL;
  7394. compare = helper.queryCompare();
  7395. stepCompare = NULL;
  7396. }
  7397. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7398. {
  7399. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7400. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7401. if (stepMeta)
  7402. stepCompare = stepMeta->queryCompare();
  7403. prev = NULL;
  7404. }
  7405. virtual void reset()
  7406. {
  7407. ReleaseClearRoxieRow(prev);
  7408. CRoxieServerActivity::reset();
  7409. }
  7410. virtual const void * nextInGroup()
  7411. {
  7412. ActivityTimer t(totalCycles, timeActivities);
  7413. const void *ret = input->nextInGroup();
  7414. if (ret && prev && compare->docompare(prev, ret) > 0)
  7415. {
  7416. // MORE - better to give mismatching rows that indexes?
  7417. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7418. }
  7419. ReleaseRoxieRow(prev);
  7420. prev = ret;
  7421. if (ret)
  7422. {
  7423. LinkRoxieRow(prev);
  7424. processed++;
  7425. }
  7426. return ret;
  7427. }
  7428. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7429. {
  7430. ActivityTimer t(totalCycles, timeActivities);
  7431. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7432. if (ret && prev && compare->docompare(prev, ret) > 0)
  7433. {
  7434. // MORE - better to give mismatching rows that indexes?
  7435. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7436. }
  7437. ReleaseRoxieRow(prev);
  7438. prev = ret;
  7439. if (ret)
  7440. {
  7441. LinkRoxieRow(prev);
  7442. processed++;
  7443. }
  7444. return ret;
  7445. }
  7446. IInputSteppingMeta * querySteppingMeta()
  7447. {
  7448. return input->querySteppingMeta();
  7449. }
  7450. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7451. {
  7452. return input->gatherConjunctions(collector);
  7453. }
  7454. virtual void resetEOF()
  7455. {
  7456. input->resetEOF();
  7457. }
  7458. };
  7459. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7460. {
  7461. public:
  7462. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7463. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7464. {
  7465. }
  7466. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7467. {
  7468. return new CRoxieServerSortedActivity(this, _probeManager);
  7469. }
  7470. };
  7471. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7472. {
  7473. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7474. }
  7475. //=====================================================================================================
  7476. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7477. {
  7478. /*
  7479. BE VERY CAREFUL - this code is tricky.
  7480. Note that starts and stops (and resets) can occur in strange orders
  7481. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7482. The last stop should call the upstream stop.
  7483. The first reset should call the upstream reset.
  7484. 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
  7485. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7486. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7487. ignored in the minIndex calculation
  7488. */
  7489. public:
  7490. IHThorArg &helper;
  7491. unsigned activeOutputs;
  7492. unsigned numOutputs;
  7493. unsigned numOriginalOutputs;
  7494. QueueOf<const void, true> buffer;
  7495. CriticalSection crit;
  7496. CriticalSection crit2;
  7497. unsigned tailIdx;
  7498. unsigned headIdx;
  7499. Owned<IException> error;
  7500. class OutputAdaptor : public CInterface, implements IRoxieInput
  7501. {
  7502. bool eof, eofpending, stopped;
  7503. public:
  7504. CRoxieServerThroughSpillActivity *parent;
  7505. unsigned idx;
  7506. unsigned oid;
  7507. unsigned processed;
  7508. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7509. public:
  7510. IMPLEMENT_IINTERFACE;
  7511. OutputAdaptor()
  7512. {
  7513. parent = NULL;
  7514. oid = 0;
  7515. idx = 0;
  7516. processed = 0;
  7517. totalCycles = 0;
  7518. eofpending = false;
  7519. eof = false;
  7520. stopped = false;
  7521. }
  7522. ~OutputAdaptor()
  7523. {
  7524. if (traceStartStop)
  7525. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7526. if (processed && parent && parent->factory)
  7527. {
  7528. parent->factory->noteProcessed(oid, processed);
  7529. if (parent->ctx)
  7530. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  7531. }
  7532. }
  7533. void init()
  7534. {
  7535. if (traceStartStop)
  7536. DBGLOG("%p init Input adaptor %d", this, oid);
  7537. idx = 0;
  7538. processed = 0;
  7539. eofpending = false;
  7540. eof = false;
  7541. stopped = false;
  7542. }
  7543. virtual unsigned queryId() const
  7544. {
  7545. return parent->queryId();
  7546. }
  7547. virtual IRoxieServerActivity *queryActivity()
  7548. {
  7549. return parent;
  7550. }
  7551. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7552. {
  7553. return parent->queryIndexReadActivity();
  7554. }
  7555. virtual unsigned __int64 queryTotalCycles() const
  7556. {
  7557. return totalCycles;
  7558. }
  7559. virtual unsigned __int64 queryLocalCycles() const
  7560. {
  7561. return 0; // Should never be called
  7562. }
  7563. virtual IRoxieInput *queryInput(unsigned idx) const
  7564. {
  7565. return parent->queryInput(idx);
  7566. }
  7567. virtual const void * nextInGroup()
  7568. {
  7569. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7570. if (eof)
  7571. return NULL;
  7572. const void *ret = parent->readBuffered(idx, oid);
  7573. #ifdef TRACE_SPLIT
  7574. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7575. #endif
  7576. if (ret)
  7577. {
  7578. processed++;
  7579. eofpending = false;
  7580. }
  7581. else if (eofpending)
  7582. eof = true;
  7583. else
  7584. eofpending = true;
  7585. return ret;
  7586. }
  7587. virtual IOutputMetaData * queryOutputMeta() const
  7588. {
  7589. return parent->queryOutputMeta();
  7590. }
  7591. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7592. {
  7593. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7594. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7595. // for minIndex to give the correct answers
  7596. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7597. if (traceStartStop)
  7598. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7599. parent->start(oid, parentExtractSize, parentExtract, paused);
  7600. }
  7601. virtual void stop(bool aborting)
  7602. {
  7603. if (traceStartStop)
  7604. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7605. if (!stopped)
  7606. {
  7607. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7608. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7609. }
  7610. };
  7611. virtual void reset()
  7612. {
  7613. if (traceStartStop)
  7614. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7615. parent->reset(oid);
  7616. idx = 0; // value should not be relevant really but this is the safest...
  7617. stopped = false;
  7618. };
  7619. virtual void resetEOF()
  7620. {
  7621. parent->resetEOF();
  7622. }
  7623. virtual void checkAbort()
  7624. {
  7625. parent->checkAbort();
  7626. }
  7627. } *adaptors;
  7628. bool *used;
  7629. unsigned nextFreeOutput()
  7630. {
  7631. unsigned i = numOutputs;
  7632. while (i)
  7633. {
  7634. i--;
  7635. if (!used[i])
  7636. return i;
  7637. }
  7638. throwUnexpected();
  7639. }
  7640. unsigned minIndex(unsigned exceptOid)
  7641. {
  7642. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7643. // this is trying to determine whether any of the adaptors will in the future read a given record
  7644. unsigned minIdx = (unsigned) -1;
  7645. for (unsigned i = 0; i < numOutputs; i++)
  7646. {
  7647. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7648. minIdx = adaptors[i].idx;
  7649. }
  7650. return minIdx;
  7651. }
  7652. inline bool isLastTailReader(unsigned exceptOid)
  7653. {
  7654. for (unsigned i = 0; i < numOutputs; i++)
  7655. {
  7656. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7657. return false;
  7658. }
  7659. return true;
  7660. }
  7661. void initOutputs()
  7662. {
  7663. activeOutputs = numOutputs;
  7664. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7665. if (used[i])
  7666. adaptors[i].init();
  7667. state = STATEstarting;
  7668. }
  7669. public:
  7670. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7671. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7672. {
  7673. numOriginalOutputs = numOutputs;
  7674. adaptors = new OutputAdaptor[numOutputs];
  7675. used = new bool[numOutputs];
  7676. for (unsigned i = 0; i < numOutputs; i++)
  7677. {
  7678. adaptors[i].parent = this;
  7679. adaptors[i].oid = i;
  7680. used[i] = false;
  7681. }
  7682. tailIdx = 0;
  7683. headIdx = 0;
  7684. activeOutputs = numOutputs;
  7685. }
  7686. ~CRoxieServerThroughSpillActivity()
  7687. {
  7688. delete [] adaptors;
  7689. delete [] used;
  7690. }
  7691. const void *readBuffered(unsigned &idx, unsigned oid)
  7692. {
  7693. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7694. const unsigned curIdx = idx;
  7695. if (curIdx == headIdx) // test once without getting the crit2 sec
  7696. {
  7697. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7698. if (curIdx == headIdx) // test again now that we have it
  7699. {
  7700. 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
  7701. if (error)
  7702. throw error.getLink();
  7703. try
  7704. {
  7705. const void *row = input->nextInGroup();
  7706. if (activeOutputs==1)
  7707. {
  7708. #ifdef TRACE_SPLIT
  7709. CTXLOG("spill %d optimised return of %p", activityId, row);
  7710. #endif
  7711. headIdx++;
  7712. idx++;
  7713. return row; // optimization for the case where only one output still active.
  7714. }
  7715. CriticalBlock b(crit);
  7716. headIdx++;
  7717. idx++;
  7718. if (activeOutputs==1)
  7719. return row; // optimization for the case where only one output still active.
  7720. buffer.enqueue(row);
  7721. if (row) LinkRoxieRow(row);
  7722. return row;
  7723. }
  7724. catch (IException *E)
  7725. {
  7726. #ifdef TRACE_SPLIT
  7727. CTXLOG("spill %d caught exception", activityId);
  7728. #endif
  7729. error.set(E);
  7730. throw;
  7731. }
  7732. catch (...)
  7733. {
  7734. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7735. error.set(E);
  7736. throw E;
  7737. }
  7738. }
  7739. }
  7740. CriticalBlock b(crit);
  7741. 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
  7742. unsigned lidx = curIdx - tailIdx;
  7743. idx++;
  7744. if (!lidx)
  7745. {
  7746. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7747. // 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
  7748. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7749. {
  7750. tailIdx++;
  7751. const void *ret = buffer.dequeue(); // no need to link - last puller
  7752. #ifdef TRACE_SPLIT
  7753. CTXLOG("last puller return of %p", ret);
  7754. #endif
  7755. return ret;
  7756. }
  7757. }
  7758. const void *ret = buffer.item(lidx);
  7759. if (ret) LinkRoxieRow(ret);
  7760. #ifdef TRACE_SPLIT
  7761. CTXLOG("standard return of %p", ret);
  7762. #endif
  7763. return ret;
  7764. }
  7765. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7766. {
  7767. CriticalBlock b(crit);
  7768. if (error)
  7769. throw error.getLink();
  7770. if (factory)
  7771. factory->noteStarted(oid);
  7772. if (traceStartStop)
  7773. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7774. if (state != STATEstarted)
  7775. {
  7776. if (state != STATEstarting)
  7777. initOutputs();
  7778. tailIdx = 0;
  7779. headIdx = 0;
  7780. error.clear();
  7781. try
  7782. {
  7783. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7784. }
  7785. catch (IException *E)
  7786. {
  7787. #ifdef TRACE_SPLIT
  7788. CTXLOG("spill %d caught exception in start", activityId);
  7789. #endif
  7790. error.set(E);
  7791. throw;
  7792. }
  7793. catch (...)
  7794. {
  7795. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7796. error.set(E);
  7797. throw E;
  7798. }
  7799. }
  7800. }
  7801. void stop(unsigned oid, unsigned & idx, bool aborting)
  7802. {
  7803. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7804. CriticalBlock b(crit);
  7805. #ifdef TRACE_STARTSTOP
  7806. if (traceStartStop)
  7807. {
  7808. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7809. if (watchActivityId && watchActivityId==activityId)
  7810. {
  7811. CTXLOG("WATCH: stop %d", activityId);
  7812. }
  7813. }
  7814. #endif
  7815. if (state != STATEstarting && state != STATEstarted)
  7816. initOutputs();
  7817. if (activeOutputs > 1)
  7818. {
  7819. if (tailIdx==idx)
  7820. {
  7821. // Discard all buffered rows that are there purely for this adaptor to read them
  7822. unsigned min = minIndex(oid);
  7823. if (min != (unsigned) -1)
  7824. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7825. // Should never happen though if there are still some active.
  7826. // there may be a small window where adaptors are blocked on the semaphore...
  7827. {
  7828. #ifdef TRACE_SPLIT
  7829. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7830. #endif
  7831. while (tailIdx < min)
  7832. {
  7833. ReleaseRoxieRow(buffer.dequeue());
  7834. tailIdx++;
  7835. }
  7836. }
  7837. }
  7838. activeOutputs--;
  7839. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7840. return;
  7841. }
  7842. #ifdef TRACE_SPLIT
  7843. CTXLOG("%p: All outputs done", this);
  7844. #endif
  7845. activeOutputs = numOutputs;
  7846. CRoxieServerActivity::stop(aborting);
  7847. };
  7848. void reset(unsigned oid)
  7849. {
  7850. if (traceStartStop)
  7851. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7852. activeOutputs = numOutputs;
  7853. while (buffer.ordinality())
  7854. ReleaseRoxieRow(buffer.dequeue());
  7855. error.clear();
  7856. if (state != STATEreset) // make sure input is only reset once
  7857. CRoxieServerActivity::reset();
  7858. };
  7859. virtual const void *nextInGroup()
  7860. {
  7861. throwUnexpected(); // Internal logic error - we are not anybody's input
  7862. }
  7863. virtual IOutputMetaData * queryOutputMeta() const
  7864. {
  7865. // if (outputMeta)
  7866. // return outputMeta;
  7867. // else
  7868. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7869. }
  7870. virtual IRoxieInput *queryOutput(unsigned idx)
  7871. {
  7872. if (idx==(unsigned)-1)
  7873. idx = nextFreeOutput(); // MORE - what is this used for?
  7874. assertex(idx < numOriginalOutputs);
  7875. assertex(!used[idx]);
  7876. used[idx] = true;
  7877. return &adaptors[idx];
  7878. }
  7879. virtual void resetOutputsUsed()
  7880. {
  7881. numOutputs = 1;
  7882. activeOutputs = 1;
  7883. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7884. }
  7885. virtual void noteOutputUsed()
  7886. {
  7887. assertex(numOutputs < numOriginalOutputs);
  7888. numOutputs++;
  7889. activeOutputs = numOutputs;
  7890. }
  7891. virtual bool isPassThrough()
  7892. {
  7893. return numOutputs==1;
  7894. }
  7895. };
  7896. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7897. {
  7898. public:
  7899. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7900. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7901. {
  7902. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7903. setNumOutputs(helper->getTempUsageCount() + 1);
  7904. }
  7905. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7906. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7907. {
  7908. setNumOutputs(_numOutputs);
  7909. }
  7910. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7911. {
  7912. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7913. }
  7914. };
  7915. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7916. {
  7917. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7918. }
  7919. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7920. {
  7921. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7922. }
  7923. //----------------------------------------------------------------------------------------------
  7924. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7925. {
  7926. public:
  7927. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7928. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7929. {
  7930. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7931. setNumOutputs(helper->numBranches());
  7932. }
  7933. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7934. {
  7935. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7936. }
  7937. };
  7938. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7939. {
  7940. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7941. }
  7942. //=====================================================================================================
  7943. #define PIPE_BUFSIZE 0x8000
  7944. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7945. {
  7946. StringBuffer msg;
  7947. if(pipe->hasError())
  7948. {
  7949. try
  7950. {
  7951. char error[512];
  7952. size32_t sz = pipe->readError(sizeof(error), error);
  7953. if(sz && sz!=(size32_t)-1)
  7954. msg.append(", stderr: '").append(sz, error).append("'");
  7955. }
  7956. catch (IException *e)
  7957. {
  7958. EXCLOG(e, "Error reading pipe stderr");
  7959. e->Release();
  7960. }
  7961. }
  7962. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7963. }
  7964. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7965. {
  7966. IHThorPipeReadArg &helper;
  7967. Owned<IPipeProcess> pipe;
  7968. StringAttr pipeCommand;
  7969. Owned<IOutputRowDeserializer> rowDeserializer;
  7970. Owned<IReadRowStream> readTransformer;
  7971. bool groupSignalled;
  7972. public:
  7973. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7974. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7975. {
  7976. groupSignalled = true;
  7977. }
  7978. virtual bool needsAllocator() const { return true; }
  7979. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7980. {
  7981. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7982. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7983. }
  7984. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7985. {
  7986. groupSignalled = true; // i.e. don't start with a NULL row
  7987. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7988. if (!readTransformer)
  7989. {
  7990. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7991. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7992. }
  7993. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7994. openPipe(pipeProgram);
  7995. }
  7996. virtual void stop(bool aborting)
  7997. {
  7998. CRoxieServerActivity::stop(aborting);
  7999. pipe.clear();
  8000. readTransformer->setStream(NULL);
  8001. }
  8002. virtual const void *nextInGroup()
  8003. {
  8004. ActivityTimer t(totalCycles, timeActivities);
  8005. while (!waitForPipe())
  8006. {
  8007. if (!pipe)
  8008. return NULL;
  8009. if (helper.getPipeFlags() & TPFgroupeachrow)
  8010. {
  8011. if (!groupSignalled)
  8012. {
  8013. groupSignalled = true;
  8014. return NULL;
  8015. }
  8016. }
  8017. }
  8018. const void *ret = readTransformer->next();
  8019. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8020. processed++;
  8021. groupSignalled = false;
  8022. return ret;
  8023. }
  8024. protected:
  8025. bool waitForPipe()
  8026. {
  8027. if (!pipe)
  8028. return false; // done
  8029. if (!readTransformer->eos())
  8030. return true;
  8031. verifyPipe();
  8032. return false;
  8033. }
  8034. void openPipe(char const * cmd)
  8035. {
  8036. pipeCommand.setown(cmd);
  8037. pipe.setown(createPipeProcess());
  8038. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8039. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8040. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8041. readTransformer->setStream(pipeReader.get());
  8042. }
  8043. void verifyPipe()
  8044. {
  8045. if (pipe)
  8046. {
  8047. unsigned err = pipe->wait();
  8048. if(err && !(helper.getPipeFlags() & TPFnofail))
  8049. {
  8050. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8051. }
  8052. pipe.clear();
  8053. }
  8054. }
  8055. };
  8056. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8057. {
  8058. IHThorPipeThroughArg &helper;
  8059. RecordPullerThread puller;
  8060. Owned<IPipeProcess> pipe;
  8061. StringAttr pipeCommand;
  8062. InterruptableSemaphore pipeVerified;
  8063. InterruptableSemaphore pipeOpened;
  8064. CachedOutputMetaData inputMeta;
  8065. Owned<IOutputRowSerializer> rowSerializer;
  8066. Owned<IOutputRowDeserializer> rowDeserializer;
  8067. Owned<IPipeWriteXformHelper> writeTransformer;
  8068. Owned<IReadRowStream> readTransformer;
  8069. bool firstRead;
  8070. bool recreate;
  8071. bool inputExhausted;
  8072. bool groupSignalled;
  8073. public:
  8074. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8075. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8076. {
  8077. recreate = helper.recreateEachRow();
  8078. groupSignalled = true;
  8079. firstRead = false;
  8080. inputExhausted = false;
  8081. }
  8082. virtual bool needsAllocator() const { return true; }
  8083. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8084. {
  8085. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8086. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8087. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8088. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8089. }
  8090. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8091. {
  8092. firstRead = true;
  8093. inputExhausted = false;
  8094. groupSignalled = true; // i.e. don't start with a NULL row
  8095. pipeVerified.reinit();
  8096. pipeOpened.reinit();
  8097. writeTransformer->ready();
  8098. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8099. if (!readTransformer)
  8100. {
  8101. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8102. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8103. }
  8104. if(!recreate)
  8105. {
  8106. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8107. openPipe(pipeProgram);
  8108. }
  8109. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8110. }
  8111. virtual void setInput(unsigned idx, IRoxieInput *_in)
  8112. {
  8113. if (idx)
  8114. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  8115. puller.setInput(this, _in);
  8116. inputMeta.set(_in->queryOutputMeta());
  8117. }
  8118. virtual void stop(bool aborting)
  8119. {
  8120. pipeVerified.interrupt(NULL);
  8121. pipeOpened.interrupt(NULL);
  8122. puller.stop(aborting);
  8123. CRoxieServerActivity::stop(aborting);
  8124. pipe.clear();
  8125. readTransformer->setStream(NULL);
  8126. }
  8127. virtual void reset()
  8128. {
  8129. puller.reset();
  8130. CRoxieServerActivity::reset();
  8131. }
  8132. virtual const void *nextInGroup()
  8133. {
  8134. ActivityTimer t(totalCycles, timeActivities);
  8135. while (!waitForPipe())
  8136. {
  8137. if (!pipe)
  8138. return NULL;
  8139. if (helper.getPipeFlags() & TPFgroupeachrow)
  8140. {
  8141. if (!groupSignalled)
  8142. {
  8143. groupSignalled = true;
  8144. return NULL;
  8145. }
  8146. }
  8147. }
  8148. const void *ret = readTransformer->next();
  8149. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8150. processed++;
  8151. groupSignalled = false;
  8152. return ret;
  8153. }
  8154. virtual void processRow(const void *row)
  8155. {
  8156. // called from puller thread
  8157. if(recreate)
  8158. openPipe(helper.getNameFromRow(row));
  8159. writeTransformer->writeTranslatedText(row, pipe);
  8160. ReleaseRoxieRow(row);
  8161. if(recreate)
  8162. {
  8163. closePipe();
  8164. pipeVerified.wait();
  8165. }
  8166. }
  8167. virtual void processDone()
  8168. {
  8169. // called from puller thread
  8170. if(recreate)
  8171. {
  8172. inputExhausted = true;
  8173. pipeOpened.signal();
  8174. }
  8175. else
  8176. {
  8177. closePipe();
  8178. pipeVerified.wait();
  8179. }
  8180. }
  8181. virtual void processEOG()
  8182. {
  8183. }
  8184. void processGroup(const ConstPointerArray &)
  8185. {
  8186. throwUnexpected();
  8187. }
  8188. virtual bool fireException(IException *e)
  8189. {
  8190. pipeOpened.interrupt(LINK(e));
  8191. pipeVerified.interrupt(e);
  8192. return true;
  8193. }
  8194. private:
  8195. bool waitForPipe()
  8196. {
  8197. if (firstRead)
  8198. {
  8199. pipeOpened.wait();
  8200. firstRead = false;
  8201. }
  8202. if (!pipe)
  8203. return false; // done
  8204. if (!readTransformer->eos())
  8205. return true;
  8206. verifyPipe();
  8207. if (recreate && !inputExhausted)
  8208. pipeOpened.wait();
  8209. return false;
  8210. }
  8211. void openPipe(char const * cmd)
  8212. {
  8213. pipeCommand.setown(cmd);
  8214. pipe.setown(createPipeProcess());
  8215. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8216. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8217. writeTransformer->writeHeader(pipe);
  8218. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8219. readTransformer->setStream(pipeReader.get());
  8220. pipeOpened.signal();
  8221. }
  8222. void closePipe()
  8223. {
  8224. writeTransformer->writeFooter(pipe);
  8225. pipe->closeInput();
  8226. }
  8227. void verifyPipe()
  8228. {
  8229. if (pipe)
  8230. {
  8231. unsigned err = pipe->wait();
  8232. if(err && !(helper.getPipeFlags() & TPFnofail))
  8233. {
  8234. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8235. }
  8236. pipe.clear();
  8237. pipeVerified.signal();
  8238. }
  8239. }
  8240. };
  8241. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8242. {
  8243. IHThorPipeWriteArg &helper;
  8244. Owned<IPipeProcess> pipe;
  8245. StringAttr pipeCommand;
  8246. CachedOutputMetaData inputMeta;
  8247. Owned<IOutputRowSerializer> rowSerializer;
  8248. Owned<IPipeWriteXformHelper> writeTransformer;
  8249. bool firstRead;
  8250. bool recreate;
  8251. bool inputExhausted;
  8252. public:
  8253. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8254. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8255. {
  8256. recreate = helper.recreateEachRow();
  8257. firstRead = false;
  8258. inputExhausted = false;
  8259. }
  8260. virtual bool needsAllocator() const { return true; }
  8261. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8262. {
  8263. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8264. inputMeta.set(input->queryOutputMeta());
  8265. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8266. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8267. }
  8268. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8269. {
  8270. firstRead = true;
  8271. inputExhausted = false;
  8272. writeTransformer->ready();
  8273. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8274. if(!recreate)
  8275. {
  8276. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8277. openPipe(pipeProgram);
  8278. }
  8279. }
  8280. virtual void stop(bool aborting)
  8281. {
  8282. if (!aborting && helper.getSequence() >= 0)
  8283. {
  8284. WorkunitUpdate wu = ctx->updateWorkUnit();
  8285. if (wu)
  8286. {
  8287. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8288. if (result)
  8289. {
  8290. result->setResultTotalRowCount(processed);
  8291. result->setResultStatus(ResultStatusCalculated);
  8292. }
  8293. }
  8294. }
  8295. CRoxieServerActivity::stop(aborting);
  8296. pipe.clear();
  8297. }
  8298. virtual void onExecute()
  8299. {
  8300. loop
  8301. {
  8302. const void *row = input->nextInGroup();
  8303. if (!row)
  8304. {
  8305. row = input->nextInGroup();
  8306. if (!row)
  8307. break;
  8308. }
  8309. processed++;
  8310. if(recreate)
  8311. openPipe(helper.getNameFromRow(row));
  8312. writeTransformer->writeTranslatedText(row, pipe);
  8313. ReleaseRoxieRow(row);
  8314. if(recreate)
  8315. closePipe();
  8316. }
  8317. closePipe();
  8318. }
  8319. private:
  8320. void openPipe(char const * cmd)
  8321. {
  8322. pipeCommand.setown(cmd);
  8323. pipe.setown(createPipeProcess());
  8324. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8325. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8326. writeTransformer->writeHeader(pipe);
  8327. }
  8328. void closePipe()
  8329. {
  8330. writeTransformer->writeFooter(pipe);
  8331. pipe->closeInput();
  8332. unsigned err = pipe->wait();
  8333. if(err && !(helper.getPipeFlags() & TPFnofail))
  8334. {
  8335. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8336. }
  8337. pipe.clear();
  8338. }
  8339. };
  8340. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8341. {
  8342. public:
  8343. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8344. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8345. {
  8346. }
  8347. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8348. {
  8349. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8350. }
  8351. };
  8352. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8353. {
  8354. public:
  8355. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8356. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8357. {
  8358. }
  8359. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8360. {
  8361. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8362. }
  8363. };
  8364. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8365. {
  8366. public:
  8367. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8368. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8369. {
  8370. }
  8371. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8372. {
  8373. return new CRoxieServerPipeWriteActivity(this, _probeManager, usageCount);
  8374. }
  8375. };
  8376. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8377. {
  8378. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8379. }
  8380. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8381. {
  8382. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8383. }
  8384. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8385. {
  8386. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8387. }
  8388. //=====================================================================================================
  8389. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8390. {
  8391. IHThorStreamedIteratorArg &helper;
  8392. Owned<IRowStream> rows;
  8393. public:
  8394. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8395. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8396. {
  8397. }
  8398. ~CRoxieServerStreamedIteratorActivity()
  8399. {
  8400. }
  8401. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8402. {
  8403. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8404. rows.setown(helper.createInput());
  8405. }
  8406. virtual void stop(bool aborting)
  8407. {
  8408. if (rows)
  8409. {
  8410. rows->stop();
  8411. rows.clear();
  8412. }
  8413. CRoxieServerActivity::stop(aborting);
  8414. }
  8415. virtual const void *nextInGroup()
  8416. {
  8417. ActivityTimer t(totalCycles, timeActivities);
  8418. assertex(rows != NULL);
  8419. const void * next = rows->nextRow();
  8420. if (next)
  8421. processed++;
  8422. return next;
  8423. }
  8424. };
  8425. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8426. {
  8427. public:
  8428. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8429. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8430. {
  8431. }
  8432. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8433. {
  8434. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8435. }
  8436. };
  8437. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8438. {
  8439. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8440. }
  8441. //=====================================================================================================
  8442. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8443. {
  8444. IHThorFilterArg &helper;
  8445. bool anyThisGroup;
  8446. IRangeCompare * stepCompare;
  8447. public:
  8448. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8449. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8450. {
  8451. anyThisGroup = false;
  8452. stepCompare = NULL;
  8453. }
  8454. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8455. {
  8456. anyThisGroup = false;
  8457. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8458. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8459. stepCompare = NULL;
  8460. if (!eof)
  8461. {
  8462. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8463. if (stepMeta)
  8464. stepCompare = stepMeta->queryCompare();
  8465. }
  8466. }
  8467. virtual const void * nextInGroup()
  8468. {
  8469. ActivityTimer t(totalCycles, timeActivities);
  8470. if (eof)
  8471. return NULL;
  8472. loop
  8473. {
  8474. const void * ret = input->nextInGroup();
  8475. if (!ret)
  8476. {
  8477. //stop returning two NULLs in a row.
  8478. if (anyThisGroup)
  8479. {
  8480. anyThisGroup = false;
  8481. return NULL;
  8482. }
  8483. ret = input->nextInGroup();
  8484. if (!ret)
  8485. {
  8486. eof = true;
  8487. return NULL; // eof...
  8488. }
  8489. }
  8490. if (helper.isValid(ret))
  8491. {
  8492. anyThisGroup = true;
  8493. processed++;
  8494. return ret;
  8495. }
  8496. ReleaseRoxieRow(ret);
  8497. }
  8498. }
  8499. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8500. {
  8501. //Could assert that this isn't grouped
  8502. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8503. ActivityTimer t(totalCycles, timeActivities);
  8504. if (eof)
  8505. return NULL;
  8506. loop
  8507. {
  8508. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8509. if (!ret)
  8510. {
  8511. eof = true;
  8512. return NULL;
  8513. }
  8514. if (!wasCompleteMatch)
  8515. {
  8516. anyThisGroup = false; // RKC->GH - is this right??
  8517. return ret;
  8518. }
  8519. if (helper.isValid(ret))
  8520. {
  8521. anyThisGroup = true;
  8522. processed++;
  8523. return ret;
  8524. }
  8525. if (!stepExtra.returnMismatches())
  8526. {
  8527. ReleaseRoxieRow(ret);
  8528. return nextInGroup();
  8529. }
  8530. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8531. //condition to advance
  8532. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8533. {
  8534. wasCompleteMatch = false;
  8535. anyThisGroup = false; // WHY?
  8536. return ret;
  8537. }
  8538. ReleaseRoxieRow(ret);
  8539. }
  8540. }
  8541. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8542. {
  8543. return input->gatherConjunctions(collector);
  8544. }
  8545. virtual void resetEOF()
  8546. {
  8547. eof = prefiltered;
  8548. anyThisGroup = false;
  8549. input->resetEOF();
  8550. }
  8551. IInputSteppingMeta * querySteppingMeta()
  8552. {
  8553. return input->querySteppingMeta();
  8554. }
  8555. };
  8556. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8557. {
  8558. public:
  8559. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8560. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8561. {
  8562. }
  8563. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8564. {
  8565. return new CRoxieServerFilterActivity(this, _probeManager);
  8566. }
  8567. };
  8568. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8569. {
  8570. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8571. }
  8572. //=====================================================================================================
  8573. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8574. {
  8575. IHThorFilterGroupArg &helper;
  8576. unsigned curIndex;
  8577. ConstPointerArray gathered;
  8578. IRangeCompare * stepCompare;
  8579. public:
  8580. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8581. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8582. {
  8583. curIndex = 0;
  8584. stepCompare = NULL;
  8585. }
  8586. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8587. {
  8588. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8589. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8590. assertex(eof == !helper.canMatchAny());
  8591. curIndex = 0;
  8592. stepCompare = NULL;
  8593. if (!eof)
  8594. {
  8595. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8596. if (inputStepping)
  8597. stepCompare = inputStepping->queryCompare();
  8598. }
  8599. }
  8600. virtual void reset()
  8601. {
  8602. releaseGathered();
  8603. CRoxieServerLateStartActivity::reset();
  8604. }
  8605. inline void releaseGathered()
  8606. {
  8607. while (gathered.isItem(curIndex))
  8608. ReleaseRoxieRow(gathered.item(curIndex++));
  8609. gathered.kill();
  8610. }
  8611. virtual const void * nextInGroup()
  8612. {
  8613. ActivityTimer t(totalCycles, timeActivities);
  8614. loop
  8615. {
  8616. if (eof)
  8617. return NULL;
  8618. if (gathered.ordinality())
  8619. {
  8620. if (gathered.isItem(curIndex))
  8621. {
  8622. const void * ret = gathered.item(curIndex++);
  8623. processed++;
  8624. return ret;
  8625. }
  8626. curIndex = 0;
  8627. gathered.kill();
  8628. return NULL;
  8629. }
  8630. const void * ret = input->nextInGroup();
  8631. while (ret)
  8632. {
  8633. gathered.append(ret);
  8634. ret = input->nextInGroup();
  8635. }
  8636. unsigned num = gathered.ordinality();
  8637. if (num != 0)
  8638. {
  8639. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8640. ReleaseRoxieRowSet(gathered); // read next group
  8641. }
  8642. else
  8643. eof = true;
  8644. }
  8645. }
  8646. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8647. {
  8648. ActivityTimer t(totalCycles, timeActivities);
  8649. if (eof)
  8650. return NULL;
  8651. if (gathered.ordinality())
  8652. {
  8653. while (gathered.isItem(curIndex))
  8654. {
  8655. const void * ret = gathered.item(curIndex++);
  8656. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8657. {
  8658. processed++;
  8659. return ret;
  8660. }
  8661. ReleaseRoxieRow(ret);
  8662. }
  8663. curIndex = 0;
  8664. gathered.kill();
  8665. //nextSteppedGE never returns an end of group marker.
  8666. }
  8667. //Not completely sure about this - it could lead the the start of a group being skipped,
  8668. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8669. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8670. //MORE: What do we do with wasCompleteMatch? something like the following????
  8671. #if 0
  8672. loop
  8673. {
  8674. const void * ret;
  8675. if (stepExtra.returnMismatches())
  8676. {
  8677. bool matchedCompletely = true;
  8678. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8679. if (!wasCompleteMatch)
  8680. return ret;
  8681. }
  8682. else
  8683. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8684. #endif
  8685. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8686. while (ret)
  8687. {
  8688. gathered.append(ret);
  8689. ret = input->nextInGroup();
  8690. }
  8691. unsigned num = gathered.ordinality();
  8692. if (num != 0)
  8693. {
  8694. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8695. ReleaseRoxieRowSet(gathered); // read next group
  8696. }
  8697. else
  8698. eof = true;
  8699. return nextUngrouped(this);
  8700. }
  8701. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8702. {
  8703. return input->gatherConjunctions(collector);
  8704. }
  8705. virtual void resetEOF()
  8706. {
  8707. eof = false;
  8708. releaseGathered();
  8709. input->resetEOF();
  8710. }
  8711. IInputSteppingMeta * querySteppingMeta()
  8712. {
  8713. return input->querySteppingMeta();
  8714. }
  8715. };
  8716. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8717. {
  8718. public:
  8719. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8720. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8721. {
  8722. }
  8723. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8724. {
  8725. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8726. }
  8727. };
  8728. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8729. {
  8730. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8731. }
  8732. //=================================================================================
  8733. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8734. {
  8735. IHThorSideEffectArg &helper;
  8736. CriticalSection ecrit;
  8737. Owned<IException> exception;
  8738. bool executed;
  8739. public:
  8740. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8741. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8742. {
  8743. executed = false;
  8744. }
  8745. virtual const void * nextInGroup()
  8746. {
  8747. ActivityTimer t(totalCycles, timeActivities);
  8748. CriticalBlock b(ecrit);
  8749. if (exception)
  8750. throw(exception.getLink());
  8751. if (!executed)
  8752. {
  8753. try
  8754. {
  8755. executed = true;
  8756. helper.action();
  8757. }
  8758. catch(IException *E)
  8759. {
  8760. exception.set(E);
  8761. throw;
  8762. }
  8763. }
  8764. return NULL;
  8765. }
  8766. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8767. {
  8768. CriticalBlock b(ecrit);
  8769. if (exception)
  8770. throw(exception.getLink());
  8771. if (!executed)
  8772. {
  8773. try
  8774. {
  8775. ActivityTimer t(totalCycles, timeActivities);
  8776. executed = true;
  8777. start(parentExtractSize, parentExtract, false);
  8778. helper.action();
  8779. stop(false);
  8780. }
  8781. catch(IException *E)
  8782. {
  8783. ctx->notifyAbort(E);
  8784. stop(true);
  8785. exception.set(E);
  8786. throw;
  8787. }
  8788. }
  8789. }
  8790. virtual void reset()
  8791. {
  8792. executed = false;
  8793. exception.clear();
  8794. CRoxieServerActivity::reset();
  8795. }
  8796. };
  8797. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8798. {
  8799. bool isRoot;
  8800. public:
  8801. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8802. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8803. {
  8804. }
  8805. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8806. {
  8807. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8808. }
  8809. virtual bool isSink() const
  8810. {
  8811. return isRoot && !meta.queryOriginal();
  8812. }
  8813. };
  8814. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8815. {
  8816. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8817. }
  8818. //=================================================================================
  8819. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8820. {
  8821. IHThorActionArg &helper;
  8822. public:
  8823. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8824. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  8825. {
  8826. }
  8827. virtual void onExecute()
  8828. {
  8829. helper.action();
  8830. }
  8831. };
  8832. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8833. {
  8834. public:
  8835. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8836. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8837. {
  8838. }
  8839. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8840. {
  8841. return new CRoxieServerActionActivity(this, _probeManager, usageCount);
  8842. }
  8843. };
  8844. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8845. {
  8846. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8847. }
  8848. //=================================================================================
  8849. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8850. {
  8851. IHThorSampleArg &helper;
  8852. unsigned numSamples;
  8853. unsigned numToSkip;
  8854. unsigned whichSample;
  8855. bool anyThisGroup;
  8856. bool eof;
  8857. public:
  8858. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8859. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8860. {
  8861. numSamples = 0;
  8862. numToSkip = 0;
  8863. whichSample = 0;
  8864. anyThisGroup = false;
  8865. eof = false;
  8866. }
  8867. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8868. {
  8869. anyThisGroup = false;
  8870. eof = false;
  8871. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8872. numSamples = helper.getProportion();
  8873. whichSample = helper.getSampleNumber();
  8874. numToSkip = (whichSample ? whichSample-1 : 0);
  8875. }
  8876. virtual const void * nextInGroup()
  8877. {
  8878. ActivityTimer t(totalCycles, timeActivities);
  8879. if (eof)
  8880. return NULL;
  8881. loop
  8882. {
  8883. const void * ret = input->nextInGroup();
  8884. if (!ret)
  8885. {
  8886. //this does work with groups - may or may not be useful...
  8887. //reset the sample for each group.... probably best.
  8888. numToSkip = (whichSample ? whichSample-1 : 0);
  8889. if (anyThisGroup)
  8890. {
  8891. anyThisGroup = false;
  8892. return NULL;
  8893. }
  8894. ret = input->nextInGroup();
  8895. if (!ret)
  8896. {
  8897. eof = true;
  8898. return NULL; // eof...
  8899. }
  8900. }
  8901. if (numToSkip == 0)
  8902. {
  8903. anyThisGroup = true;
  8904. numToSkip = numSamples-1;
  8905. processed++;
  8906. return ret;
  8907. }
  8908. numToSkip--;
  8909. ReleaseRoxieRow(ret);
  8910. }
  8911. }
  8912. };
  8913. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8914. {
  8915. public:
  8916. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8917. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8918. {
  8919. }
  8920. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8921. {
  8922. return new CRoxieServerSampleActivity(this, _probeManager);
  8923. }
  8924. };
  8925. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8926. {
  8927. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8928. }
  8929. //=================================================================================
  8930. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8931. {
  8932. IHThorChooseSetsArg &helper;
  8933. unsigned numSets;
  8934. unsigned * setCounts;
  8935. bool done;
  8936. public:
  8937. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8938. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8939. {
  8940. setCounts = NULL;
  8941. numSets = 0;
  8942. done = false;
  8943. }
  8944. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8945. {
  8946. done = false;
  8947. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8948. numSets = helper.getNumSets();
  8949. setCounts = new unsigned[numSets];
  8950. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8951. helper.setCounts(setCounts);
  8952. }
  8953. virtual void reset()
  8954. {
  8955. delete [] setCounts;
  8956. setCounts = NULL;
  8957. CRoxieServerActivity::reset();
  8958. }
  8959. virtual const void * nextInGroup()
  8960. {
  8961. ActivityTimer t(totalCycles, timeActivities);
  8962. if (done)
  8963. return NULL;
  8964. loop
  8965. {
  8966. const void * ret = input->nextInGroup();
  8967. if (!ret)
  8968. {
  8969. ret = input->nextInGroup();
  8970. if (!ret)
  8971. {
  8972. done = true;
  8973. return NULL;
  8974. }
  8975. }
  8976. processed++;
  8977. switch (helper.getRecordAction(ret))
  8978. {
  8979. case 2:
  8980. done = true;
  8981. return ret;
  8982. case 1:
  8983. return ret;
  8984. }
  8985. ReleaseRoxieRow(ret);
  8986. }
  8987. }
  8988. };
  8989. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8990. {
  8991. public:
  8992. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8993. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8994. {
  8995. }
  8996. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8997. {
  8998. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8999. }
  9000. };
  9001. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9002. {
  9003. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9004. }
  9005. //=================================================================================
  9006. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9007. {
  9008. protected:
  9009. IHThorChooseSetsExArg &helper;
  9010. unsigned numSets;
  9011. unsigned curIndex;
  9012. unsigned * setCounts;
  9013. count_t * limits;
  9014. bool done;
  9015. ConstPointerArray gathered;
  9016. virtual bool includeRow(const void * row) = 0;
  9017. virtual void calculateSelection() = 0;
  9018. public:
  9019. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9020. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9021. {
  9022. setCounts = NULL;
  9023. limits = NULL;
  9024. done = false;
  9025. curIndex = 0;
  9026. numSets = 0;
  9027. }
  9028. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9029. {
  9030. done = false;
  9031. curIndex = 0;
  9032. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9033. numSets = helper.getNumSets();
  9034. setCounts = new unsigned[numSets];
  9035. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9036. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9037. helper.getLimits(limits);
  9038. }
  9039. virtual void reset()
  9040. {
  9041. delete [] setCounts;
  9042. setCounts = NULL;
  9043. free(limits);
  9044. limits = NULL;
  9045. while (gathered.isItem(curIndex))
  9046. ReleaseRoxieRow(gathered.item(curIndex++));
  9047. gathered.kill();
  9048. CRoxieServerActivity::reset();
  9049. }
  9050. virtual const void * nextInGroup()
  9051. {
  9052. ActivityTimer t(totalCycles, timeActivities);
  9053. if (gathered.ordinality() == 0)
  9054. {
  9055. curIndex = 0;
  9056. if (!input->nextGroup(gathered))
  9057. {
  9058. done = true;
  9059. return NULL;
  9060. }
  9061. ForEachItemIn(idx1, gathered)
  9062. {
  9063. unsigned category = helper.getCategory(gathered.item(idx1));
  9064. if (category)
  9065. setCounts[category-1]++;
  9066. }
  9067. calculateSelection();
  9068. }
  9069. while (gathered.isItem(curIndex))
  9070. {
  9071. const void * row = gathered.item(curIndex);
  9072. gathered.replace(NULL, curIndex);
  9073. curIndex++;
  9074. if (includeRow(row))
  9075. {
  9076. processed++;
  9077. return row;
  9078. }
  9079. ReleaseRoxieRow(row);
  9080. }
  9081. gathered.kill();
  9082. return NULL;
  9083. }
  9084. };
  9085. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9086. {
  9087. unsigned * numToSkip;
  9088. public:
  9089. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9090. {
  9091. numToSkip = NULL;
  9092. }
  9093. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9094. {
  9095. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9096. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9097. }
  9098. virtual void reset()
  9099. {
  9100. free(numToSkip);
  9101. numToSkip = NULL;
  9102. CRoxieServerChooseSetsExActivity::reset();
  9103. }
  9104. protected:
  9105. virtual void calculateSelection()
  9106. {
  9107. for (unsigned idx=0; idx < numSets; idx++)
  9108. {
  9109. if (setCounts[idx] < limits[idx])
  9110. numToSkip[idx] = 0;
  9111. else
  9112. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9113. }
  9114. }
  9115. virtual bool includeRow(const void * row)
  9116. {
  9117. unsigned category = helper.getCategory(row);
  9118. if (category)
  9119. {
  9120. if (numToSkip[category-1] == 0)
  9121. return true;
  9122. numToSkip[category-1]--;
  9123. }
  9124. return false;
  9125. }
  9126. };
  9127. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9128. {
  9129. count_t * counter;
  9130. public:
  9131. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9132. {
  9133. counter = NULL;
  9134. }
  9135. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9136. {
  9137. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9138. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9139. }
  9140. virtual void reset()
  9141. {
  9142. free(counter);
  9143. counter = NULL;
  9144. CRoxieServerChooseSetsExActivity::reset();
  9145. }
  9146. protected:
  9147. virtual void calculateSelection()
  9148. {
  9149. }
  9150. virtual bool includeRow(const void * row)
  9151. {
  9152. unsigned category = helper.getCategory(row);
  9153. if (category)
  9154. {
  9155. assertex(category <= numSets);
  9156. counter[category-1] += limits[category-1];
  9157. if(counter[category-1] >= setCounts[category-1])
  9158. {
  9159. counter[category-1] -= setCounts[category-1];
  9160. return true;
  9161. }
  9162. }
  9163. return false;
  9164. }
  9165. };
  9166. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9167. {
  9168. public:
  9169. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9170. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9171. {
  9172. }
  9173. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9174. {
  9175. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  9176. }
  9177. };
  9178. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9179. {
  9180. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9181. }
  9182. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9183. {
  9184. public:
  9185. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9187. {
  9188. }
  9189. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9190. {
  9191. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  9192. }
  9193. };
  9194. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9195. {
  9196. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9197. }
  9198. //=================================================================================
  9199. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9200. {
  9201. IHThorEnthArg &helper;
  9202. unsigned __int64 numerator;
  9203. unsigned __int64 denominator;
  9204. unsigned __int64 counter;
  9205. bool eof;
  9206. public:
  9207. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9208. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9209. {
  9210. eof = false;
  9211. numerator = denominator = counter = 0;
  9212. }
  9213. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9214. {
  9215. eof = false;
  9216. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9217. numerator = helper.getProportionNumerator();
  9218. denominator = helper.getProportionDenominator();
  9219. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9220. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9221. if (counter >= denominator)
  9222. counter %= denominator;
  9223. }
  9224. inline bool wanted()
  9225. {
  9226. counter += numerator;
  9227. if(counter >= denominator)
  9228. {
  9229. counter -= denominator;
  9230. return true;
  9231. }
  9232. return false;
  9233. }
  9234. virtual const void * nextInGroup()
  9235. {
  9236. ActivityTimer t(totalCycles, timeActivities);
  9237. if (eof)
  9238. return NULL;
  9239. const void * ret;
  9240. loop
  9241. {
  9242. ret = input->nextInGroup();
  9243. if(!ret) //end of group
  9244. ret = input->nextInGroup();
  9245. if(!ret) //eof
  9246. {
  9247. eof = true;
  9248. return ret;
  9249. }
  9250. if (wanted())
  9251. return ret;
  9252. ReleaseRoxieRow(ret);
  9253. }
  9254. }
  9255. };
  9256. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9257. {
  9258. public:
  9259. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9260. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9261. {
  9262. }
  9263. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9264. {
  9265. return new CRoxieServerEnthActivity(this, _probeManager);
  9266. }
  9267. };
  9268. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9269. {
  9270. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9271. }
  9272. //=================================================================================
  9273. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9274. {
  9275. IHThorAggregateArg &helper;
  9276. bool eof;
  9277. bool isInputGrouped;
  9278. bool abortEarly;
  9279. public:
  9280. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9281. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9282. {
  9283. eof = false;
  9284. isInputGrouped = false;
  9285. abortEarly = false;
  9286. }
  9287. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9288. {
  9289. eof = false;
  9290. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9291. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9292. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9293. }
  9294. virtual bool needsAllocator() const { return true; }
  9295. virtual const void * nextInGroup()
  9296. {
  9297. ActivityTimer t(totalCycles, timeActivities);
  9298. if (eof)
  9299. return NULL;
  9300. const void * next = input->nextInGroup();
  9301. if (!next && isInputGrouped)
  9302. {
  9303. eof = true;
  9304. return NULL;
  9305. }
  9306. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9307. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9308. if (next)
  9309. {
  9310. finalSize = helper.processFirst(rowBuilder, next);
  9311. ReleaseRoxieRow(next);
  9312. if (!abortEarly)
  9313. {
  9314. loop
  9315. {
  9316. next = input->nextInGroup();
  9317. if (!next)
  9318. break;
  9319. finalSize = helper.processNext(rowBuilder, next);
  9320. ReleaseRoxieRow(next);
  9321. }
  9322. }
  9323. }
  9324. if (!isInputGrouped) // either read all, or aborted early
  9325. eof = true;
  9326. processed++;
  9327. return rowBuilder.finalizeRowClear(finalSize);
  9328. }
  9329. };
  9330. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9331. {
  9332. public:
  9333. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9334. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9335. {
  9336. }
  9337. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9338. {
  9339. return new CRoxieServerAggregateActivity(this, _probeManager);
  9340. }
  9341. };
  9342. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9343. {
  9344. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9345. }
  9346. //=================================================================================
  9347. typedef unsigned t_hashPrefix;
  9348. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9349. {
  9350. IHThorHashAggregateArg &helper;
  9351. RowAggregator aggregated;
  9352. bool eof;
  9353. bool gathered;
  9354. bool isGroupedAggregate;
  9355. public:
  9356. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9357. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9358. isGroupedAggregate(_isGroupedAggregate),
  9359. aggregated(helper, helper)
  9360. {
  9361. eof = false;
  9362. gathered = false;
  9363. }
  9364. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9365. {
  9366. eof = false;
  9367. gathered = false;
  9368. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9369. }
  9370. virtual void reset()
  9371. {
  9372. aggregated.reset();
  9373. CRoxieServerActivity::reset();
  9374. }
  9375. virtual bool needsAllocator() const { return true; }
  9376. virtual const void * nextInGroup()
  9377. {
  9378. ActivityTimer t(totalCycles, timeActivities);
  9379. if (eof)
  9380. return NULL;
  9381. if (!gathered)
  9382. {
  9383. aggregated.start(rowAllocator);
  9384. bool eog = true;
  9385. loop
  9386. {
  9387. const void * next = input->nextInGroup();
  9388. if (!next)
  9389. {
  9390. if (isGroupedAggregate)
  9391. {
  9392. if (eog)
  9393. eof = true;
  9394. break;
  9395. }
  9396. next = input->nextInGroup();
  9397. if (!next)
  9398. break;
  9399. }
  9400. eog = false;
  9401. aggregated.addRow(next);
  9402. ReleaseRoxieRow(next);
  9403. }
  9404. gathered = true;
  9405. }
  9406. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9407. if (next)
  9408. {
  9409. processed++;
  9410. return next->finalizeRowClear();
  9411. }
  9412. if (!isGroupedAggregate)
  9413. eof = true;
  9414. aggregated.reset();
  9415. gathered = false;
  9416. return NULL;
  9417. }
  9418. };
  9419. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9420. {
  9421. public:
  9422. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9423. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9424. {
  9425. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9426. }
  9427. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9428. {
  9429. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9430. }
  9431. protected:
  9432. bool isGroupedAggregate;
  9433. };
  9434. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9435. {
  9436. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9437. }
  9438. //=================================================================================
  9439. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9440. {
  9441. IHThorDegroupArg &helper;
  9442. bool eof;
  9443. public:
  9444. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9445. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9446. {
  9447. eof = false;
  9448. }
  9449. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9450. {
  9451. eof = false;
  9452. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9453. }
  9454. virtual const void * nextInGroup()
  9455. {
  9456. ActivityTimer t(totalCycles, timeActivities);
  9457. if (eof)
  9458. return NULL;
  9459. const void * ret = input->nextInGroup();
  9460. if (!ret)
  9461. ret = input->nextInGroup();
  9462. if (ret)
  9463. processed++;
  9464. else
  9465. eof = true;
  9466. return ret;
  9467. }
  9468. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9469. {
  9470. ActivityTimer t(totalCycles, timeActivities);
  9471. if (eof)
  9472. return NULL;
  9473. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9474. if (ret)
  9475. processed++;
  9476. else
  9477. eof = true;
  9478. return ret;
  9479. }
  9480. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9481. {
  9482. return input->gatherConjunctions(collector);
  9483. }
  9484. virtual void resetEOF()
  9485. {
  9486. eof = false;
  9487. input->resetEOF();
  9488. }
  9489. IInputSteppingMeta * querySteppingMeta()
  9490. {
  9491. return input->querySteppingMeta();
  9492. }
  9493. };
  9494. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9495. {
  9496. public:
  9497. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9498. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9499. {
  9500. }
  9501. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9502. {
  9503. return new CRoxieServerDegroupActivity(this, _probeManager);
  9504. }
  9505. };
  9506. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9507. {
  9508. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9509. }
  9510. //=================================================================================
  9511. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9512. {
  9513. IHThorDiskReadArg &helper;
  9514. bool needTransform;
  9515. bool eof;
  9516. bool anyThisGroup;
  9517. unsigned __int64 rowLimit;
  9518. unsigned __int64 choosenLimit;
  9519. public:
  9520. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9521. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9522. {
  9523. needTransform = helper.needTransform();
  9524. rowLimit = (unsigned __int64) -1;
  9525. choosenLimit = 0;
  9526. eof = false;
  9527. anyThisGroup = false;
  9528. }
  9529. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9530. {
  9531. anyThisGroup = false;
  9532. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9533. if (helper.canMatchAny())
  9534. eof = false;
  9535. else
  9536. eof = true;
  9537. choosenLimit = helper.getChooseNLimit();
  9538. rowLimit = helper.getRowLimit();
  9539. helper.setCallback(NULL); // members should not be called - change if they are
  9540. }
  9541. virtual bool needsAllocator() const { return true; }
  9542. virtual const void * nextInGroup()
  9543. {
  9544. ActivityTimer t(totalCycles, timeActivities);
  9545. if (eof)
  9546. return NULL;
  9547. if (processed==choosenLimit)
  9548. {
  9549. eof = true;
  9550. return NULL;
  9551. }
  9552. if (needTransform)
  9553. {
  9554. loop
  9555. {
  9556. const void *in = input->nextInGroup();
  9557. if (!in)
  9558. {
  9559. if (anyThisGroup)
  9560. {
  9561. anyThisGroup = false;
  9562. return NULL;
  9563. }
  9564. in = input->nextInGroup();
  9565. if (!in)
  9566. {
  9567. eof = true;
  9568. return NULL; // eof...
  9569. }
  9570. }
  9571. unsigned outSize;
  9572. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9573. try
  9574. {
  9575. outSize = helper.transform(rowBuilder, in);
  9576. ReleaseRoxieRow(in);
  9577. }
  9578. catch (IException *E)
  9579. {
  9580. throw makeWrappedException(E);
  9581. }
  9582. if (outSize)
  9583. {
  9584. anyThisGroup = true;
  9585. processed++;
  9586. if (processed==rowLimit)
  9587. {
  9588. if (traceLevel > 4)
  9589. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9590. helper.onLimitExceeded();
  9591. }
  9592. return rowBuilder.finalizeRowClear(outSize);
  9593. }
  9594. }
  9595. }
  9596. else
  9597. {
  9598. const void *ret = input->nextInGroup();
  9599. if (ret)
  9600. {
  9601. processed++;
  9602. if (processed==rowLimit)
  9603. {
  9604. if (traceLevel > 4)
  9605. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9606. ReleaseClearRoxieRow(ret);
  9607. helper.onLimitExceeded(); // should not return
  9608. throwUnexpected();
  9609. }
  9610. }
  9611. return ret;
  9612. }
  9613. }
  9614. };
  9615. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9616. {
  9617. public:
  9618. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9619. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9620. {
  9621. }
  9622. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9623. {
  9624. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9625. }
  9626. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9627. {
  9628. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9629. setInput(0, source, sourceIdx);
  9630. else
  9631. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9632. }
  9633. };
  9634. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9635. {
  9636. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9637. }
  9638. //=================================================================================
  9639. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9640. {
  9641. public:
  9642. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9643. : CRoxieServerActivity(_factory, _probeManager)
  9644. {
  9645. }
  9646. ~CRoxieServerSpillWriteActivity()
  9647. {
  9648. }
  9649. virtual const void *nextInGroup()
  9650. {
  9651. ActivityTimer t(totalCycles, timeActivities);
  9652. return input->nextInGroup();
  9653. }
  9654. };
  9655. //==================================================================================
  9656. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9657. {
  9658. protected:
  9659. Owned<IExtRowWriter> outSeq;
  9660. Owned<IOutputRowSerializer> rowSerializer;
  9661. Linked<IFileIOStream> diskout;
  9662. bool blockcompressed;
  9663. bool extend;
  9664. bool overwrite;
  9665. bool encrypted;
  9666. bool grouped;
  9667. IHThorDiskWriteArg &helper;
  9668. CachedOutputMetaData diskmeta;
  9669. Owned<IRoxieWriteHandler> writer;
  9670. bool tallycrc;
  9671. unsigned __int64 uncompressedBytesWritten;
  9672. CRC32 crc;
  9673. void updateWorkUnitResult(unsigned __int64 reccount)
  9674. {
  9675. assertex(writer);
  9676. // MORE - a lot of this is common with hthor
  9677. WorkunitUpdate wu = ctx->updateWorkUnit();
  9678. if (wu)
  9679. {
  9680. OwnedRoxieString rawLogicalName = helper.getFileName();
  9681. StringBuffer lfn; // logical filename
  9682. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  9683. if (lfn.length())
  9684. {
  9685. unsigned flags = helper.getFlags();
  9686. WUFileKind fileKind;
  9687. if (TDXtemporary & flags)
  9688. fileKind = WUFileTemporary;
  9689. else if(TDXjobtemp & flags)
  9690. fileKind = WUFileJobOwned;
  9691. else if(TDWowned & flags)
  9692. fileKind = WUFileOwned;
  9693. else
  9694. fileKind = WUFileStandard;
  9695. StringArray clusters;
  9696. writer->getClusters(clusters);
  9697. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9698. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9699. {
  9700. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9701. if (result)
  9702. {
  9703. result->setResultTotalRowCount(reccount);
  9704. result->setResultStatus(ResultStatusCalculated);
  9705. if (helper.getFlags() & TDWresult)
  9706. result->setResultFilename(lfn.str());
  9707. else
  9708. result->setResultLogicalName(lfn.str());
  9709. }
  9710. }
  9711. }
  9712. }
  9713. }
  9714. void resolve()
  9715. {
  9716. OwnedRoxieString rawLogicalName = helper.getFileName();
  9717. assertex(rawLogicalName);
  9718. assertex((helper.getFlags() & TDXtemporary) == 0);
  9719. StringArray clusters;
  9720. unsigned clusterIdx = 0;
  9721. while(true)
  9722. {
  9723. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9724. if(!cluster)
  9725. break;
  9726. clusters.append(cluster);
  9727. clusterIdx++;
  9728. }
  9729. if (clusters.length())
  9730. {
  9731. if (extend)
  9732. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9733. }
  9734. else
  9735. {
  9736. if (roxieName.length())
  9737. clusters.append(roxieName.str());
  9738. else
  9739. clusters.append(".");
  9740. }
  9741. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  9742. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9743. }
  9744. public:
  9745. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9746. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  9747. {
  9748. extend = ((helper.getFlags() & TDWextend) != 0);
  9749. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9750. grouped = false; // don't think we need to support it...
  9751. diskmeta.set(helper.queryDiskRecordSize());
  9752. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9753. encrypted = false; // set later
  9754. tallycrc = true;
  9755. uncompressedBytesWritten = 0;
  9756. }
  9757. ~CRoxieServerDiskWriteActivity()
  9758. {
  9759. }
  9760. virtual bool needsAllocator() const
  9761. {
  9762. return true;
  9763. }
  9764. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9765. {
  9766. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9767. resolve();
  9768. Owned<IFileIO> io;
  9769. void *ekey;
  9770. size32_t ekeylen;
  9771. helper.getEncryptKey(ekeylen, ekey);
  9772. Owned<ICompressor> ecomp;
  9773. if (ekeylen!=0)
  9774. {
  9775. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9776. memset(ekey,0,ekeylen);
  9777. rtlFree(ekey);
  9778. encrypted = true;
  9779. blockcompressed = true;
  9780. }
  9781. if (blockcompressed)
  9782. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9783. else
  9784. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9785. if (!io)
  9786. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9787. diskout.setown(createBufferedIOStream(io));
  9788. if (extend)
  9789. diskout->seek(0, IFSend);
  9790. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9791. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9792. rowSerializer.set(rowIf->queryRowSerializer());
  9793. unsigned rwFlags = rw_autoflush;
  9794. if(grouped)
  9795. rwFlags |= rw_grouped;
  9796. if(tallycrc)
  9797. rwFlags |= rw_crc;
  9798. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9799. }
  9800. virtual void stop(bool aborting)
  9801. {
  9802. if (aborting)
  9803. {
  9804. if (writer)
  9805. writer->finish(false, this);
  9806. }
  9807. else
  9808. {
  9809. if (outSeq)
  9810. outSeq->flush(&crc);
  9811. if (outSeq)
  9812. uncompressedBytesWritten = outSeq->getPosition();
  9813. if (writer)
  9814. {
  9815. updateWorkUnitResult(processed);
  9816. writer->finish(true, this);
  9817. }
  9818. }
  9819. writer.clear();
  9820. CRoxieServerActivity::stop(aborting);
  9821. }
  9822. virtual void reset()
  9823. {
  9824. CRoxieServerActivity::reset();
  9825. diskout.clear();
  9826. outSeq.clear();
  9827. writer.clear();
  9828. uncompressedBytesWritten = 0;
  9829. crc.reset();
  9830. }
  9831. virtual void onExecute()
  9832. {
  9833. loop
  9834. {
  9835. const void *nextrec = input->nextInGroup();
  9836. if (!nextrec)
  9837. {
  9838. nextrec = input->nextInGroup();
  9839. if (!nextrec)
  9840. break;
  9841. }
  9842. processed++;
  9843. outSeq->putRow(nextrec);
  9844. }
  9845. }
  9846. virtual void setFileProperties(IFileDescriptor *desc) const
  9847. {
  9848. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9849. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9850. if (blockcompressed)
  9851. {
  9852. // caller has already set @size from file size...
  9853. fileProps.setPropBool("@blockCompressed", true);
  9854. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9855. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9856. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9857. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9858. }
  9859. else if (tallycrc)
  9860. partProps.setPropInt64("@fileCrc", crc.get());
  9861. if (encrypted)
  9862. fileProps.setPropBool("@encrypted", true);
  9863. fileProps.setPropInt64("@recordCount", processed);
  9864. unsigned flags = helper.getFlags();
  9865. if (flags & TDWpersist)
  9866. fileProps.setPropBool("@persistent", true);
  9867. if (grouped)
  9868. fileProps.setPropBool("@grouped", true);
  9869. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9870. fileProps.setPropBool("@owned", true);
  9871. if (flags & TDWresult)
  9872. fileProps.setPropBool("@result", true);
  9873. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9874. if (workUnit)
  9875. {
  9876. SCMStringBuffer owner, wuid, job;
  9877. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9878. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9879. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9880. }
  9881. if (flags & TDWexpires)
  9882. setExpiryTime(fileProps, helper.getExpiryDays());
  9883. if (flags & TDWupdate)
  9884. {
  9885. unsigned eclCRC;
  9886. unsigned __int64 totalCRC;
  9887. helper.getUpdateCRCs(eclCRC, totalCRC);
  9888. fileProps.setPropInt("@eclCRC", eclCRC);
  9889. fileProps.setPropInt64("@totalCRC", totalCRC);
  9890. }
  9891. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9892. IRecordSize * inputMeta = input->queryOutputMeta();
  9893. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9894. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9895. const char *recordECL = helper.queryRecordECL();
  9896. if (recordECL && *recordECL)
  9897. fileProps.setProp("ECL", recordECL);
  9898. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9899. }
  9900. virtual IUserDescriptor *queryUserDescriptor() const
  9901. {
  9902. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9903. if (workUnit)
  9904. return workUnit->queryUserDescriptor();
  9905. else
  9906. return NULL;
  9907. }
  9908. virtual bool isOutputTransformed() const { return false; }
  9909. };
  9910. //=================================================================================
  9911. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9912. {
  9913. IHThorCsvWriteArg &csvHelper;
  9914. CSVOutputStream csvOutput;
  9915. public:
  9916. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9917. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9918. {
  9919. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9920. }
  9921. virtual void onExecute()
  9922. {
  9923. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9924. if (header)
  9925. {
  9926. csvOutput.beginLine();
  9927. csvOutput.writeHeaderLn(strlen(header), header);
  9928. diskout->write(csvOutput.length(), csvOutput.str());
  9929. }
  9930. loop
  9931. {
  9932. const void *nextrec = input->nextInGroup();
  9933. if (!nextrec)
  9934. {
  9935. nextrec = input->nextInGroup();
  9936. if (!nextrec)
  9937. break;
  9938. }
  9939. processed++;
  9940. csvOutput.beginLine();
  9941. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9942. csvOutput.endLine();
  9943. diskout->write(csvOutput.length(), csvOutput.str());
  9944. ReleaseRoxieRow(nextrec);
  9945. }
  9946. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9947. if (footer)
  9948. {
  9949. csvOutput.beginLine();
  9950. csvOutput.writeHeaderLn(strlen(footer), footer);
  9951. diskout->write(csvOutput.length(), csvOutput.str());
  9952. }
  9953. }
  9954. virtual void setFileProperties(IFileDescriptor *desc) const
  9955. {
  9956. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9957. IPropertyTree &props = desc->queryProperties();
  9958. props.setProp("@format","utf8n");
  9959. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9960. StringBuffer separator;
  9961. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9962. const char *s = rs;
  9963. while (s && *s)
  9964. {
  9965. if (',' == *s)
  9966. separator.append("\\,");
  9967. else
  9968. separator.append(*s);
  9969. ++s;
  9970. }
  9971. props.setProp("@csvSeparate", separator.str());
  9972. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9973. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9974. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9975. props.setProp("@kind", "csv");
  9976. }
  9977. virtual bool isOutputTransformed() const { return true; }
  9978. };
  9979. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9980. {
  9981. IHThorXmlWriteArg &xmlHelper;
  9982. StringAttr rowTag;
  9983. ThorActivityKind kind;
  9984. unsigned headerLength;
  9985. unsigned footerLength;
  9986. public:
  9987. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  9988. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  9989. {
  9990. }
  9991. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9992. {
  9993. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9994. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9995. if (!xmlpath)
  9996. rowTag.set("Row");
  9997. else
  9998. {
  9999. const char *path = xmlpath;
  10000. if (*path == '/') path++;
  10001. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10002. rowTag.set(path);
  10003. }
  10004. }
  10005. virtual void onExecute()
  10006. {
  10007. StringBuffer header;
  10008. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10009. if (kind==TAKjsonwrite)
  10010. {
  10011. buildJsonHeader(header, suppliedHeader, rowTag);
  10012. headerLength = header.length();
  10013. }
  10014. else if (suppliedHeader)
  10015. header.set(suppliedHeader);
  10016. else
  10017. header.set("<Dataset>\n");
  10018. diskout->write(header.length(), header.str());
  10019. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10020. writer->outputBeginArray(rowTag); //need to set this
  10021. writer->clear(); //but not output it
  10022. loop
  10023. {
  10024. OwnedConstRoxieRow nextrec = input->nextInGroup();
  10025. if (!nextrec)
  10026. {
  10027. nextrec.setown(input->nextInGroup());
  10028. if (!nextrec)
  10029. break;
  10030. }
  10031. processed++;
  10032. writer->clear().outputBeginNested(rowTag, false);
  10033. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10034. writer->outputEndNested(rowTag);
  10035. diskout->write(writer->length(), writer->str());
  10036. }
  10037. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10038. StringBuffer footer;
  10039. if (kind==TAKjsonwrite)
  10040. {
  10041. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10042. footerLength=footer.length();
  10043. }
  10044. else if (suppliedFooter)
  10045. footer.append(suppliedFooter);
  10046. else
  10047. footer.append("</Dataset>");
  10048. diskout->write(footer.length(), footer);
  10049. }
  10050. virtual void reset()
  10051. {
  10052. CRoxieServerDiskWriteActivity::reset();
  10053. rowTag.clear();
  10054. }
  10055. virtual void setFileProperties(IFileDescriptor *desc) const
  10056. {
  10057. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10058. desc->queryProperties().setProp("@format","utf8n");
  10059. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10060. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10061. if (headerLength)
  10062. desc->queryProperties().setPropInt("@headerLength", headerLength);
  10063. if (footerLength)
  10064. desc->queryProperties().setPropInt("@footerLength", footerLength);
  10065. }
  10066. virtual bool isOutputTransformed() const { return true; }
  10067. };
  10068. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10069. {
  10070. bool isRoot;
  10071. bool isTemp;
  10072. public:
  10073. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10074. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  10075. {
  10076. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10077. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10078. setNumOutputs(helper->getTempUsageCount());
  10079. if (_kind!=TAKdiskwrite)
  10080. assertex(numOutputs == 0);
  10081. }
  10082. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10083. {
  10084. switch (numOutputs)
  10085. {
  10086. case 0:
  10087. switch (kind)
  10088. {
  10089. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  10090. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  10091. case TAKxmlwrite:
  10092. case TAKjsonwrite:
  10093. return new CRoxieServerXmlWriteActivity(this, _probeManager, kind);
  10094. };
  10095. throwUnexpected();
  10096. case 1:
  10097. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  10098. default:
  10099. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  10100. }
  10101. }
  10102. virtual bool isSink() const
  10103. {
  10104. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10105. }
  10106. };
  10107. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10108. {
  10109. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10110. }
  10111. //=================================================================================
  10112. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10113. {
  10114. IHThorIndexWriteArg &helper;
  10115. bool overwrite;
  10116. Owned<ClusterWriteHandler> clusterHandler;
  10117. Owned<IRoxieWriteHandler> writer;
  10118. unsigned __int64 reccount;
  10119. unsigned int fileCrc;
  10120. StringBuffer filename;
  10121. void updateWorkUnitResult()
  10122. {
  10123. // MORE - a lot of this is common with hthor
  10124. WorkunitUpdate wu = ctx->updateWorkUnit();
  10125. if (wu)
  10126. {
  10127. OwnedRoxieString rawLogicalName = helper.getFileName();
  10128. StringBuffer lfn; // logical filename
  10129. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10130. if (lfn.length())
  10131. {
  10132. if (helper.getSequence() >= 0)
  10133. {
  10134. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10135. if (result)
  10136. {
  10137. result->setResultTotalRowCount(reccount);
  10138. result->setResultStatus(ResultStatusCalculated);
  10139. result->setResultLogicalName(lfn.str());
  10140. }
  10141. }
  10142. if(clusterHandler)
  10143. clusterHandler->finish(writer->queryFile());
  10144. CTXLOG("Created roxie index file %s", lfn.str());
  10145. }
  10146. }
  10147. }
  10148. virtual void resolve()
  10149. {
  10150. StringArray clusters;
  10151. unsigned clusterIdx = 0;
  10152. while(true)
  10153. {
  10154. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10155. if(!cluster)
  10156. break;
  10157. clusters.append(cluster);
  10158. clusterIdx++;
  10159. }
  10160. if (roxieName.length())
  10161. clusters.append(roxieName.str());
  10162. else
  10163. clusters.append(".");
  10164. OwnedRoxieString fname(helper.getFileName());
  10165. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10166. filename.set(writer->queryFile()->queryFilename());
  10167. if (writer->queryFile()->exists())
  10168. {
  10169. if (overwrite)
  10170. {
  10171. CTXLOG("Removing existing %s from DFS",filename.str());
  10172. writer->queryFile()->remove();
  10173. }
  10174. else
  10175. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10176. }
  10177. }
  10178. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10179. {
  10180. size32_t nameLen;
  10181. char * nameBuff;
  10182. size32_t valueLen;
  10183. char * valueBuff;
  10184. unsigned idx = 0;
  10185. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10186. {
  10187. StringBuffer name(nameLen, nameBuff);
  10188. StringBuffer value(valueLen, valueBuff);
  10189. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10190. {
  10191. OwnedRoxieString fname(helper.getFileName());
  10192. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10193. }
  10194. if(!validateXMLTag(name.str()))
  10195. {
  10196. OwnedRoxieString fname(helper.getFileName());
  10197. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10198. }
  10199. if(!metadata)
  10200. metadata.setown(createPTree("metadata"));
  10201. metadata->setProp(name.str(), value.str());
  10202. }
  10203. }
  10204. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10205. {
  10206. if(!metadata)
  10207. metadata.setown(createPTree("metadata"));
  10208. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10209. void * layoutMetaBuff;
  10210. size32_t layoutMetaSize;
  10211. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10212. {
  10213. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10214. rtlFree(layoutMetaBuff);
  10215. }
  10216. }
  10217. public:
  10218. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10219. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10220. {
  10221. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10222. reccount = 0;
  10223. fileCrc = 0;
  10224. }
  10225. ~CRoxieServerIndexWriteActivity()
  10226. {
  10227. }
  10228. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10229. {
  10230. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10231. resolve();
  10232. }
  10233. virtual void onExecute()
  10234. {
  10235. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10236. size32_t maxDiskRecordSize;
  10237. if (isVariable)
  10238. {
  10239. if (helper.getFlags() & TIWmaxlength)
  10240. maxDiskRecordSize = helper.getMaxKeySize();
  10241. else
  10242. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10243. }
  10244. else
  10245. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10246. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10247. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10248. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10249. fileCrc = -1;
  10250. {
  10251. Owned<IFileIO> io;
  10252. try
  10253. {
  10254. io.setown(writer->queryFile()->open(IFOcreate));
  10255. }
  10256. catch(IException * e)
  10257. {
  10258. e->Release();
  10259. clearKeyStoreCache(false);
  10260. io.setown(writer->queryFile()->open(IFOcreate));
  10261. }
  10262. if(!io)
  10263. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10264. Owned<IFileIOStream> out = createIOStream(io);
  10265. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10266. if (helper.getFlags() & TIWrowcompress)
  10267. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10268. else if (!(helper.getFlags() & TIWnolzwcompress))
  10269. flags |= HTREE_COMPRESSED_KEY;
  10270. if (isVariable)
  10271. flags |= HTREE_VARSIZE;
  10272. Owned<IPropertyTree> metadata;
  10273. buildUserMetadata(metadata);
  10274. buildLayoutMetadata(metadata);
  10275. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10276. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10277. class BcWrapper : implements IBlobCreator
  10278. {
  10279. IKeyBuilder *builder;
  10280. public:
  10281. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10282. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10283. {
  10284. return builder->createBlob(size, (const char *) ptr);
  10285. }
  10286. } bc(builder);
  10287. // Loop thru the results
  10288. loop
  10289. {
  10290. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10291. if (!nextrec)
  10292. {
  10293. nextrec.setown(input->nextInGroup());
  10294. if (!nextrec)
  10295. break;
  10296. }
  10297. try
  10298. {
  10299. unsigned __int64 fpos;
  10300. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10301. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10302. builder->processKeyData(rowBuffer, fpos, thisSize);
  10303. }
  10304. catch(IException * e)
  10305. {
  10306. throw makeWrappedException(e);
  10307. }
  10308. reccount++;
  10309. }
  10310. if(metadata)
  10311. builder->finish(metadata,&fileCrc);
  10312. else
  10313. builder->finish(&fileCrc);
  10314. }
  10315. }
  10316. virtual void stop(bool aborting)
  10317. {
  10318. if (writer)
  10319. {
  10320. if (!aborting)
  10321. updateWorkUnitResult();
  10322. writer->finish(!aborting, this);
  10323. writer.clear();
  10324. }
  10325. CRoxieServerActivity::stop(aborting);
  10326. }
  10327. virtual void reset()
  10328. {
  10329. CRoxieServerActivity::reset();
  10330. writer.clear();
  10331. }
  10332. //interface IRoxiePublishCallback
  10333. virtual void setFileProperties(IFileDescriptor *desc) const
  10334. {
  10335. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10336. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10337. // Now publish to name services
  10338. StringBuffer dir,base;
  10339. offset_t indexFileSize = writer->queryFile()->size();
  10340. if(clusterHandler)
  10341. clusterHandler->splitPhysicalFilename(dir, base);
  10342. else
  10343. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10344. desc->setDefaultDir(dir.str());
  10345. //properties of the first file part.
  10346. Owned<IPropertyTree> attrs;
  10347. if(clusterHandler)
  10348. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10349. else
  10350. {
  10351. // add cluster
  10352. StringBuffer mygroupname;
  10353. desc->setNumParts(1);
  10354. desc->setPartMask(base.str());
  10355. attrs.set(&desc->queryPart(0)->queryProperties());
  10356. }
  10357. attrs->setPropInt64("@size", indexFileSize);
  10358. CDateTime createTime, modifiedTime, accessedTime;
  10359. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10360. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10361. unsigned hour, min, sec, nanosec;
  10362. modifiedTime.getTime(hour, min, sec, nanosec);
  10363. modifiedTime.setTime(hour, min, sec, 0);
  10364. StringBuffer timestr;
  10365. modifiedTime.getString(timestr);
  10366. if(timestr.length())
  10367. attrs->setProp("@modified", timestr.str());
  10368. if(clusterHandler)
  10369. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10370. // properties of the logical file
  10371. IPropertyTree & properties = desc->queryProperties();
  10372. properties.setProp("@kind", "key");
  10373. properties.setPropInt64("@size", indexFileSize);
  10374. properties.setPropInt64("@recordCount", reccount);
  10375. SCMStringBuffer info;
  10376. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10377. if (workUnit)
  10378. {
  10379. properties.setProp("@owner", workUnit->getUser(info).str());
  10380. info.clear();
  10381. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10382. info.clear();
  10383. properties.setProp("@job", workUnit->getJobName(info).str());
  10384. }
  10385. char const * rececl = helper.queryRecordECL();
  10386. if(rececl && *rececl)
  10387. properties.setProp("ECL", rececl);
  10388. if (helper.getFlags() & TIWexpires)
  10389. setExpiryTime(properties, helper.getExpiryDays());
  10390. if (helper.getFlags() & TIWupdate)
  10391. {
  10392. unsigned eclCRC;
  10393. unsigned __int64 totalCRC;
  10394. helper.getUpdateCRCs(eclCRC, totalCRC);
  10395. properties.setPropInt("@eclCRC", eclCRC);
  10396. properties.setPropInt64("@totalCRC", totalCRC);
  10397. }
  10398. properties.setPropInt("@fileCrc", fileCrc);
  10399. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10400. void * layoutMetaBuff;
  10401. size32_t layoutMetaSize;
  10402. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10403. {
  10404. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10405. rtlFree(layoutMetaBuff);
  10406. }
  10407. }
  10408. IUserDescriptor *queryUserDescriptor() const
  10409. {
  10410. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10411. if (workUnit)
  10412. return workUnit->queryUserDescriptor();
  10413. else
  10414. return NULL;
  10415. }
  10416. };
  10417. //=================================================================================
  10418. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10419. {
  10420. public:
  10421. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10422. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10423. {
  10424. setNumOutputs(0);
  10425. }
  10426. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10427. {
  10428. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10429. }
  10430. virtual bool isSink() const
  10431. {
  10432. return true;
  10433. }
  10434. };
  10435. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10436. {
  10437. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10438. }
  10439. //=================================================================================
  10440. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10441. {
  10442. if((flags & JFmatchAbortLimitSkips) != 0)
  10443. {
  10444. limitFail = false;
  10445. limitOnFail = false;
  10446. }
  10447. else
  10448. {
  10449. limitOnFail = ((flags & JFonfail) != 0);
  10450. limitFail = !limitOnFail;
  10451. }
  10452. }
  10453. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10454. {
  10455. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10456. IHThorJoinArg &helper;
  10457. ICompare * collate;
  10458. ICompare * collateupper;
  10459. ThorActivityKind activityKind;
  10460. bool leftOuterJoin;
  10461. bool rightOuterJoin;
  10462. bool exclude;
  10463. bool limitFail;
  10464. bool limitOnFail;
  10465. unsigned keepLimit;
  10466. unsigned joinLimit;
  10467. unsigned atmostLimit;
  10468. unsigned abortLimit;
  10469. unsigned atmostsTriggered;
  10470. bool betweenjoin;
  10471. OwnedRowArray right;
  10472. const void * left;
  10473. const void * pendingRight;
  10474. unsigned rightIndex;
  10475. unsigned joinCounter;
  10476. BoolArray matchedRight;
  10477. bool matchedLeft;
  10478. Owned<IException> failingLimit;
  10479. ConstPointerArray filteredRight;
  10480. Owned<IRHLimitedCompareHelper> limitedhelper;
  10481. OwnedConstRoxieRow defaultLeft;
  10482. OwnedConstRoxieRow defaultRight;
  10483. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10484. Owned<IEngineRowAllocator> defaultRightAllocator;
  10485. bool cloneLeft;
  10486. void createDefaultLeft()
  10487. {
  10488. if (!defaultLeft)
  10489. {
  10490. if (!defaultLeftAllocator)
  10491. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10492. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10493. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10494. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10495. }
  10496. }
  10497. void createDefaultRight()
  10498. {
  10499. if (!defaultRight)
  10500. {
  10501. if (!defaultRightAllocator)
  10502. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10503. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10504. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10505. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10506. }
  10507. }
  10508. public:
  10509. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10510. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10511. {
  10512. // MORE - some of this should be done in factory
  10513. unsigned joinFlags = helper.getJoinFlags();
  10514. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10515. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10516. exclude = (joinFlags & JFexclude) != 0;
  10517. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10518. getLimitType(joinFlags, limitFail, limitOnFail);
  10519. if (joinFlags & JFslidingmatch)
  10520. {
  10521. betweenjoin = true;
  10522. collate = helper.queryCompareLeftRightLower();
  10523. collateupper = helper.queryCompareLeftRightUpper();
  10524. }
  10525. else
  10526. {
  10527. betweenjoin = false;
  10528. collate = collateupper = helper.queryCompareLeftRight();
  10529. }
  10530. rightIndex = 0;
  10531. joinCounter = 0;
  10532. state = JSfill;
  10533. matchedLeft = false;
  10534. joinLimit = 0;
  10535. keepLimit = 0; // wait until ctx available
  10536. atmostLimit = 0; // wait until ctx available
  10537. abortLimit = 0; // wait until ctx available
  10538. atmostsTriggered = 0;
  10539. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10540. left = NULL;
  10541. pendingRight = NULL;
  10542. activityKind = _factory->getKind();
  10543. }
  10544. virtual bool needsAllocator() const { return true; }
  10545. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10546. {
  10547. left = NULL;
  10548. rightIndex = 0;
  10549. joinCounter = 0;
  10550. state = JSfill;
  10551. matchedLeft = false;
  10552. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10553. keepLimit = helper.getKeepLimit();
  10554. if (keepLimit == 0)
  10555. keepLimit = (unsigned)-1;
  10556. atmostsTriggered = 0;
  10557. atmostLimit = helper.getJoinLimit();
  10558. if(atmostLimit == 0)
  10559. atmostLimit = (unsigned)-1;
  10560. else
  10561. assertex(!rightOuterJoin && !betweenjoin);
  10562. abortLimit = helper.getMatchAbortLimit();
  10563. if (abortLimit == 0)
  10564. abortLimit = (unsigned)-1;
  10565. if (rightOuterJoin)
  10566. createDefaultLeft();
  10567. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10568. createDefaultRight();
  10569. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10570. { //limited match join (s[1..n])
  10571. limitedhelper.setown(createRHLimitedCompareHelper());
  10572. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10573. }
  10574. }
  10575. virtual void reset()
  10576. {
  10577. if (atmostsTriggered)
  10578. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  10579. right.clear();
  10580. ReleaseClearRoxieRow(left);
  10581. ReleaseClearRoxieRow(pendingRight);
  10582. defaultRight.clear();
  10583. defaultLeft.clear();
  10584. CRoxieServerTwoInputActivity::reset();
  10585. }
  10586. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10587. {
  10588. switch(idx)
  10589. {
  10590. case 0:
  10591. if ((helper.getJoinFlags() & JFparallel) != 0)
  10592. {
  10593. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10594. puller->setInput(0, _in);
  10595. _in = puller;
  10596. }
  10597. input = _in;
  10598. break;
  10599. case 1:
  10600. input1 = _in;
  10601. break;
  10602. default:
  10603. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10604. }
  10605. }
  10606. virtual IRoxieInput *queryOutput(unsigned idx)
  10607. {
  10608. if (idx==(unsigned)-1)
  10609. idx = 0;
  10610. return idx ? NULL : this;
  10611. }
  10612. void fillLeft()
  10613. {
  10614. matchedLeft = false;
  10615. left = input->nextInGroup();
  10616. if (!left)
  10617. left = input->nextInGroup();
  10618. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10619. fillRight();
  10620. if (limitedhelper && 0==rightIndex)
  10621. {
  10622. rightIndex = 0;
  10623. joinCounter = 0;
  10624. right.clear();
  10625. matchedRight.kill();
  10626. if (left)
  10627. {
  10628. limitedhelper->getGroup(right,left);
  10629. ForEachItemIn(idx, right)
  10630. matchedRight.append(false);
  10631. }
  10632. }
  10633. }
  10634. void fillRight()
  10635. {
  10636. if (limitedhelper)
  10637. return;
  10638. failingLimit.clear();
  10639. if(betweenjoin && left)
  10640. {
  10641. aindex_t start = 0;
  10642. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10643. start++;
  10644. if(start>0)
  10645. right.clearPart(0, start);
  10646. }
  10647. else
  10648. right.clear();
  10649. rightIndex = 0;
  10650. joinCounter = 0;
  10651. unsigned groupCount = 0;
  10652. const void * next;
  10653. while(true)
  10654. {
  10655. if(pendingRight)
  10656. {
  10657. next = pendingRight;
  10658. pendingRight = NULL;
  10659. }
  10660. else
  10661. {
  10662. next = input1->nextInGroup();
  10663. }
  10664. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10665. {
  10666. while(next)
  10667. {
  10668. ReleaseClearRoxieRow(next);
  10669. next = input1->nextInGroup();
  10670. }
  10671. continue;
  10672. }
  10673. while(next)
  10674. {
  10675. if(groupCount==abortLimit)
  10676. {
  10677. if(limitFail)
  10678. failLimit();
  10679. if (ctx->queryDebugContext())
  10680. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10681. if(limitOnFail)
  10682. {
  10683. assertex(!failingLimit);
  10684. try
  10685. {
  10686. failLimit();
  10687. }
  10688. catch(IException * except)
  10689. {
  10690. failingLimit.setown(except);
  10691. }
  10692. assertex(failingLimit != NULL);
  10693. }
  10694. right.append(next);
  10695. do
  10696. {
  10697. next = input1->nextInGroup();
  10698. ReleaseRoxieRow(next);
  10699. } while(next);
  10700. break;
  10701. }
  10702. else if(groupCount==atmostLimit)
  10703. {
  10704. atmostsTriggered++;
  10705. right.clear();
  10706. groupCount = 0;
  10707. while(next)
  10708. {
  10709. ReleaseRoxieRow(next);
  10710. next = input1->nextInGroup();
  10711. }
  10712. }
  10713. else
  10714. {
  10715. right.append(next);
  10716. groupCount++;
  10717. }
  10718. next = input1->nextInGroup();
  10719. }
  10720. // 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
  10721. if(betweenjoin && left)
  10722. {
  10723. pendingRight = input1->nextInGroup();
  10724. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10725. break;
  10726. }
  10727. else
  10728. break;
  10729. }
  10730. matchedRight.kill();
  10731. ForEachItemIn(idx, right)
  10732. matchedRight.append(false);
  10733. }
  10734. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  10735. {
  10736. if (cloneLeft)
  10737. {
  10738. LinkRoxieRow(curLeft);
  10739. return curLeft;
  10740. }
  10741. try
  10742. {
  10743. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10744. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  10745. if (thisSize)
  10746. return rowBuilder.finalizeRowClear(thisSize);
  10747. else
  10748. return NULL;
  10749. }
  10750. catch (IException *E)
  10751. {
  10752. throw makeWrappedException(E);
  10753. }
  10754. }
  10755. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10756. {
  10757. try
  10758. {
  10759. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10760. unsigned numRows = rows.ordinality();
  10761. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10762. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10763. if (thisSize)
  10764. return rowBuilder.finalizeRowClear(thisSize);
  10765. else
  10766. return NULL;
  10767. }
  10768. catch (IException *E)
  10769. {
  10770. throw makeWrappedException(E);
  10771. }
  10772. }
  10773. const void * joinException(const void * curLeft, IException * except)
  10774. {
  10775. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10776. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10777. return rowBuilder.finalizeRowClear(thisSize);
  10778. }
  10779. void failLimit()
  10780. {
  10781. helper.onMatchAbortLimitExceeded();
  10782. CommonXmlWriter xmlwrite(0);
  10783. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10784. {
  10785. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10786. }
  10787. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10788. }
  10789. virtual const void * nextInGroup()
  10790. {
  10791. ActivityTimer t(totalCycles, timeActivities);
  10792. loop
  10793. {
  10794. switch (state)
  10795. {
  10796. case JSfill:
  10797. fillLeft();
  10798. state = JSfillright;
  10799. break;
  10800. case JSfillright:
  10801. fillRight();
  10802. state = JScollate;
  10803. break;
  10804. case JSfillleft:
  10805. fillLeft();
  10806. state = JScollate;
  10807. break;
  10808. case JScollate:
  10809. if (right.ordinality() == 0)
  10810. {
  10811. if (left == NULL)
  10812. return NULL;
  10813. state = JSleftonly;
  10814. }
  10815. else
  10816. {
  10817. if (!left)
  10818. state = JSrightonly;
  10819. else
  10820. {
  10821. int diff;
  10822. if(betweenjoin)
  10823. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10824. else
  10825. diff = collate->docompare(left, right.item(0));
  10826. bool limitExceeded = right.ordinality()>abortLimit;
  10827. if (diff == 0)
  10828. {
  10829. if (limitExceeded)
  10830. {
  10831. const void * ret = NULL;
  10832. if(failingLimit)
  10833. ret = joinException(left, failingLimit);
  10834. ReleaseRoxieRow(left);
  10835. left = NULL;
  10836. state = JSfillleft;
  10837. ForEachItemIn(idx, right)
  10838. matchedRight.replace(true, idx);
  10839. if(ret)
  10840. {
  10841. processed++;
  10842. return ret;
  10843. }
  10844. }
  10845. else
  10846. {
  10847. state = JScompare;
  10848. joinLimit = keepLimit;
  10849. }
  10850. }
  10851. else if (diff < 0)
  10852. state = JSleftonly;
  10853. else if (limitExceeded)
  10854. {
  10855. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10856. state = JSfillright;
  10857. }
  10858. else
  10859. state = JSrightonly;
  10860. }
  10861. }
  10862. break;
  10863. case JSrightonly:
  10864. if (rightOuterJoin)
  10865. {
  10866. switch (activityKind)
  10867. {
  10868. case TAKjoin:
  10869. {
  10870. while (right.isItem(rightIndex))
  10871. {
  10872. if (!matchedRight.item(rightIndex))
  10873. {
  10874. const void * rhs = right.item(rightIndex++);
  10875. const void *ret = joinRecords(defaultLeft, rhs, 0);
  10876. if (ret)
  10877. {
  10878. processed++;
  10879. return ret;
  10880. }
  10881. }
  10882. else
  10883. rightIndex++;
  10884. }
  10885. break;
  10886. }
  10887. //Probably excessive to implement the following, but possibly useful
  10888. case TAKdenormalize:
  10889. {
  10890. OwnedConstRoxieRow newLeft;
  10891. newLeft.set(defaultLeft);
  10892. unsigned rowSize = 0;
  10893. unsigned leftCount = 0;
  10894. while (right.isItem(rightIndex))
  10895. {
  10896. if (!matchedRight.item(rightIndex))
  10897. {
  10898. const void * rhs = right.item(rightIndex);
  10899. try
  10900. {
  10901. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10902. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10903. if (thisSize)
  10904. {
  10905. rowSize = thisSize;
  10906. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10907. }
  10908. }
  10909. catch (IException *E)
  10910. {
  10911. throw makeWrappedException(E);
  10912. }
  10913. }
  10914. rightIndex++;
  10915. }
  10916. state = JSfillright;
  10917. if (rowSize)
  10918. {
  10919. processed++;
  10920. return newLeft.getClear();
  10921. }
  10922. break;
  10923. }
  10924. case TAKdenormalizegroup:
  10925. {
  10926. filteredRight.kill();
  10927. while (right.isItem(rightIndex))
  10928. {
  10929. if (!matchedRight.item(rightIndex))
  10930. filteredRight.append(right.item(rightIndex));
  10931. rightIndex++;
  10932. }
  10933. state = JSfillright;
  10934. if (filteredRight.ordinality())
  10935. {
  10936. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10937. filteredRight.kill();
  10938. if (ret)
  10939. {
  10940. processed++;
  10941. return ret;
  10942. }
  10943. }
  10944. break;
  10945. }
  10946. }
  10947. }
  10948. state = JSfillright;
  10949. break;
  10950. case JSleftonly:
  10951. {
  10952. const void * ret = NULL;
  10953. if (!matchedLeft && leftOuterJoin)
  10954. {
  10955. switch (activityKind)
  10956. {
  10957. case TAKjoin:
  10958. ret = joinRecords(left, defaultRight, 0);
  10959. break;
  10960. case TAKdenormalize:
  10961. ret = left;
  10962. left = NULL;
  10963. break;
  10964. case TAKdenormalizegroup:
  10965. filteredRight.kill();
  10966. ret = denormalizeRecords(left, filteredRight);
  10967. break;
  10968. }
  10969. }
  10970. ReleaseRoxieRow(left);
  10971. left = NULL;
  10972. state = JSfillleft;
  10973. if (ret)
  10974. {
  10975. processed++;
  10976. return ret;
  10977. }
  10978. break;
  10979. }
  10980. case JScompare:
  10981. if (joinLimit != 0)
  10982. {
  10983. switch (activityKind)
  10984. {
  10985. case TAKjoin:
  10986. {
  10987. while (right.isItem(rightIndex))
  10988. {
  10989. const void * rhs = right.item(rightIndex++);
  10990. if (helper.match(left, rhs))
  10991. {
  10992. matchedRight.replace(true, rightIndex-1);
  10993. matchedLeft = true;
  10994. if (!exclude)
  10995. {
  10996. const void *ret = joinRecords(left, rhs, ++joinCounter);
  10997. if (ret)
  10998. {
  10999. processed++;
  11000. joinLimit--;
  11001. return ret;
  11002. }
  11003. }
  11004. }
  11005. }
  11006. break;
  11007. }
  11008. case TAKdenormalize:
  11009. {
  11010. OwnedConstRoxieRow newLeft;
  11011. newLeft.set(left);
  11012. unsigned rowSize = 0;
  11013. unsigned leftCount = 0;
  11014. while (right.isItem(rightIndex) && joinLimit)
  11015. {
  11016. try
  11017. {
  11018. const void * rhs = right.item(rightIndex++);
  11019. if (helper.match(left, rhs))
  11020. {
  11021. matchedRight.replace(true, rightIndex-1);
  11022. matchedLeft = true;
  11023. if (!exclude)
  11024. {
  11025. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11026. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11027. if (thisSize)
  11028. {
  11029. rowSize = thisSize;
  11030. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11031. joinLimit--;
  11032. }
  11033. }
  11034. }
  11035. }
  11036. catch (IException *E)
  11037. {
  11038. throw makeWrappedException(E);
  11039. }
  11040. }
  11041. state = JSleftonly;
  11042. rightIndex = 0;
  11043. if (rowSize)
  11044. {
  11045. processed++;
  11046. return newLeft.getClear();
  11047. }
  11048. break;
  11049. }
  11050. case TAKdenormalizegroup:
  11051. {
  11052. filteredRight.kill();
  11053. while (right.isItem(rightIndex))
  11054. {
  11055. const void * rhs = right.item(rightIndex++);
  11056. if (helper.match(left, rhs))
  11057. {
  11058. matchedRight.replace(true, rightIndex-1);
  11059. filteredRight.append(rhs);
  11060. matchedLeft = true;
  11061. if (filteredRight.ordinality()==joinLimit)
  11062. break;
  11063. }
  11064. }
  11065. state = JSleftonly;
  11066. rightIndex = 0;
  11067. if (!exclude && filteredRight.ordinality())
  11068. {
  11069. const void * ret = denormalizeRecords(left, filteredRight);
  11070. filteredRight.kill();
  11071. if (ret)
  11072. {
  11073. processed++;
  11074. return ret;
  11075. }
  11076. }
  11077. break;
  11078. }
  11079. }
  11080. }
  11081. state = JSleftonly;
  11082. rightIndex = 0;
  11083. joinCounter = 0;
  11084. break;
  11085. }
  11086. }
  11087. }
  11088. };
  11089. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11090. {
  11091. unsigned input2;
  11092. unsigned input2idx;
  11093. public:
  11094. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11095. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11096. {
  11097. input2 = 0;
  11098. input2idx = 0;
  11099. }
  11100. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11101. {
  11102. return new CRoxieServerJoinActivity(this, _probeManager);
  11103. }
  11104. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11105. {
  11106. if (idx==1)
  11107. {
  11108. input2 = source;
  11109. input2idx = sourceidx;
  11110. }
  11111. else
  11112. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11113. }
  11114. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11115. {
  11116. switch (idx)
  11117. {
  11118. case 1:
  11119. sourceidx = input2idx;
  11120. return input2;
  11121. case 0:
  11122. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11123. default:
  11124. return (unsigned) -1;
  11125. }
  11126. }
  11127. virtual unsigned numInputs() const { return 2; }
  11128. virtual const StatisticsMapping &queryStatsMapping() const
  11129. {
  11130. return joinStatistics;
  11131. }
  11132. };
  11133. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11134. {
  11135. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11136. }
  11137. //=================================================================================
  11138. #define CONCAT_READAHEAD 1000
  11139. class CRoxieThreadedConcatReader : public CInterface, implements IRecordPullerCallback
  11140. {
  11141. public:
  11142. IMPLEMENT_IINTERFACE;
  11143. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11144. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11145. {
  11146. }
  11147. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11148. {
  11149. space.reinit(CONCAT_READAHEAD);
  11150. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11151. }
  11152. void stop(bool aborting)
  11153. {
  11154. space.interrupt();
  11155. puller.stop(aborting);
  11156. }
  11157. IRoxieInput *queryInput() const
  11158. {
  11159. return puller.queryInput();
  11160. }
  11161. void reset()
  11162. {
  11163. puller.reset();
  11164. ForEachItemIn(idx, buffer)
  11165. ReleaseRoxieRow(buffer.item(idx));
  11166. buffer.clear();
  11167. eof = false;
  11168. atEog = true;
  11169. }
  11170. void setInput(IRoxieInput *_in)
  11171. {
  11172. puller.setInput(this, _in);
  11173. }
  11174. virtual void processRow(const void *row)
  11175. {
  11176. buffer.enqueue(row);
  11177. ready.signal();
  11178. space.wait();
  11179. }
  11180. virtual void processGroup(const ConstPointerArray &rows)
  11181. {
  11182. // We use record-by-record input mode of the puller thread even in grouped mode.
  11183. throwUnexpected();
  11184. }
  11185. virtual void processEOG()
  11186. {
  11187. if (grouped)
  11188. processRow(NULL);
  11189. }
  11190. virtual void processDone()
  11191. {
  11192. processRow(NULL);
  11193. }
  11194. virtual bool fireException(IException *e)
  11195. {
  11196. // called from puller thread on failure
  11197. ready.interrupt(LINK(e));
  11198. space.interrupt(e);
  11199. return true;
  11200. }
  11201. bool peek(const void * &row, bool &anyActive)
  11202. {
  11203. if (!eof)
  11204. {
  11205. if (buffer.ordinality())
  11206. {
  11207. space.signal();
  11208. row = buffer.dequeue();
  11209. if (row==NULL)
  11210. {
  11211. if (atEog)
  11212. {
  11213. eof = true;
  11214. return false;
  11215. }
  11216. else
  11217. atEog = true;
  11218. }
  11219. else if (grouped)
  11220. atEog = false;
  11221. return true;
  11222. }
  11223. anyActive = true;
  11224. }
  11225. return false;
  11226. }
  11227. protected:
  11228. RecordPullerThread puller;
  11229. InterruptableSemaphore space;
  11230. InterruptableSemaphore &ready;
  11231. SafeQueueOf<const void, true> buffer;
  11232. bool atEog;
  11233. bool eof;
  11234. bool grouped;
  11235. };
  11236. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11237. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11238. {
  11239. InterruptableSemaphore ready;
  11240. ReaderArray pullers;
  11241. unsigned numInputs;
  11242. unsigned nextPuller; // for round robin
  11243. unsigned readyPending;
  11244. bool eof;
  11245. bool inGroup;
  11246. bool grouped;
  11247. public:
  11248. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11249. : CRoxieServerActivity(_factory, _probeManager), grouped(_grouped)
  11250. {
  11251. numInputs = _numInputs;
  11252. eof = (numInputs==0);
  11253. inGroup = false;
  11254. nextPuller = 0;
  11255. readyPending = 0;
  11256. for (unsigned i = 0; i < numInputs; i++)
  11257. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11258. }
  11259. ~CRoxieServerThreadedConcatActivity()
  11260. {
  11261. ForEachItemIn(idx, pullers)
  11262. delete &pullers.item(idx);
  11263. }
  11264. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11265. {
  11266. eof = (numInputs==0);
  11267. inGroup = false;
  11268. nextPuller = 0;
  11269. readyPending = 0;
  11270. ready.reinit();
  11271. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11272. ForEachItemIn(idx, pullers)
  11273. {
  11274. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11275. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11276. // in the part of the subgraph that the thread uses has been started.
  11277. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11278. }
  11279. }
  11280. virtual void stop(bool aborting)
  11281. {
  11282. ready.interrupt();
  11283. ForEachItemIn(idx, pullers)
  11284. pullers.item(idx).stop(aborting);
  11285. CRoxieServerActivity::stop(aborting);
  11286. }
  11287. virtual unsigned __int64 queryLocalCycles() const
  11288. {
  11289. return 0;
  11290. }
  11291. virtual IRoxieInput *queryInput(unsigned idx) const
  11292. {
  11293. if (pullers.isItem(idx))
  11294. return pullers.item(idx).queryInput();
  11295. else
  11296. return NULL;
  11297. }
  11298. virtual void reset()
  11299. {
  11300. CRoxieServerActivity::reset();
  11301. ForEachItemIn(idx, pullers)
  11302. pullers.item(idx).reset();
  11303. eof = false;
  11304. inGroup = false;
  11305. nextPuller = 0;
  11306. readyPending = 0;
  11307. }
  11308. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11309. {
  11310. if (pullers.isItem(idx))
  11311. pullers.item(idx).setInput(_in);
  11312. else
  11313. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11314. }
  11315. virtual const void * nextInGroup()
  11316. {
  11317. ActivityTimer t(totalCycles, timeActivities);
  11318. if (eof)
  11319. return NULL;
  11320. loop
  11321. {
  11322. if (readyPending && !inGroup)
  11323. {
  11324. if (readyPending > 1)
  11325. ready.signal(readyPending-1);
  11326. readyPending = 0;
  11327. }
  11328. else
  11329. ready.wait();
  11330. bool anyActive = false;
  11331. ForEachItemIn(unused_index, pullers)
  11332. {
  11333. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11334. const void *ret;
  11335. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11336. if (fetched)
  11337. {
  11338. inGroup = (ret != NULL);
  11339. return ret;
  11340. }
  11341. if (inGroup && grouped)
  11342. {
  11343. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11344. readyPending++;
  11345. anyActive = true;
  11346. break;
  11347. }
  11348. nextPuller++;
  11349. if (nextPuller==pullers.ordinality())
  11350. nextPuller = 0;
  11351. }
  11352. if (!anyActive)
  11353. break;
  11354. // A ready signal without anything being ready means someone reached end-of-file.
  11355. }
  11356. eof = true;
  11357. return NULL;
  11358. }
  11359. };
  11360. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11361. {
  11362. IRoxieInput *curInput;
  11363. bool eogSeen;
  11364. bool anyThisGroup;
  11365. bool grouped;
  11366. unsigned numInputs;
  11367. unsigned inputIdx;
  11368. IRoxieInput **inputArray;
  11369. public:
  11370. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11371. : CRoxieServerActivity(_factory, _probeManager)
  11372. {
  11373. eogSeen = false;
  11374. anyThisGroup = false;
  11375. grouped = _grouped;
  11376. numInputs = _numInputs;
  11377. inputIdx = 0;
  11378. inputArray = new IRoxieInput*[numInputs];
  11379. for (unsigned i = 0; i < numInputs; i++)
  11380. inputArray[i] = NULL;
  11381. curInput = NULL;
  11382. }
  11383. ~CRoxieServerOrderedConcatActivity()
  11384. {
  11385. delete [] inputArray;
  11386. }
  11387. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11388. {
  11389. inputIdx = 0;
  11390. curInput = inputArray[inputIdx];
  11391. eogSeen = false;
  11392. anyThisGroup = false;
  11393. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11394. for (unsigned i = 0; i < numInputs; i++)
  11395. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11396. }
  11397. virtual void stop(bool aborting)
  11398. {
  11399. for (unsigned i = 0; i < numInputs; i++)
  11400. inputArray[i]->stop(aborting);
  11401. CRoxieServerActivity::stop(aborting);
  11402. }
  11403. virtual unsigned __int64 queryLocalCycles() const
  11404. {
  11405. return 0;
  11406. }
  11407. virtual IRoxieInput *queryInput(unsigned idx) const
  11408. {
  11409. if (idx < numInputs)
  11410. return inputArray[idx];
  11411. else
  11412. return NULL;
  11413. }
  11414. virtual void reset()
  11415. {
  11416. CRoxieServerActivity::reset();
  11417. for (unsigned i = 0; i < numInputs; i++)
  11418. inputArray[i]->reset();
  11419. }
  11420. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11421. {
  11422. inputArray[idx] = _in;
  11423. }
  11424. virtual const void * nextInGroup()
  11425. {
  11426. ActivityTimer t(totalCycles, timeActivities);
  11427. if (!curInput)
  11428. return NULL; // eof
  11429. const void * next = curInput->nextInGroup();
  11430. if (next)
  11431. {
  11432. anyThisGroup = true;
  11433. eogSeen = false;
  11434. processed++;
  11435. return next;
  11436. }
  11437. else if (!eogSeen)
  11438. {
  11439. eogSeen = true;
  11440. if (grouped)
  11441. {
  11442. if (anyThisGroup)
  11443. {
  11444. anyThisGroup = false;
  11445. return NULL;
  11446. }
  11447. else
  11448. return nextInGroup();
  11449. }
  11450. else
  11451. return nextInGroup();
  11452. }
  11453. else if (inputIdx < numInputs-1)
  11454. {
  11455. inputIdx++;
  11456. curInput = inputArray[inputIdx];
  11457. eogSeen = false;
  11458. return nextInGroup();
  11459. }
  11460. else
  11461. {
  11462. curInput = NULL;
  11463. return NULL;
  11464. }
  11465. }
  11466. };
  11467. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11468. {
  11469. bool ordered;
  11470. bool grouped;
  11471. public:
  11472. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11473. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11474. {
  11475. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11476. ordered = helper->isOrdered();
  11477. grouped = helper->queryOutputMeta()->isGrouped();
  11478. }
  11479. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11480. {
  11481. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11482. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11483. else
  11484. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11485. }
  11486. };
  11487. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11488. {
  11489. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11490. }
  11491. //=================================================================================
  11492. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11493. {
  11494. IRoxieInput * selectedInput;
  11495. unsigned savedParentExtractSize;
  11496. const byte * savedParentExtract;
  11497. bool foundInput;
  11498. public:
  11499. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11500. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11501. {
  11502. foundInput = false;
  11503. selectedInput = NULL;
  11504. savedParentExtractSize = 0;;
  11505. savedParentExtract = NULL;
  11506. }
  11507. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11508. {
  11509. //Don't start the inputs yet so we can short-circuit...
  11510. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11511. savedParentExtractSize = parentExtractSize;
  11512. savedParentExtract = parentExtract;
  11513. }
  11514. virtual void stop(bool aborting)
  11515. {
  11516. if (foundInput)
  11517. {
  11518. if (selectedInput)
  11519. selectedInput->stop(aborting);
  11520. }
  11521. else
  11522. {
  11523. for (unsigned i = 0; i < numInputs; i++)
  11524. inputArray[i]->stop(aborting);
  11525. }
  11526. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11527. }
  11528. virtual void reset()
  11529. {
  11530. CRoxieServerMultiInputBaseActivity::reset();
  11531. foundInput = false;
  11532. selectedInput = NULL;
  11533. }
  11534. virtual unsigned __int64 queryLocalCycles() const
  11535. {
  11536. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11537. }
  11538. virtual const void * nextInGroup()
  11539. {
  11540. ActivityTimer t(totalCycles, timeActivities);
  11541. if (!foundInput)
  11542. {
  11543. foundInput = true;
  11544. //If we get an exception in this loop then stop() will stop any started inputs
  11545. for (unsigned i=0; i < numInputs; i++)
  11546. {
  11547. selectedInput = inputArray[i];
  11548. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11549. const void * next = selectedInput->nextInGroup();
  11550. if (next)
  11551. {
  11552. //Found a row so stop remaining
  11553. for (unsigned j=i+1; j < numInputs; j++)
  11554. inputArray[j]->stop(false);
  11555. processed++;
  11556. return next;
  11557. }
  11558. selectedInput->stop(false);
  11559. }
  11560. selectedInput = NULL;
  11561. return NULL;
  11562. }
  11563. if (!selectedInput)
  11564. return NULL;
  11565. const void * next = selectedInput->nextInGroup();
  11566. if (next)
  11567. processed++;
  11568. return next;
  11569. }
  11570. };
  11571. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11572. {
  11573. public:
  11574. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11575. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11576. {
  11577. }
  11578. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11579. {
  11580. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11581. }
  11582. };
  11583. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11584. {
  11585. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11586. }
  11587. //=================================================================================
  11588. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11589. {
  11590. IHThorMergeArg &helper;
  11591. unsigned *mergeheap;
  11592. unsigned activeInputs;
  11593. unsigned numInputs;
  11594. IRoxieInput **inputArray;
  11595. const void **pending;
  11596. bool first;
  11597. ICompare *compare;
  11598. bool dedup;
  11599. void permute()
  11600. {
  11601. assertex(activeInputs == 0);
  11602. for(unsigned i = 0; i < numInputs; i++)
  11603. if(pullInput(i))
  11604. mergeheap[activeInputs++] = i;
  11605. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11606. // the heap property: no element should be smaller than its parent
  11607. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11608. // 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
  11609. if (activeInputs >= 2)
  11610. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11611. siftDown(p);
  11612. if(dedup)
  11613. siftDownDedupTop();
  11614. else
  11615. siftDown(0);
  11616. }
  11617. void readNext()
  11618. {
  11619. if(!pullInput(mergeheap[0]))
  11620. if(!promote(0))
  11621. return;
  11622. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11623. if(dedup)
  11624. siftDownDedupTop();
  11625. else
  11626. siftDown(0);
  11627. }
  11628. bool pullInput(unsigned i)
  11629. {
  11630. const void *next = inputArray[i]->nextInGroup();
  11631. if (!next)
  11632. next = inputArray[i]->nextInGroup();
  11633. pending[i] = next;
  11634. return (next != NULL);
  11635. }
  11636. bool promote(unsigned p)
  11637. {
  11638. activeInputs--;
  11639. if(activeInputs == p)
  11640. return false;
  11641. mergeheap[p] = mergeheap[activeInputs];
  11642. return true;
  11643. }
  11644. bool siftDown(unsigned p)
  11645. {
  11646. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11647. bool nochange = true;
  11648. while(1)
  11649. {
  11650. unsigned c = p*2 + 1;
  11651. if(c >= activeInputs)
  11652. return nochange;
  11653. if(c+1 < activeInputs)
  11654. {
  11655. int childcmp = BuffCompare(c+1, c);
  11656. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11657. ++c;
  11658. }
  11659. int cmp = BuffCompare(c, p);
  11660. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11661. return nochange;
  11662. nochange = false;
  11663. unsigned r = mergeheap[c];
  11664. mergeheap[c] = mergeheap[p];
  11665. mergeheap[p] = r;
  11666. p = c;
  11667. }
  11668. }
  11669. void siftDownDedupTop()
  11670. {
  11671. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11672. if(activeInputs < 2)
  11673. return;
  11674. unsigned c = 1;
  11675. int childcmp = 1;
  11676. if(activeInputs >= 3)
  11677. {
  11678. childcmp = BuffCompare(2, 1);
  11679. if(childcmp < 0)
  11680. c = 2;
  11681. }
  11682. int cmp = BuffCompare(c, 0);
  11683. if(cmp > 0)
  11684. return;
  11685. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11686. while(cmp <= 0)
  11687. {
  11688. if(cmp == 0)
  11689. {
  11690. if(mergeheap[c] < mergeheap[0])
  11691. {
  11692. unsigned r = mergeheap[c];
  11693. mergeheap[c] = mergeheap[0];
  11694. mergeheap[0] = r;
  11695. }
  11696. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11697. if(!pullInput(mergeheap[c]))
  11698. if(!promote(c))
  11699. break;
  11700. siftDown(c);
  11701. }
  11702. else
  11703. {
  11704. unsigned r = mergeheap[c];
  11705. mergeheap[c] = mergeheap[0];
  11706. mergeheap[0] = r;
  11707. if(siftDown(c))
  11708. break;
  11709. }
  11710. cmp = BuffCompare(c, 0);
  11711. }
  11712. // the following loop ensures the uniqueness property holds on the other branch too
  11713. c = 3-c;
  11714. if(activeInputs <= c)
  11715. return;
  11716. while(childcmp == 0)
  11717. {
  11718. if(mergeheap[c] < mergeheap[0])
  11719. {
  11720. unsigned r = mergeheap[c];
  11721. mergeheap[c] = mergeheap[0];
  11722. mergeheap[0] = r;
  11723. }
  11724. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11725. if(!pullInput(mergeheap[c]))
  11726. if(!promote(c))
  11727. break;
  11728. siftDown(c);
  11729. childcmp = BuffCompare(c, 0);
  11730. }
  11731. }
  11732. inline int BuffCompare(unsigned a, unsigned b)
  11733. {
  11734. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11735. }
  11736. public:
  11737. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11738. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11739. {
  11740. activeInputs = 0;
  11741. first = true;
  11742. mergeheap = new unsigned[numInputs];
  11743. inputArray = new IRoxieInput*[numInputs];
  11744. pending = new const void *[numInputs];
  11745. compare = helper.queryCompare();
  11746. dedup = helper.dedup();
  11747. for (unsigned i = 0; i < numInputs; i++)
  11748. {
  11749. inputArray[i] = NULL;
  11750. pending[i] = NULL;
  11751. }
  11752. }
  11753. ~CRoxieServerMergeActivity()
  11754. {
  11755. delete [] mergeheap;
  11756. delete [] inputArray;
  11757. delete [] pending;
  11758. }
  11759. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11760. {
  11761. activeInputs = 0;
  11762. first = true;
  11763. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11764. for (unsigned i = 0; i < numInputs; i++)
  11765. {
  11766. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11767. }
  11768. }
  11769. virtual void stop(bool aborting)
  11770. {
  11771. for (unsigned i = 0; i < numInputs; i++)
  11772. {
  11773. inputArray[i]->stop(aborting);
  11774. }
  11775. CRoxieServerActivity::stop(aborting);
  11776. }
  11777. virtual void reset()
  11778. {
  11779. for (unsigned i = 0; i < numInputs; i++)
  11780. {
  11781. ReleaseClearRoxieRow(pending[i]);
  11782. inputArray[i]->reset();
  11783. }
  11784. CRoxieServerActivity::reset();
  11785. }
  11786. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11787. {
  11788. inputArray[idx] = _in;
  11789. }
  11790. virtual const void * nextInGroup()
  11791. {
  11792. ActivityTimer t(totalCycles, timeActivities);
  11793. if (first)
  11794. {
  11795. permute();
  11796. first = false;
  11797. }
  11798. if (activeInputs)
  11799. {
  11800. const void *next = pending[mergeheap[0]];
  11801. readNext();
  11802. if (next)
  11803. processed++;
  11804. return next;
  11805. }
  11806. else
  11807. return NULL;
  11808. }
  11809. };
  11810. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11811. {
  11812. public:
  11813. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11814. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11815. {
  11816. }
  11817. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11818. {
  11819. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11820. }
  11821. };
  11822. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11823. {
  11824. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11825. }
  11826. //=================================================================================
  11827. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11828. {
  11829. IHThorRegroupArg &helper;
  11830. unsigned inputIndex;
  11831. bool eof;
  11832. unsigned __int64 numProcessedLastGroup;
  11833. public:
  11834. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11835. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11836. {
  11837. inputIndex = 0;
  11838. eof = false;
  11839. numProcessedLastGroup = 0;
  11840. }
  11841. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11842. {
  11843. inputIndex = 0;
  11844. eof = false;
  11845. numProcessedLastGroup = processed;
  11846. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11847. }
  11848. const void * nextFromInputs()
  11849. {
  11850. unsigned initialInput = inputIndex;
  11851. while (inputIndex < numInputs)
  11852. {
  11853. const void * next = inputArray[inputIndex]->nextInGroup();
  11854. if (next)
  11855. {
  11856. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11857. {
  11858. ReleaseRoxieRow(next);
  11859. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11860. }
  11861. return next;
  11862. }
  11863. inputIndex++;
  11864. }
  11865. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11866. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11867. inputIndex = 0;
  11868. return NULL;
  11869. }
  11870. virtual const void * nextInGroup()
  11871. {
  11872. ActivityTimer t(totalCycles, timeActivities);
  11873. if (eof)
  11874. return NULL;
  11875. const void * ret = nextFromInputs();
  11876. if (ret)
  11877. {
  11878. processed++;
  11879. return ret;
  11880. }
  11881. if (numProcessedLastGroup != processed)
  11882. {
  11883. numProcessedLastGroup = processed;
  11884. return NULL;
  11885. }
  11886. eof = true;
  11887. return NULL;
  11888. }
  11889. #if 0
  11890. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11891. {
  11892. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11893. if (idx)
  11894. {
  11895. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11896. puller->setInput(0, _in);
  11897. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11898. }
  11899. else
  11900. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11901. }
  11902. #endif
  11903. };
  11904. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11905. {
  11906. public:
  11907. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11908. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11909. {
  11910. }
  11911. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11912. {
  11913. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11914. }
  11915. };
  11916. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11917. {
  11918. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11919. }
  11920. //=================================================================================
  11921. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11922. {
  11923. IHThorCombineArg &helper;
  11924. unsigned __int64 numProcessedLastGroup;
  11925. public:
  11926. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11927. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11928. {
  11929. numProcessedLastGroup = 0;
  11930. }
  11931. ~CRoxieServerCombineActivity()
  11932. {
  11933. }
  11934. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11935. {
  11936. numProcessedLastGroup = processed;
  11937. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11938. }
  11939. void nextInputs(ConstPointerArray & out)
  11940. {
  11941. for (unsigned i=0; i < numInputs; i++)
  11942. {
  11943. const void * next = inputArray[i]->nextInGroup();
  11944. if (next)
  11945. out.append(next);
  11946. }
  11947. }
  11948. virtual bool needsAllocator() const { return true; }
  11949. virtual const void * nextInGroup()
  11950. {
  11951. ActivityTimer t(totalCycles, timeActivities);
  11952. loop
  11953. {
  11954. ConstPointerArray group;
  11955. nextInputs(group);
  11956. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11957. nextInputs(group);
  11958. if (group.ordinality() == 0)
  11959. {
  11960. numProcessedLastGroup = processed;
  11961. return NULL;
  11962. }
  11963. else if (group.ordinality() != numInputs)
  11964. {
  11965. ReleaseRoxieRowSet(group);
  11966. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11967. }
  11968. try
  11969. {
  11970. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11971. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11972. ReleaseRoxieRowSet(group);
  11973. if (outSize)
  11974. {
  11975. processed++;
  11976. return rowBuilder.finalizeRowClear(outSize);
  11977. }
  11978. }
  11979. catch (IException *E)
  11980. {
  11981. ReleaseRoxieRowSet(group);
  11982. throw makeWrappedException(E);
  11983. }
  11984. }
  11985. }
  11986. };
  11987. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11988. {
  11989. public:
  11990. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11991. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11992. {
  11993. }
  11994. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11995. {
  11996. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11997. }
  11998. };
  11999. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12000. {
  12001. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12002. }
  12003. //=================================================================================
  12004. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12005. {
  12006. IHThorCombineGroupArg &helper;
  12007. unsigned __int64 numProcessedLastGroup;
  12008. public:
  12009. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12010. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12011. {
  12012. numProcessedLastGroup = 0;
  12013. }
  12014. ~CRoxieServerCombineGroupActivity()
  12015. {
  12016. }
  12017. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12018. {
  12019. numProcessedLastGroup = processed;
  12020. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12021. }
  12022. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12023. {
  12024. switch(idx)
  12025. {
  12026. case 0:
  12027. #if 0
  12028. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  12029. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  12030. puller->setInput(0, _in);
  12031. _in = puller;
  12032. #endif
  12033. input = _in;
  12034. break;
  12035. case 1:
  12036. input1 = _in;
  12037. break;
  12038. default:
  12039. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12040. }
  12041. }
  12042. virtual IRoxieInput *queryOutput(unsigned idx)
  12043. {
  12044. if (idx==(unsigned)-1)
  12045. idx = 0;
  12046. return idx ? NULL : this;
  12047. }
  12048. virtual bool needsAllocator() const { return true; }
  12049. virtual const void * nextInGroup()
  12050. {
  12051. ActivityTimer t(totalCycles, timeActivities);
  12052. loop
  12053. {
  12054. const void * left = input->nextInGroup();
  12055. if (!left && (numProcessedLastGroup == processed))
  12056. left = input->nextInGroup();
  12057. if (!left)
  12058. {
  12059. if (numProcessedLastGroup == processed)
  12060. {
  12061. const void * nextRight = input1->nextInGroup();
  12062. if (nextRight)
  12063. {
  12064. ReleaseRoxieRow(nextRight);
  12065. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12066. }
  12067. }
  12068. else
  12069. numProcessedLastGroup = processed;
  12070. return NULL;
  12071. }
  12072. ConstPointerArray group;
  12073. loop
  12074. {
  12075. const void * in = input1->nextInGroup();
  12076. if (!in)
  12077. break;
  12078. group.append(in);
  12079. }
  12080. if (group.ordinality() == 0)
  12081. {
  12082. ReleaseRoxieRow(left);
  12083. ReleaseRoxieRowSet(group);
  12084. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12085. }
  12086. try
  12087. {
  12088. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12089. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12090. ReleaseRoxieRow(left);
  12091. ReleaseRoxieRowSet(group);
  12092. if (outSize)
  12093. {
  12094. processed++;
  12095. return rowBuilder.finalizeRowClear(outSize);
  12096. }
  12097. }
  12098. catch (IException *E)
  12099. {
  12100. ReleaseRoxieRow(left);
  12101. ReleaseRoxieRowSet(group);
  12102. throw makeWrappedException(E);
  12103. }
  12104. }
  12105. }
  12106. };
  12107. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12108. {
  12109. unsigned input2;
  12110. unsigned input2idx;
  12111. public:
  12112. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12113. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12114. {
  12115. input2 = 0;
  12116. input2idx = 0;
  12117. }
  12118. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12119. {
  12120. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  12121. }
  12122. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12123. {
  12124. if (idx==1)
  12125. {
  12126. input2 = source;
  12127. input2idx = sourceidx;
  12128. }
  12129. else
  12130. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12131. }
  12132. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12133. {
  12134. switch (idx)
  12135. {
  12136. case 1:
  12137. sourceidx = input2idx;
  12138. return input2;
  12139. case 0:
  12140. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12141. default:
  12142. return (unsigned) -1;
  12143. }
  12144. }
  12145. virtual unsigned numInputs() const { return 2; }
  12146. };
  12147. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12148. {
  12149. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12150. }
  12151. //=================================================================================
  12152. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12153. {
  12154. IHThorRollupGroupArg &helper;
  12155. bool eof;
  12156. public:
  12157. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12158. : CRoxieServerActivity(_factory, _probeManager),
  12159. helper((IHThorRollupGroupArg &)basehelper)
  12160. {
  12161. eof = false;
  12162. }
  12163. ~CRoxieServerRollupGroupActivity()
  12164. {
  12165. }
  12166. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12167. {
  12168. eof = false;
  12169. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12170. }
  12171. virtual bool needsAllocator() const { return true; }
  12172. virtual const void * nextInGroup()
  12173. {
  12174. ActivityTimer t(totalCycles, timeActivities);
  12175. if (eof)
  12176. return NULL;
  12177. loop
  12178. {
  12179. ConstPointerArray group;
  12180. loop
  12181. {
  12182. const void * in = input->nextInGroup();
  12183. if (!in)
  12184. break;
  12185. group.append(in);
  12186. }
  12187. if (group.ordinality() == 0)
  12188. {
  12189. eof = true;
  12190. return NULL;
  12191. }
  12192. try
  12193. {
  12194. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12195. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12196. ReleaseRoxieRowSet(group);
  12197. if (outSize)
  12198. {
  12199. processed++;
  12200. return rowBuilder.finalizeRowClear(outSize);
  12201. }
  12202. }
  12203. catch (IException * E)
  12204. {
  12205. ReleaseRoxieRowSet(group);
  12206. throw makeWrappedException(E);
  12207. }
  12208. }
  12209. }
  12210. };
  12211. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12212. {
  12213. public:
  12214. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12215. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12216. {
  12217. }
  12218. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12219. {
  12220. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  12221. }
  12222. };
  12223. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12224. {
  12225. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12226. }
  12227. //=================================================================================
  12228. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12229. {
  12230. IHThorFilterProjectArg &helper;
  12231. unsigned numProcessedLastGroup;
  12232. unsigned __int64 recordCount;
  12233. public:
  12234. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12235. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12236. {
  12237. numProcessedLastGroup = 0;
  12238. recordCount = 0;
  12239. }
  12240. ~CRoxieServerFilterProjectActivity()
  12241. {
  12242. }
  12243. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12244. {
  12245. numProcessedLastGroup = 0;
  12246. recordCount = 0;
  12247. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12248. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12249. }
  12250. virtual bool needsAllocator() const { return true; }
  12251. virtual const void * nextInGroup()
  12252. {
  12253. ActivityTimer t(totalCycles, timeActivities);
  12254. if (eof)
  12255. return NULL;
  12256. loop
  12257. {
  12258. const void * in = input->nextInGroup();
  12259. if (!in)
  12260. {
  12261. recordCount = 0;
  12262. if (numProcessedLastGroup == processed)
  12263. in = input->nextInGroup();
  12264. if (!in)
  12265. {
  12266. numProcessedLastGroup = processed;
  12267. return NULL;
  12268. }
  12269. }
  12270. try
  12271. {
  12272. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12273. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12274. ReleaseRoxieRow(in);
  12275. if (outSize)
  12276. {
  12277. processed++;
  12278. return rowBuilder.finalizeRowClear(outSize);
  12279. }
  12280. }
  12281. catch (IException *E)
  12282. {
  12283. throw makeWrappedException(E);
  12284. }
  12285. }
  12286. }
  12287. };
  12288. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12289. {
  12290. public:
  12291. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12292. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12293. {
  12294. }
  12295. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12296. {
  12297. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  12298. }
  12299. };
  12300. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12301. {
  12302. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12303. }
  12304. //=================================================================================
  12305. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12306. {
  12307. unsigned numProcessedLastGroup;
  12308. bool count;
  12309. unsigned __int64 recordCount;
  12310. public:
  12311. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12312. : CRoxieServerActivity(_factory, _probeManager),
  12313. count(_count)
  12314. {
  12315. numProcessedLastGroup = 0;
  12316. recordCount = 0;
  12317. }
  12318. ~CRoxieServerProjectActivity()
  12319. {
  12320. }
  12321. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12322. {
  12323. numProcessedLastGroup = 0;
  12324. recordCount = 0;
  12325. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12326. }
  12327. virtual bool needsAllocator() const { return true; }
  12328. virtual const void * nextInGroup()
  12329. {
  12330. ActivityTimer t(totalCycles, timeActivities);
  12331. loop
  12332. {
  12333. OwnedConstRoxieRow in = input->nextInGroup();
  12334. if (!in)
  12335. {
  12336. recordCount = 0;
  12337. if (numProcessedLastGroup == processed)
  12338. in.setown(input->nextInGroup());
  12339. if (!in)
  12340. {
  12341. numProcessedLastGroup = processed;
  12342. return NULL;
  12343. }
  12344. }
  12345. try
  12346. {
  12347. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12348. size32_t outSize;
  12349. if (count)
  12350. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12351. else
  12352. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12353. if (outSize)
  12354. {
  12355. processed++;
  12356. return rowBuilder.finalizeRowClear(outSize);
  12357. }
  12358. }
  12359. catch (IException *E)
  12360. {
  12361. throw makeWrappedException(E);
  12362. }
  12363. }
  12364. }
  12365. };
  12366. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12367. {
  12368. protected:
  12369. bool count;
  12370. public:
  12371. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12372. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12373. {
  12374. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12375. }
  12376. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12377. {
  12378. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12379. }
  12380. };
  12381. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12382. {
  12383. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12384. }
  12385. //=================================================================================
  12386. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12387. {
  12388. unsigned numProcessedLastGroup;
  12389. bool count;
  12390. bool eof;
  12391. bool allPulled;
  12392. bool isThreaded;
  12393. unsigned preload;
  12394. unsigned __int64 recordCount;
  12395. IHThorPrefetchProjectArg &helper;
  12396. RecordPullerThread puller;
  12397. InterruptableSemaphore ready;
  12398. InterruptableSemaphore space;
  12399. class PrefetchInfo : public CInterface
  12400. {
  12401. public:
  12402. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12403. {
  12404. if (helper.preTransform(extract, _in, _recordCount))
  12405. {
  12406. in.setown(_in);
  12407. recordCount = _recordCount;
  12408. }
  12409. else
  12410. ReleaseRoxieRow(_in);
  12411. }
  12412. OwnedConstRoxieRow in;
  12413. unsigned __int64 recordCount;
  12414. rtlRowBuilder extract;
  12415. };
  12416. QueueOf<PrefetchInfo, true> pulled;
  12417. CriticalSection pulledCrit;
  12418. public:
  12419. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12420. : CRoxieServerActivity(_factory, _probeManager),
  12421. helper((IHThorPrefetchProjectArg &) basehelper),
  12422. puller(false),
  12423. count(_count)
  12424. {
  12425. numProcessedLastGroup = 0;
  12426. recordCount = 0;
  12427. eof = false;
  12428. allPulled = false;
  12429. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12430. preload = 0;
  12431. }
  12432. ~CRoxieServerPrefetchProjectActivity()
  12433. {
  12434. while (pulled.ordinality())
  12435. ::Release(pulled.dequeue());
  12436. }
  12437. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12438. {
  12439. if (idx)
  12440. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12441. puller.setInput(this, _in);
  12442. }
  12443. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12444. {
  12445. numProcessedLastGroup = 0;
  12446. recordCount = 0;
  12447. eof = false;
  12448. allPulled = false;
  12449. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12450. preload = helper.getLookahead();
  12451. if (!preload)
  12452. preload = ctx->queryOptions().prefetchProjectPreload;
  12453. space.reinit(preload);
  12454. ready.reinit();
  12455. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12456. }
  12457. virtual void stop(bool aborting)
  12458. {
  12459. space.interrupt();
  12460. ready.interrupt();
  12461. CRoxieServerActivity::stop(aborting);
  12462. puller.stop(aborting);
  12463. }
  12464. virtual void reset()
  12465. {
  12466. CRoxieServerActivity::reset();
  12467. puller.reset();
  12468. allPulled = false;
  12469. while (pulled.ordinality())
  12470. ::Release(pulled.dequeue());
  12471. }
  12472. virtual PrefetchInfo *readNextRecord()
  12473. {
  12474. if (!isThreaded)
  12475. {
  12476. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12477. puller.pullRecords(1);
  12478. }
  12479. else
  12480. ready.wait();
  12481. CriticalBlock b(pulledCrit);
  12482. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12483. space.signal();
  12484. return ret;
  12485. }
  12486. virtual bool needsAllocator() const { return true; }
  12487. virtual const void * nextInGroup()
  12488. {
  12489. ActivityTimer t(totalCycles, timeActivities);
  12490. if (eof)
  12491. return NULL;
  12492. loop
  12493. {
  12494. Owned<PrefetchInfo> in = readNextRecord();
  12495. if (!in)
  12496. {
  12497. recordCount = 0;
  12498. if (numProcessedLastGroup == processed)
  12499. in.setown(readNextRecord());
  12500. if (!in)
  12501. {
  12502. numProcessedLastGroup = processed;
  12503. eof = true;
  12504. return NULL;
  12505. }
  12506. }
  12507. try
  12508. {
  12509. if (in->in)
  12510. {
  12511. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12512. size32_t outSize;
  12513. IThorChildGraph *child = helper.queryChild();
  12514. Owned<IEclGraphResults> results;
  12515. if (child)
  12516. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12517. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12518. if (outSize)
  12519. {
  12520. processed++;
  12521. return rowBuilder.finalizeRowClear(outSize);
  12522. }
  12523. }
  12524. }
  12525. catch (IException *E)
  12526. {
  12527. throw makeWrappedException(E);
  12528. }
  12529. }
  12530. }
  12531. // interface IExceptionHandler
  12532. virtual bool fireException(IException *e)
  12533. {
  12534. // called from puller thread on failure
  12535. ready.interrupt(LINK(e));
  12536. space.interrupt(e);
  12537. return true;
  12538. }
  12539. // interface IRecordPullerCallback
  12540. virtual void processRow(const void *row)
  12541. {
  12542. {
  12543. CriticalBlock b(pulledCrit);
  12544. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12545. }
  12546. if (isThreaded)
  12547. {
  12548. ready.signal();
  12549. space.wait();
  12550. }
  12551. }
  12552. virtual void processEOG()
  12553. {
  12554. {
  12555. CriticalBlock b(pulledCrit);
  12556. pulled.enqueue(NULL);
  12557. }
  12558. if (isThreaded)
  12559. {
  12560. ready.signal();
  12561. space.wait();
  12562. }
  12563. }
  12564. virtual void processGroup(const ConstPointerArray &rows)
  12565. {
  12566. throwUnexpected();
  12567. }
  12568. virtual void processDone()
  12569. {
  12570. CriticalBlock b(pulledCrit);
  12571. allPulled = true;
  12572. if (isThreaded)
  12573. ready.signal();
  12574. }
  12575. };
  12576. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12577. {
  12578. public:
  12579. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12580. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12581. {
  12582. }
  12583. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12584. {
  12585. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12586. }
  12587. };
  12588. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12589. {
  12590. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12591. }
  12592. //=================================================================================
  12593. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12594. {
  12595. public:
  12596. CPointerArrayRoxieInput()
  12597. {
  12598. rowset = NULL;
  12599. rowcount = 0;
  12600. curRow = 0;
  12601. }
  12602. void init(size32_t _rowcount, byte **_rowset)
  12603. {
  12604. rowset = _rowset;
  12605. rowcount = _rowcount;
  12606. curRow = 0;
  12607. }
  12608. virtual const void * nextInGroup()
  12609. {
  12610. if (curRow < rowcount)
  12611. {
  12612. const void * ret = rowset[curRow];
  12613. if (ret)
  12614. LinkRoxieRow(ret);
  12615. curRow++;
  12616. return ret;
  12617. }
  12618. return NULL;
  12619. }
  12620. protected:
  12621. byte **rowset;
  12622. size32_t rowcount;
  12623. size32_t curRow;
  12624. };
  12625. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12626. {
  12627. protected:
  12628. IHThorLoopArg &helper;
  12629. ThorActivityKind activityKind;
  12630. unsigned maxIterations;
  12631. bool finishedLooping;
  12632. unsigned flags;
  12633. bool eof;
  12634. rtlRowBuilder loopExtractBuilder;
  12635. unsigned loopGraphId;
  12636. Linked<IOutputMetaData> counterMeta;
  12637. public:
  12638. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12639. : CRoxieServerActivity(_factory, _probeManager),
  12640. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12641. {
  12642. eof = false;
  12643. finishedLooping = false;
  12644. activityKind = factory->getKind();
  12645. flags = helper.getFlags();
  12646. maxIterations = 0;
  12647. }
  12648. virtual bool needsAllocator() const { return true; }
  12649. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12650. {
  12651. eof = false;
  12652. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12653. int iterations = (int) helper.numIterations();
  12654. maxIterations = (iterations >= 0) ? iterations : 0;
  12655. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12656. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12657. finishedLooping = true;
  12658. loopExtractBuilder.clear();
  12659. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12660. }
  12661. virtual void stop(bool aborting)
  12662. {
  12663. CRoxieServerActivity::stop(aborting);
  12664. loopExtractBuilder.clear();
  12665. }
  12666. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12667. {
  12668. if (flags & IHThorLoopArg::LFcounter)
  12669. {
  12670. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12671. *((thor_loop_counter_t *)counterRow) = counter;
  12672. RtlLinkedDatasetBuilder builder(rowAllocator);
  12673. builder.appendOwn(counterRow);
  12674. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12675. graph->setInputResult(2, counterResult);
  12676. }
  12677. }
  12678. };
  12679. //=================================================================================
  12680. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12681. {
  12682. Owned<IActivityGraph> loopQuery;
  12683. Owned<IRoxieServerChildGraph> loopGraph;
  12684. IRoxieInput * curInput;
  12685. RtlLinkedDatasetBuilder *loopInputBuilder;
  12686. CPointerArrayRoxieInput arrayInput;
  12687. Linked<IRoxieInput> resultInput;
  12688. unsigned loopCounter;
  12689. public:
  12690. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12691. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12692. {
  12693. curInput = NULL;
  12694. loopCounter = 0;
  12695. loopInputBuilder = NULL;
  12696. }
  12697. virtual bool needsAllocator() const { return true; }
  12698. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12699. {
  12700. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12701. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12702. }
  12703. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12704. {
  12705. curInput = input;
  12706. loopCounter = 1;
  12707. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12708. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12709. loopGraph.set(loopQuery->queryLoopGraph());
  12710. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12711. }
  12712. virtual void stop(bool aborting)
  12713. {
  12714. delete loopInputBuilder;
  12715. loopInputBuilder = NULL;
  12716. CRoxieServerLoopActivity::stop(aborting);
  12717. }
  12718. virtual const void * nextInGroup()
  12719. {
  12720. ActivityTimer t(totalCycles, timeActivities);
  12721. if (eof)
  12722. return NULL;
  12723. unsigned emptyIterations = 0;
  12724. loop
  12725. {
  12726. loop
  12727. {
  12728. const void * ret = curInput->nextInGroup();
  12729. if (!ret)
  12730. {
  12731. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12732. if (!ret)
  12733. {
  12734. if (finishedLooping)
  12735. {
  12736. eof = true;
  12737. return NULL;
  12738. }
  12739. break;
  12740. }
  12741. }
  12742. if (finishedLooping ||
  12743. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12744. {
  12745. processed++;
  12746. return ret;
  12747. }
  12748. loopInputBuilder->appendOwn(ret);
  12749. }
  12750. switch (activityKind)
  12751. {
  12752. case TAKloopdataset:
  12753. {
  12754. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12755. {
  12756. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12757. {
  12758. if (loopInputBuilder->getcount() == 0)
  12759. {
  12760. eof = true;
  12761. return NULL;
  12762. }
  12763. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12764. // MORE - should builder be cleared here?
  12765. curInput = &arrayInput;
  12766. finishedLooping = true;
  12767. continue; // back to the input loop again
  12768. }
  12769. }
  12770. break;
  12771. }
  12772. case TAKlooprow:
  12773. if (!loopInputBuilder->getcount())
  12774. {
  12775. finishedLooping = true;
  12776. eof = true;
  12777. return NULL;
  12778. }
  12779. break;
  12780. }
  12781. if (loopInputBuilder->getcount())
  12782. emptyIterations = 0;
  12783. else
  12784. {
  12785. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12786. emptyIterations++;
  12787. if (emptyIterations > maxEmptyLoopIterations)
  12788. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12789. if (emptyIterations % 32 == 0)
  12790. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12791. }
  12792. checkAbort();
  12793. try
  12794. {
  12795. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12796. resultInput.setown(results->createIterator(0));
  12797. if (flags & IHThorLoopArg::LFnewloopagain)
  12798. {
  12799. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12800. OwnedConstRoxieRow row = againResult->nextInGroup();
  12801. assertex(row);
  12802. //Result is a row which contains a single boolean field.
  12803. if (!((const bool *)row.get())[0])
  12804. finishedLooping = true;
  12805. }
  12806. }
  12807. catch (IException *E)
  12808. {
  12809. throw makeWrappedException(E);
  12810. }
  12811. curInput = resultInput.get();
  12812. loopCounter++;
  12813. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12814. finishedLooping = true;
  12815. }
  12816. }
  12817. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12818. {
  12819. try
  12820. {
  12821. loopGraph->beforeExecute();
  12822. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12823. loopInputBuilder->clear();
  12824. loopGraph->setInputResult(1, inputRowsResult);
  12825. createCounterResult(loopGraph, counter);
  12826. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12827. loopGraph->afterExecute();
  12828. return ret.getClear();
  12829. }
  12830. catch (...)
  12831. {
  12832. CTXLOG("Exception thrown in loop body - cleaning up");
  12833. loopGraph->afterExecute();
  12834. throw;
  12835. }
  12836. }
  12837. };
  12838. //=================================================================================
  12839. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12840. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12841. {
  12842. public:
  12843. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12844. input(_input)
  12845. {
  12846. eof = false;
  12847. }
  12848. virtual const void * nextInGroup()
  12849. {
  12850. if (eof)
  12851. return NULL;
  12852. const void * ret = input.dequeue();
  12853. if (!ret)
  12854. eof = true;
  12855. return ret;
  12856. }
  12857. protected:
  12858. SafeRowQueue & input;
  12859. bool eof;
  12860. };
  12861. class CRoxieServerParallelLoopActivity;
  12862. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12863. {
  12864. public:
  12865. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12866. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12867. {
  12868. }
  12869. virtual const void * nextInGroup();
  12870. protected:
  12871. CRoxieServerParallelLoopActivity * activity;
  12872. unsigned counter;
  12873. };
  12874. class LoopExecutorThread : public RestartableThread
  12875. {
  12876. protected:
  12877. Owned<IRoxieInput> safeInput;
  12878. CRoxieServerParallelLoopActivity * activity;
  12879. bool eof;
  12880. CriticalSection crit;
  12881. unsigned flags;
  12882. SafeRowQueue tempResults[2];
  12883. unsigned savedParentExtractSize;
  12884. const byte * savedParentExtract;
  12885. IArrayOf<IActivityGraph> cachedGraphs;
  12886. IRoxieSlaveContext *ctx;
  12887. public:
  12888. LoopExecutorThread()
  12889. : RestartableThread("LoopExecutorThread")
  12890. {
  12891. activity = NULL;
  12892. eof = false;
  12893. flags = 0;
  12894. ctx = NULL;
  12895. savedParentExtract = NULL;
  12896. savedParentExtractSize = 0;
  12897. }
  12898. virtual IRoxieInput *queryInput(unsigned idx) const
  12899. {
  12900. return safeInput->queryInput(idx);
  12901. }
  12902. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12903. {
  12904. activity = _activity;
  12905. flags = _flags;
  12906. // 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.
  12907. safeInput.setown(new CSafeRoxieInput(_input));
  12908. }
  12909. IRoxieInput *queryInput() const
  12910. {
  12911. return safeInput;
  12912. }
  12913. void onCreate(IRoxieSlaveContext * _ctx);
  12914. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12915. void stop(bool aborting);
  12916. void reset();
  12917. virtual int run();
  12918. protected:
  12919. void executeLoop();
  12920. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12921. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12922. };
  12923. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12924. {
  12925. friend class LoopFilterPseudoInput;
  12926. friend class LoopExecutorThread;
  12927. QueueOf<const void, true> ready;
  12928. CriticalSection helperCS;
  12929. CriticalSection cs;
  12930. size32_t sizeNumParallel;
  12931. rtlDataAttr listNumParallel;
  12932. unsigned defaultNumParallel;
  12933. LoopExecutorThread executor;
  12934. IProbeManager* probeManager;
  12935. CriticalSection canAccess;
  12936. CriticalSection scrit;
  12937. InterruptableSemaphore readySpace;
  12938. InterruptableSemaphore recordsReady;
  12939. protected:
  12940. bool includeInLoop(unsigned counter, const void * row)
  12941. {
  12942. CriticalBlock b(helperCS);
  12943. return helper.sendToLoop(counter, row);
  12944. }
  12945. public:
  12946. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12947. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12948. readySpace(parallelLoopFlowLimit)
  12949. {
  12950. probeManager = _probeManager;
  12951. defaultNumParallel = 0;
  12952. sizeNumParallel = 0;
  12953. }
  12954. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12955. {
  12956. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12957. executor.onCreate(_ctx);
  12958. }
  12959. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12960. {
  12961. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12962. readySpace.reinit(parallelLoopFlowLimit);
  12963. recordsReady.reinit();
  12964. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12965. defaultNumParallel = helper.defaultParallelIterations();
  12966. if (!defaultNumParallel)
  12967. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12968. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12969. //MORE: If numIterations <= number of parallel iterations[1],
  12970. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12971. //being transferred via a queue
  12972. executor.start(parentExtractSize, parentExtract, paused);
  12973. }
  12974. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12975. {
  12976. if (idx)
  12977. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12978. executor.setInput(this, _in, flags);
  12979. }
  12980. virtual void stop(bool aborting)
  12981. {
  12982. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12983. readySpace.interrupt();
  12984. recordsReady.interrupt();
  12985. executor.join(); // MORE - may not be needed given stop/reset split
  12986. CRoxieServerLoopActivity::stop(aborting);
  12987. }
  12988. virtual void reset()
  12989. {
  12990. while (ready.ordinality())
  12991. ReleaseRoxieRow(ready.dequeue());
  12992. executor.reset();
  12993. CRoxieServerActivity::reset();
  12994. }
  12995. virtual const void * nextInGroup()
  12996. {
  12997. ActivityTimer t(totalCycles, timeActivities);
  12998. loop
  12999. {
  13000. if (eof)
  13001. return NULL;
  13002. recordsReady.wait();
  13003. CriticalBlock procedure(canAccess);
  13004. if (ready.ordinality())
  13005. {
  13006. const void *result = ready.dequeue();
  13007. readySpace.signal();
  13008. if (result)
  13009. processed++;
  13010. return result;
  13011. }
  13012. else
  13013. eof = true;
  13014. }
  13015. }
  13016. unsigned getNumParallel(unsigned iter)
  13017. {
  13018. if (iter * sizeof(unsigned) >= sizeNumParallel)
  13019. return defaultNumParallel;
  13020. return ((unsigned *)listNumParallel.getdata())[iter];
  13021. }
  13022. inline void enqueueResult(const void * row)
  13023. {
  13024. try
  13025. {
  13026. while(!readySpace.wait(1000))
  13027. {
  13028. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13029. }
  13030. }
  13031. catch (...)
  13032. {
  13033. ReleaseRoxieRow(row);
  13034. throw;
  13035. }
  13036. CriticalBlock b2(canAccess);
  13037. ready.enqueue(row);
  13038. recordsReady.signal();
  13039. }
  13040. inline void finishResults()
  13041. {
  13042. recordsReady.signal();
  13043. }
  13044. virtual bool fireException(IException *e)
  13045. {
  13046. readySpace.interrupt(LINK(e));
  13047. recordsReady.interrupt(e);
  13048. return true;
  13049. }
  13050. IActivityGraph * createChildGraphInstance()
  13051. {
  13052. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13053. }
  13054. IActivityGraph * queryChildGraph()
  13055. {
  13056. return ctx->queryChildGraph(loopGraphId);
  13057. }
  13058. };
  13059. //=================================================================================
  13060. const void * LoopFilterPseudoInput::nextInGroup()
  13061. {
  13062. loop
  13063. {
  13064. const void * next = input->nextInGroup();
  13065. if (!next || activity->includeInLoop(counter, next))
  13066. return next;
  13067. activity->enqueueResult(next);
  13068. }
  13069. }
  13070. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13071. {
  13072. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13073. ctx = _ctx;
  13074. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13075. }
  13076. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13077. {
  13078. savedParentExtractSize = parentExtractSize;
  13079. savedParentExtract = parentExtract;
  13080. eof = false;
  13081. StringBuffer logPrefix("[");
  13082. ctx->getLogPrefix(logPrefix).append("] ");
  13083. RestartableThread::start(logPrefix);
  13084. }
  13085. int LoopExecutorThread::run()
  13086. {
  13087. try
  13088. {
  13089. executeLoop();
  13090. }
  13091. catch (IException *e)
  13092. {
  13093. activity->fireException(e);
  13094. }
  13095. catch (...)
  13096. {
  13097. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13098. }
  13099. return 0;
  13100. }
  13101. void LoopExecutorThread::stop(bool aborting)
  13102. {
  13103. safeInput->stop(aborting);
  13104. RestartableThread::join();
  13105. }
  13106. void LoopExecutorThread::reset()
  13107. {
  13108. safeInput->reset();
  13109. }
  13110. void LoopExecutorThread::executeLoop()
  13111. {
  13112. unsigned iterations = 0;
  13113. unsigned counter = 0;
  13114. unsigned outputIndex = 0;
  13115. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13116. loop
  13117. {
  13118. if (activity->activityKind == TAKloopcount)
  13119. {
  13120. if (counter == activity->maxIterations)
  13121. break;
  13122. }
  13123. else
  13124. {
  13125. //This condition isn't quite right because it needs to be whether the filtered
  13126. //input is empty. May be ok if we include that in the semantics,
  13127. if (tempResults[1-outputIndex].ordinality() == 0)
  13128. break;
  13129. }
  13130. unsigned numParallel = activity->getNumParallel(iterations);
  13131. Linked<IRoxieInput> curInput;
  13132. if (iterations == 0)
  13133. curInput.set(safeInput);
  13134. else
  13135. {
  13136. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13137. inputQueue.enqueue(NULL);
  13138. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  13139. }
  13140. SafeRowQueue * curOutput = NULL;
  13141. if (counter+numParallel > activity->maxIterations)
  13142. numParallel = activity->maxIterations - counter;
  13143. else if (counter+numParallel < activity->maxIterations)
  13144. curOutput = &tempResults[outputIndex];
  13145. executeLoopInstance(counter, numParallel, curInput, curOutput);
  13146. outputIndex = 1-outputIndex;
  13147. counter += numParallel;
  13148. iterations++;
  13149. }
  13150. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13151. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13152. while (inputQueue.ordinality())
  13153. {
  13154. const void * next = inputQueue.dequeue();
  13155. activity->enqueueResult(next);
  13156. }
  13157. activity->finishResults();
  13158. }
  13159. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  13160. {
  13161. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13162. Linked<IRoxieInput> curInput = input;
  13163. unsigned i;
  13164. for (i= 0; i != numIterations; i++)
  13165. {
  13166. unsigned thisCounter = counter+i+1;
  13167. IRoxieInput * filtered = curInput;
  13168. if (flags & IHThorLoopArg::LFfiltered)
  13169. {
  13170. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  13171. savedInputs.append(*filtered);
  13172. }
  13173. //graph is kept, so new curInput will be guaranteed to exist
  13174. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  13175. }
  13176. try
  13177. {
  13178. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13179. if (spillOutput)
  13180. {
  13181. loop
  13182. {
  13183. const void * next = curInput->nextInGroup();
  13184. if (!next)
  13185. break;
  13186. spillOutput->enqueue(next);
  13187. }
  13188. }
  13189. else
  13190. {
  13191. loop
  13192. {
  13193. const void * next = curInput->nextInGroup();
  13194. if (!next)
  13195. break;
  13196. activity->enqueueResult(next);
  13197. }
  13198. }
  13199. }
  13200. catch (IException *E)
  13201. {
  13202. ctx->notifyAbort(E);
  13203. for (i= 0; i != numIterations; i++)
  13204. {
  13205. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13206. }
  13207. curInput->stop(true);
  13208. curInput->reset();
  13209. throw;
  13210. }
  13211. for (i= 0; i != numIterations; i++)
  13212. {
  13213. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13214. }
  13215. curInput->stop(false);
  13216. curInput->reset();
  13217. }
  13218. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  13219. {
  13220. if (!cachedGraphs.isItem(i))
  13221. cachedGraphs.append(*activity->createChildGraphInstance());
  13222. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13223. loopGraph->beforeExecute();
  13224. if (!loopGraph->querySetInputResult(1, input))
  13225. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13226. activity->createCounterResult(loopGraph, counter);
  13227. return loopGraph->selectOutput(0);
  13228. }
  13229. //=================================================================================
  13230. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  13231. {
  13232. public:
  13233. IMPLEMENT_IINTERFACE
  13234. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13235. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13236. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13237. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13238. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13239. virtual unsigned getMetaFlags() { return 0; }
  13240. virtual void destruct(byte * self) {}
  13241. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13242. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13243. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13244. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13245. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13246. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13247. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13248. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13249. };
  13250. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13251. {
  13252. unsigned loopGraphId;
  13253. unsigned flags;
  13254. Linked<IOutputMetaData> counterMeta;
  13255. public:
  13256. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13257. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13258. {
  13259. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13260. flags = helper->getFlags();
  13261. counterMeta.setown(new CCounterRowMetaData);
  13262. }
  13263. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13264. {
  13265. if (flags & IHThorLoopArg::LFparallel)
  13266. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13267. else
  13268. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13269. }
  13270. };
  13271. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13272. {
  13273. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13274. }
  13275. //=================================================================================
  13276. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13277. {
  13278. protected:
  13279. IHThorGraphLoopArg &helper;
  13280. unsigned maxIterations;
  13281. unsigned flags;
  13282. rtlRowBuilder GraphExtractBuilder;
  13283. unsigned loopGraphId;
  13284. Linked<IOutputMetaData> counterMeta;
  13285. public:
  13286. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13287. : CRoxieServerActivity(_factory, _probeManager),
  13288. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13289. {
  13290. flags = helper.getFlags();
  13291. maxIterations = 0;
  13292. }
  13293. virtual bool needsAllocator() const { return true; }
  13294. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13295. {
  13296. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13297. int iterations = (int) helper.numIterations();
  13298. maxIterations = (iterations >= 0) ? iterations : 0;
  13299. if (maxIterations > maxGraphLoopIterations)
  13300. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13301. if (maxIterations != 0)
  13302. {
  13303. GraphExtractBuilder.clear();
  13304. helper.createParentExtract(GraphExtractBuilder);
  13305. }
  13306. }
  13307. virtual void stop(bool aborting)
  13308. {
  13309. CRoxieServerActivity::stop(aborting);
  13310. GraphExtractBuilder.clear();
  13311. }
  13312. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13313. {
  13314. if (flags & IHThorGraphLoopArg::GLFcounter)
  13315. {
  13316. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13317. *((thor_loop_counter_t *)counterRow) = counter;
  13318. RtlLinkedDatasetBuilder builder(rowAllocator);
  13319. builder.appendOwn(counterRow);
  13320. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13321. graph->setInputResult(0, counterResult);
  13322. }
  13323. }
  13324. };
  13325. //=================================================================================
  13326. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13327. {
  13328. Owned<IActivityGraph> GraphQuery;
  13329. Owned<IRoxieServerChildGraph> loopGraph;
  13330. Linked<IRoxieInput> resultInput;
  13331. bool evaluated;
  13332. public:
  13333. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13334. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13335. {
  13336. evaluated = false;
  13337. }
  13338. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13339. {
  13340. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13341. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13342. }
  13343. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13344. {
  13345. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13346. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13347. loopGraph.set(GraphQuery->queryLoopGraph());
  13348. evaluated = false;
  13349. }
  13350. virtual void stop(bool aborting)
  13351. {
  13352. if (loopGraph)
  13353. loopGraph->clearGraphLoopResults();
  13354. CRoxieServerGraphLoopActivity::stop(aborting);
  13355. }
  13356. virtual const void * nextInGroup()
  13357. {
  13358. ActivityTimer t(totalCycles, timeActivities);
  13359. if (!evaluated)
  13360. {
  13361. executeEntireGraph();
  13362. evaluated = true;
  13363. }
  13364. const void * ret = resultInput->nextInGroup();
  13365. if (ret)
  13366. processed++;
  13367. return ret;
  13368. }
  13369. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13370. {
  13371. try
  13372. {
  13373. loopGraph->beforeExecute();
  13374. createCounterResult(loopGraph, counter);
  13375. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13376. loopGraph->afterExecute();
  13377. }
  13378. catch (...)
  13379. {
  13380. CTXLOG("Exception thrown in graph body - cleaning up");
  13381. loopGraph->afterExecute();
  13382. throw;
  13383. }
  13384. }
  13385. void createInitialGraphInput()
  13386. {
  13387. loopGraph->clearGraphLoopResults();
  13388. RtlLinkedDatasetBuilder builder(rowAllocator);
  13389. input->readAll(builder);
  13390. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13391. loopGraph->setGraphLoopResult(0, result);
  13392. }
  13393. void executeEntireGraph()
  13394. {
  13395. createInitialGraphInput();
  13396. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13397. {
  13398. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13399. }
  13400. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13401. }
  13402. };
  13403. //=================================================================================
  13404. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13405. {
  13406. public:
  13407. virtual unsigned numBranches()
  13408. {
  13409. return 0;
  13410. }
  13411. virtual IOutputMetaData * queryOutputMeta()
  13412. {
  13413. return NULL;// get it from the parent..
  13414. }
  13415. };
  13416. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13417. class CGraphIterationInfo : public CInterface
  13418. {
  13419. private:
  13420. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13421. unsigned sourceIdx;
  13422. Linked<IRoxieServerActivity> sourceAct;
  13423. Linked<IRoxieInput> sourceInput;
  13424. unsigned numUses;
  13425. unsigned iteration;
  13426. public:
  13427. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13428. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13429. {
  13430. numUses = 0;
  13431. }
  13432. inline void noteUsed()
  13433. {
  13434. numUses++;
  13435. }
  13436. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13437. {
  13438. if (numUses > 1)
  13439. {
  13440. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13441. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13442. splitter->onCreate(ctx, NULL);
  13443. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13444. if (probeManager)
  13445. {
  13446. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13447. input = static_cast<IRoxieInput*>(inputBase);
  13448. // MORE - shouldn't this be added to probes?
  13449. }
  13450. sourceAct.setown(splitter);
  13451. sourceAct->setInput(0, input);
  13452. sourceIdx = 0;
  13453. sourceInput.clear();
  13454. }
  13455. }
  13456. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13457. {
  13458. // MORE - not really necessary to create splitters in separate pass, is it?
  13459. if (factory) // we created a splitter....
  13460. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13461. IRoxieInput *ret = sourceInput;
  13462. if (probeManager)
  13463. {
  13464. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13465. ret = static_cast<IRoxieInput *>(inputBase);
  13466. probes.append(*LINK(ret));
  13467. }
  13468. if (factory) // we created a splitter....
  13469. sourceIdx++;
  13470. return ret;
  13471. }
  13472. };
  13473. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13474. {
  13475. Owned<IActivityGraph> childGraph;
  13476. IRoxieInput * resultInput;
  13477. CIArrayOf<CGraphIterationInfo> outputs;
  13478. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13479. Owned<CExtractMapperInput> inputExtractMapper;
  13480. IProbeManager *probeManager;
  13481. unsigned createLoopCounter;
  13482. IArrayOf<IRoxieInput> probes;
  13483. public:
  13484. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13485. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13486. {
  13487. inputExtractMapper.setown(new CExtractMapperInput);
  13488. resultInput = NULL;
  13489. createLoopCounter = 0;
  13490. }
  13491. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13492. {
  13493. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13494. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13495. }
  13496. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13497. {
  13498. //Input needs to be handled very carefully.....
  13499. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13500. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13501. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13502. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13503. assertex(idx == 0);
  13504. inputExtractMapper->setInput(_in);
  13505. }
  13506. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13507. {
  13508. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13509. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13510. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13511. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13512. }
  13513. virtual void stop(bool aborting)
  13514. {
  13515. if (resultInput)
  13516. resultInput->stop(aborting);
  13517. CRoxieServerGraphLoopActivity::stop(aborting);
  13518. }
  13519. virtual void reset()
  13520. {
  13521. if (resultInput)
  13522. resultInput->reset();
  13523. resultInput = NULL;
  13524. outputs.kill();
  13525. iterationGraphs.kill(); // must be done after all activities killed
  13526. if (probeManager)
  13527. {
  13528. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13529. probes.kill();
  13530. }
  13531. CRoxieServerGraphLoopActivity::reset();
  13532. }
  13533. virtual const void * nextInGroup()
  13534. {
  13535. ActivityTimer t(totalCycles, timeActivities);
  13536. const void * ret = resultInput->nextInGroup();
  13537. if (ret)
  13538. processed++;
  13539. return ret;
  13540. }
  13541. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13542. {
  13543. //result(0) is the input to the graph.
  13544. resultInput = inputExtractMapper;
  13545. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13546. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13547. {
  13548. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13549. graph->beforeExecute();
  13550. iterationGraphs.append(*graph);
  13551. graph->gatherIterationUsage(*this);
  13552. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13553. outputs.append(*iteration);
  13554. }
  13555. createLoopCounter = 0;
  13556. createSplitters(probeManager);
  13557. ForEachItemIn(i2, iterationGraphs)
  13558. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13559. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13560. }
  13561. void createSplitters(IProbeManager *probeManager)
  13562. {
  13563. ForEachItemIn(i, outputs)
  13564. {
  13565. CGraphIterationInfo & next = outputs.item(i);
  13566. next.createSplitter(ctx, probeManager);
  13567. }
  13568. }
  13569. //IRoxieServerLoopResultProcessor
  13570. virtual void noteUseIteration(unsigned _whichIteration)
  13571. {
  13572. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13573. if (whichIteration >= 0)
  13574. {
  13575. if (!outputs.isItem(whichIteration))
  13576. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13577. outputs.item(whichIteration).noteUsed();
  13578. }
  13579. }
  13580. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13581. {
  13582. if (outputs.isItem(whichIteration))
  13583. {
  13584. CGraphIterationInfo & next = outputs.item(whichIteration);
  13585. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13586. }
  13587. return NULL;
  13588. }
  13589. };
  13590. //=================================================================================
  13591. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13592. {
  13593. unsigned loopGraphId;
  13594. unsigned flags;
  13595. Linked<IOutputMetaData> counterMeta;
  13596. public:
  13597. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13598. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13599. {
  13600. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13601. flags = helper->getFlags();
  13602. counterMeta.setown(new CCounterRowMetaData);
  13603. }
  13604. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13605. {
  13606. if (kind == TAKparallelgraphloop)
  13607. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13608. else
  13609. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13610. }
  13611. };
  13612. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13613. {
  13614. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13615. }
  13616. //=====================================================================================================
  13617. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13618. {
  13619. class OutputAdaptor : public CExtractMapperInput
  13620. {
  13621. bool stopped;
  13622. public:
  13623. CRoxieServerLibraryCallActivity *parent;
  13624. unsigned oid;
  13625. unsigned processed;
  13626. public:
  13627. IMPLEMENT_IINTERFACE;
  13628. OutputAdaptor() : CExtractMapperInput(NULL)
  13629. {
  13630. parent = NULL;
  13631. oid = 0;
  13632. init();
  13633. }
  13634. ~OutputAdaptor()
  13635. {
  13636. if (traceStartStop)
  13637. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  13638. if (processed && parent && parent->factory)
  13639. {
  13640. parent->factory->noteProcessed(oid, processed);
  13641. if (parent->ctx)
  13642. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  13643. }
  13644. }
  13645. void init()
  13646. {
  13647. processed = 0;
  13648. stopped = false;
  13649. }
  13650. virtual unsigned queryId() const
  13651. {
  13652. return parent->queryId();
  13653. }
  13654. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13655. {
  13656. parent->start(oid, parentExtractSize, parentExtract, paused);
  13657. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13658. }
  13659. virtual void stop(bool aborting)
  13660. {
  13661. if (!stopped)
  13662. {
  13663. stopped = true;
  13664. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13665. CExtractMapperInput::stop(aborting);
  13666. }
  13667. };
  13668. virtual void reset()
  13669. {
  13670. parent->reset(oid);
  13671. CExtractMapperInput::reset();
  13672. init();
  13673. };
  13674. virtual void checkAbort()
  13675. {
  13676. parent->checkAbort();
  13677. }
  13678. };
  13679. IHThorLibraryCallArg &helper;
  13680. unsigned numInputs;
  13681. unsigned numOutputs;
  13682. unsigned numActiveOutputs;
  13683. bool started;
  13684. OutputAdaptor* outputAdaptors;
  13685. CExtractMapperInput * * inputAdaptors;
  13686. bool * inputUsed;
  13687. bool * outputUsed;
  13688. Owned<IException> error;
  13689. CriticalSection crit;
  13690. rtlRowBuilder libraryExtractBuilder;
  13691. Owned<IActivityGraph> libraryGraph;
  13692. const LibraryCallFactoryExtra & extra;
  13693. public:
  13694. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13695. : CRoxieServerActivity(_factory, _probeManager),
  13696. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13697. {
  13698. numInputs = _numInputs;
  13699. numOutputs = _numOutputs;
  13700. numActiveOutputs = numOutputs;
  13701. inputAdaptors = new CExtractMapperInput*[numInputs];
  13702. inputUsed = new bool[numInputs];
  13703. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13704. {
  13705. inputAdaptors[i1] = new CExtractMapperInput;
  13706. inputUsed[i1] = false;
  13707. }
  13708. outputAdaptors = new OutputAdaptor[numOutputs];
  13709. outputUsed = new bool[numOutputs];
  13710. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13711. {
  13712. outputAdaptors[i2].parent = this;
  13713. outputAdaptors[i2].oid = i2;
  13714. outputUsed[i2] = false;
  13715. }
  13716. started = false;
  13717. }
  13718. ~CRoxieServerLibraryCallActivity()
  13719. {
  13720. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13721. ::Release(inputAdaptors[i1]);
  13722. delete [] inputAdaptors;
  13723. delete [] inputUsed;
  13724. delete [] outputAdaptors;
  13725. delete [] outputUsed;
  13726. }
  13727. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13728. {
  13729. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13730. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13731. libraryGraph->onCreate(_ctx, _colocalParent);
  13732. //Now map the inputs and outputs to the adapters
  13733. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13734. for (unsigned i1=0; i1<numInputs; i1++)
  13735. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13736. for (unsigned i2=0; i2<numOutputs; i2++)
  13737. {
  13738. unsigned outputIndex = extra.outputs.item(i2);
  13739. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13740. outputAdaptors[i2].setInput(output);
  13741. }
  13742. }
  13743. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13744. {
  13745. CriticalBlock b(crit);
  13746. if (error)
  13747. throw error.getLink();
  13748. if (factory)
  13749. factory->noteStarted(oid);
  13750. if (!started)
  13751. {
  13752. // even though it is not complete, we don't want to run this again if it fails.
  13753. started = true;
  13754. //see notes on splitter above
  13755. try
  13756. {
  13757. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13758. }
  13759. catch (IException *E)
  13760. {
  13761. #ifdef TRACE_SPLIT
  13762. CTXLOG("spill %d caught exception in start", activityId);
  13763. #endif
  13764. error.set(E);
  13765. throw;
  13766. }
  13767. catch (...)
  13768. {
  13769. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13770. error.set(E);
  13771. throw E;
  13772. }
  13773. //recreate the parent extract, and use it to reinitialize the graphs...
  13774. libraryExtractBuilder.clear();
  13775. helper.createParentExtract(libraryExtractBuilder);
  13776. // 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
  13777. // some inputs before we see start on others.
  13778. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13779. {
  13780. if (inputUsed[i1])
  13781. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13782. else
  13783. inputAdaptors[i1]->stop(false);
  13784. }
  13785. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13786. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13787. //call stop on all the unused inputs.
  13788. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13789. graph->beforeExecute();
  13790. ForEachItemIn(i3, extra.unusedOutputs)
  13791. {
  13792. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13793. output->stop(false);
  13794. }
  13795. }
  13796. }
  13797. virtual void stop(unsigned oid, bool aborting)
  13798. {
  13799. CriticalBlock b(crit);
  13800. if (--numActiveOutputs == 0)
  13801. {
  13802. //call stop on all the unused inputs.
  13803. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13804. graph->beforeExecute();
  13805. ForEachItemIn(i3, extra.unusedOutputs)
  13806. {
  13807. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13808. output->stop(false);
  13809. }
  13810. CRoxieServerActivity::stop(aborting);
  13811. }
  13812. }
  13813. void reset(unsigned oid)
  13814. {
  13815. started = false;
  13816. error.clear();
  13817. numActiveOutputs = numOutputs;
  13818. if (state != STATEreset) // make sure input is only reset once
  13819. {
  13820. CRoxieServerActivity::reset();
  13821. libraryGraph->reset();
  13822. //Call reset on all unused inputs/outputs from the graph - no one else will.
  13823. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13824. {
  13825. if (!inputUsed[i1])
  13826. inputAdaptors[i1]->reset();
  13827. }
  13828. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13829. ForEachItemIn(i3, extra.unusedOutputs)
  13830. {
  13831. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13832. output->reset();
  13833. }
  13834. }
  13835. };
  13836. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13837. {
  13838. inputAdaptors[idx]->setInput(_in);
  13839. }
  13840. public:
  13841. virtual const void *nextInGroup()
  13842. {
  13843. throwUnexpected(); // Internal logic error - we are not anybody's input
  13844. }
  13845. virtual IOutputMetaData * queryOutputMeta() const
  13846. {
  13847. throwUnexpected(); // should be called on outputs instead
  13848. }
  13849. virtual IRoxieInput *queryOutput(unsigned idx)
  13850. {
  13851. assertex(idx!=(unsigned)-1);
  13852. assertex(!outputUsed[idx]);
  13853. outputUsed[idx] = true;
  13854. return &outputAdaptors[idx];
  13855. }
  13856. };
  13857. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13858. {
  13859. ForEachItemIn(i1, _other.outputs)
  13860. outputs.append(_other.outputs.item(i1));
  13861. ForEachItemIn(i2, _other.unusedOutputs)
  13862. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13863. maxOutputs = _other.maxOutputs;
  13864. graphid = _other.graphid;
  13865. libraryName.set(_other.libraryName);
  13866. embeddedGraphName.set(_other.embeddedGraphName);
  13867. interfaceHash = _other.interfaceHash;
  13868. embedded = _other.embedded;
  13869. }
  13870. void LibraryCallFactoryExtra::calcUnused()
  13871. {
  13872. for (unsigned i=0; i < maxOutputs; i++)
  13873. if (!outputs.contains(i))
  13874. unusedOutputs.append(i);
  13875. }
  13876. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13877. {
  13878. private:
  13879. CRoxieServerMultiInputInfo inputs;
  13880. LibraryCallFactoryExtra extra;
  13881. public:
  13882. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13883. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13884. {
  13885. extra.set(_extra);
  13886. extra.calcUnused();
  13887. setNumOutputs(extra.outputs.ordinality());
  13888. }
  13889. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13890. {
  13891. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13892. }
  13893. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13894. {
  13895. inputs.set(idx, source, sourceidx);
  13896. }
  13897. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13898. {
  13899. return inputs.get(idx, sourceidx);
  13900. }
  13901. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13902. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13903. {
  13904. addXrefLibraryInfo(reply, extra.libraryName);
  13905. }
  13906. };
  13907. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13908. {
  13909. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13910. }
  13911. //=====================================================================================================
  13912. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13913. {
  13914. IHThorNWayInputArg & helper;
  13915. IRoxieInput ** inputs;
  13916. PointerArrayOf<IRoxieInput> selectedInputs;
  13917. unsigned numInputs;
  13918. public:
  13919. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13920. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13921. {
  13922. inputs = new IRoxieInput*[numInputs];
  13923. for (unsigned i = 0; i < numInputs; i++)
  13924. inputs[i] = NULL;
  13925. }
  13926. ~CRoxieServerNWayInputActivity()
  13927. {
  13928. delete [] inputs;
  13929. }
  13930. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13931. {
  13932. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13933. bool selectionIsAll;
  13934. size32_t selectionLen;
  13935. rtlDataAttr selection;
  13936. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13937. selectedInputs.kill();
  13938. if (selectionIsAll)
  13939. {
  13940. for (unsigned i=0; i < numInputs; i++)
  13941. selectedInputs.append(inputs[i]);
  13942. }
  13943. else
  13944. {
  13945. const size32_t * selections = (const size32_t *)selection.getdata();
  13946. unsigned max = selectionLen/sizeof(size32_t);
  13947. for (unsigned i = 0; i < max; i++)
  13948. {
  13949. unsigned nextIndex = selections[i];
  13950. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13951. for (unsigned j=i+1; j < max; j++)
  13952. {
  13953. if (nextIndex == selections[j])
  13954. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13955. }
  13956. if (nextIndex > numInputs)
  13957. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13958. selectedInputs.append(inputs[nextIndex-1]);
  13959. }
  13960. }
  13961. ForEachItemIn(i2, selectedInputs)
  13962. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13963. }
  13964. virtual void stop(bool aborting)
  13965. {
  13966. ForEachItemIn(i2, selectedInputs)
  13967. selectedInputs.item(i2)->stop(aborting);
  13968. CRoxieServerActivity::stop(aborting);
  13969. }
  13970. virtual unsigned __int64 queryLocalCycles() const
  13971. {
  13972. __int64 localCycles = totalCycles.totalCycles;
  13973. ForEachItemIn(i, selectedInputs)
  13974. {
  13975. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13976. }
  13977. if (localCycles < 0)
  13978. localCycles = 0;
  13979. return localCycles;
  13980. }
  13981. virtual IRoxieInput *queryInput(unsigned idx) const
  13982. {
  13983. if (selectedInputs.isItem(idx))
  13984. return selectedInputs.item(idx);
  13985. else
  13986. return NULL;
  13987. }
  13988. virtual void reset()
  13989. {
  13990. ForEachItemIn(i, selectedInputs)
  13991. selectedInputs.item(i)->reset();
  13992. selectedInputs.kill();
  13993. CRoxieServerActivity::reset();
  13994. }
  13995. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13996. {
  13997. assertex(idx < numInputs);
  13998. inputs[idx] = _in;
  13999. }
  14000. virtual const void * nextInGroup()
  14001. {
  14002. throwUnexpected();
  14003. }
  14004. virtual unsigned numConcreteOutputs() const
  14005. {
  14006. return selectedInputs.ordinality();
  14007. }
  14008. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  14009. {
  14010. if (selectedInputs.isItem(idx))
  14011. return selectedInputs.item(idx);
  14012. return NULL;
  14013. }
  14014. };
  14015. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14016. {
  14017. // bool ordered;
  14018. public:
  14019. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14020. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14021. {
  14022. }
  14023. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14024. {
  14025. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  14026. }
  14027. };
  14028. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14029. {
  14030. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14031. }
  14032. //=====================================================================================================
  14033. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  14034. {
  14035. IHThorNWayGraphLoopResultReadArg & helper;
  14036. CIArrayOf<CRoxieServerActivity> resultReaders;
  14037. PointerArrayOf<IRoxieInput> inputs;
  14038. unsigned graphId;
  14039. bool grouped;
  14040. bool selectionIsAll;
  14041. size32_t selectionLen;
  14042. rtlDataAttr selection;
  14043. public:
  14044. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14045. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14046. {
  14047. grouped = helper.isGrouped();
  14048. graphId = _graphId;
  14049. selectionIsAll = false;
  14050. selectionLen = 0;
  14051. }
  14052. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14053. {
  14054. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14055. if (inputs.ordinality() == 0)
  14056. {
  14057. initInputSelection();
  14058. unsigned max = selectionLen / sizeof(size32_t);
  14059. const size32_t * selections = (const size32_t *)selection.getdata();
  14060. IProbeManager * probeManager = NULL; // MORE!!
  14061. for (unsigned i = 0; i < max; i++)
  14062. {
  14063. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  14064. resultReaders.append(*resultInput);
  14065. inputs.append(resultInput->queryOutput(0));
  14066. resultInput->onCreate(ctx, colocalParent);
  14067. resultInput->start(parentExtractSize, parentExtract, paused);
  14068. }
  14069. }
  14070. else
  14071. {
  14072. ForEachItemIn(i, inputs)
  14073. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  14074. }
  14075. }
  14076. virtual void stop(bool aborting)
  14077. {
  14078. ForEachItemIn(i, inputs)
  14079. inputs.item(i)->stop(aborting);
  14080. CRoxieServerActivity::stop(aborting);
  14081. }
  14082. virtual void reset()
  14083. {
  14084. ForEachItemIn(i, inputs)
  14085. inputs.item(i)->reset();
  14086. inputs.kill();
  14087. resultReaders.kill();
  14088. CRoxieServerActivity::reset();
  14089. }
  14090. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14091. {
  14092. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  14093. }
  14094. virtual const void * nextInGroup()
  14095. {
  14096. throwUnexpected();
  14097. }
  14098. virtual unsigned numConcreteOutputs() const
  14099. {
  14100. return inputs.ordinality();
  14101. }
  14102. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  14103. {
  14104. if (inputs.isItem(idx))
  14105. return inputs.item(idx);
  14106. return NULL;
  14107. }
  14108. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14109. {
  14110. ensureCreated();
  14111. basehelper.onStart(parentExtract, NULL);
  14112. initInputSelection();
  14113. unsigned max = selectionLen / sizeof(size32_t);
  14114. const size32_t * selections = (const size32_t *)selection.getdata();
  14115. for (unsigned i = 0; i < max; i++)
  14116. processor.noteUseIteration(selections[i]);
  14117. }
  14118. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  14119. {
  14120. //selection etc. already initialised from the gratherIterationUsage() call.
  14121. unsigned max = selectionLen / sizeof(size32_t);
  14122. const size32_t * selections = (const size32_t *)selection.getdata();
  14123. for (unsigned i = 0; i < max; i++)
  14124. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  14125. }
  14126. protected:
  14127. void initInputSelection()
  14128. {
  14129. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14130. if (selectionIsAll)
  14131. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14132. }
  14133. };
  14134. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14135. {
  14136. unsigned graphId;
  14137. public:
  14138. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  14139. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  14140. {
  14141. }
  14142. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14143. {
  14144. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  14145. }
  14146. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14147. {
  14148. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14149. }
  14150. };
  14151. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  14152. {
  14153. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  14154. }
  14155. //=================================================================================
  14156. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  14157. {
  14158. public:
  14159. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  14160. IMPLEMENT_IINTERFACE
  14161. protected:
  14162. virtual const void * nextInputRow()
  14163. {
  14164. #ifdef TRACE_SEEK_REQUESTS
  14165. IRoxieContextLogger * logger = input->queryActivity();
  14166. const void * ret = doNextInputRow();
  14167. {
  14168. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14169. if (!ret)
  14170. xmlwrite.outputBool(true,"eof");
  14171. else if (input->queryOutputMeta()->hasXML())
  14172. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14173. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14174. }
  14175. return ret;
  14176. #else
  14177. return doNextInputRow();
  14178. #endif
  14179. }
  14180. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14181. {
  14182. #ifdef TRACE_SEEK_REQUESTS
  14183. IRoxieContextLogger * logger = input->queryActivity();
  14184. {
  14185. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14186. if (input->queryOutputMeta()->hasXML())
  14187. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14188. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14189. numFields,
  14190. stepExtra.readAheadManyResults() ? "readahead " : "",
  14191. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14192. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14193. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14194. xmlwrite.str());
  14195. }
  14196. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14197. {
  14198. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14199. if (!ret)
  14200. xmlwrite.outputBool(true,"eof");
  14201. else if (input->queryOutputMeta()->hasXML())
  14202. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14203. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14204. numFields,
  14205. stepExtra.readAheadManyResults() ? "readahead " : "",
  14206. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14207. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14208. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14209. xmlwrite.str());
  14210. }
  14211. return ret;
  14212. #else
  14213. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14214. #endif
  14215. }
  14216. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14217. {
  14218. return input->gatherConjunctions(collector);
  14219. }
  14220. virtual void resetEOF()
  14221. {
  14222. input->resetEOF();
  14223. }
  14224. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14225. {
  14226. return input->querySteppingMeta();
  14227. }
  14228. inline const void * doNextInputRow()
  14229. {
  14230. const void * ret = input->nextInGroup();
  14231. if (!ret)
  14232. ret = input->nextInGroup();
  14233. return ret;
  14234. }
  14235. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14236. {
  14237. assertex(wasCompleteMatch);
  14238. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14239. }
  14240. protected:
  14241. IRoxieInput * input;
  14242. };
  14243. //=================================================================================
  14244. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  14245. {
  14246. public:
  14247. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14248. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  14249. {
  14250. }
  14251. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14252. {
  14253. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14254. for (unsigned i=0; i < numInputs; i++)
  14255. {
  14256. IRoxieInput * cur = inputArray[i];
  14257. unsigned numRealInputs = cur->numConcreteOutputs();
  14258. for (unsigned j = 0; j < numRealInputs; j++)
  14259. {
  14260. IRoxieInput * curReal = cur->queryConcreteInput(j);
  14261. expandedInputs.append(curReal);
  14262. }
  14263. }
  14264. }
  14265. virtual void reset()
  14266. {
  14267. expandedInputs.kill();
  14268. CRoxieServerMultiInputActivity::reset();
  14269. }
  14270. protected:
  14271. PointerArrayOf<IRoxieInput> expandedInputs;
  14272. };
  14273. //=================================================================================
  14274. class CRoxieStreamMerger : public CStreamMerger
  14275. {
  14276. public:
  14277. CRoxieStreamMerger() : CStreamMerger(true)
  14278. {
  14279. inputArray = NULL;
  14280. }
  14281. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  14282. {
  14283. CStreamMerger::initInputs(_numInputs);
  14284. inputArray = _inputArray;
  14285. }
  14286. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14287. {
  14288. const void * next;
  14289. bool matches = true;
  14290. if (seek)
  14291. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  14292. else
  14293. next = nextUngrouped(inputArray[i]);
  14294. pending[i] = next;
  14295. pendingMatches[i] = matches;
  14296. return (next != NULL);
  14297. }
  14298. virtual void releaseRow(const void * row)
  14299. {
  14300. ReleaseRoxieRow(row);
  14301. }
  14302. protected:
  14303. IRoxieInput **inputArray;
  14304. };
  14305. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14306. {
  14307. public:
  14308. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14309. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  14310. helper((IHThorNWayMergeArg &)basehelper)
  14311. {
  14312. initializedMeta = false;
  14313. }
  14314. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14315. {
  14316. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14317. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14318. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  14319. }
  14320. virtual void stop(bool aborting)
  14321. {
  14322. merger.done();
  14323. CRoxieServerNaryActivity::stop(aborting);
  14324. }
  14325. virtual void reset()
  14326. {
  14327. merger.cleanup();
  14328. CRoxieServerNaryActivity::reset();
  14329. initializedMeta = false;
  14330. }
  14331. virtual const void * nextInGroup()
  14332. {
  14333. ActivityTimer t(totalCycles, timeActivities);
  14334. const void * next = merger.nextRow();
  14335. if (next)
  14336. processed++;
  14337. return next;
  14338. }
  14339. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14340. {
  14341. ActivityTimer t(totalCycles, timeActivities);
  14342. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14343. if (next)
  14344. processed++;
  14345. return next;
  14346. }
  14347. virtual IInputSteppingMeta * querySteppingMeta()
  14348. {
  14349. if (expandedInputs.ordinality() == 0)
  14350. return NULL;
  14351. if (!initializedMeta)
  14352. {
  14353. meta.init(helper.querySteppingMeta(), false);
  14354. ForEachItemIn(i, expandedInputs)
  14355. {
  14356. if (meta.getNumFields() == 0)
  14357. break;
  14358. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14359. meta.intersect(inputMeta);
  14360. }
  14361. initializedMeta = true;
  14362. }
  14363. if (meta.getNumFields() == 0)
  14364. return NULL;
  14365. return &meta;
  14366. }
  14367. protected:
  14368. IHThorNWayMergeArg &helper;
  14369. CRoxieStreamMerger merger;
  14370. CSteppingMeta meta;
  14371. bool initializedMeta;
  14372. };
  14373. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14374. {
  14375. public:
  14376. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14377. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14378. {
  14379. }
  14380. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14381. {
  14382. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14383. }
  14384. };
  14385. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14386. {
  14387. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14388. }
  14389. //=================================================================================
  14390. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14391. {
  14392. public:
  14393. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14394. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14395. helper((IHThorNWayMergeJoinArg &)basehelper)
  14396. {
  14397. }
  14398. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14399. {
  14400. CRoxieServerNaryActivity::onCreate(_ctx, _colocalParent);
  14401. ICodeContext * codectx = ctx->queryCodeContext();
  14402. inputAllocator.setown(codectx->getRowAllocator(helper.queryInputMeta(), activityId));
  14403. outputAllocator.setown(codectx->getRowAllocator(helper.queryOutputMeta(), activityId));
  14404. }
  14405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14406. {
  14407. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14408. ForEachItemIn(i1, expandedInputs)
  14409. {
  14410. IRoxieInput * cur = expandedInputs.item(i1);
  14411. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14412. processor.addInput(stepInput);
  14413. }
  14414. processor.beforeProcessing(inputAllocator, outputAllocator);
  14415. }
  14416. virtual void stop(bool aborting)
  14417. {
  14418. processor.afterProcessing();
  14419. CRoxieServerNaryActivity::stop(aborting);
  14420. }
  14421. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14422. {
  14423. return processor.gatherConjunctions(collector);
  14424. }
  14425. virtual void resetEOF()
  14426. {
  14427. processor.queryResetEOF();
  14428. }
  14429. virtual const void * nextInGroup()
  14430. {
  14431. ActivityTimer t(totalCycles, timeActivities);
  14432. const void * next = processor.nextInGroup();
  14433. if (next)
  14434. processed++;
  14435. return next;
  14436. }
  14437. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14438. {
  14439. ActivityTimer t(totalCycles, timeActivities);
  14440. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14441. if (next)
  14442. processed++;
  14443. return next;
  14444. }
  14445. virtual IInputSteppingMeta * querySteppingMeta()
  14446. {
  14447. return processor.queryInputSteppingMeta();
  14448. }
  14449. protected:
  14450. IHThorNWayMergeJoinArg & helper;
  14451. CMergeJoinProcessor & processor;
  14452. Owned<IEngineRowAllocator> inputAllocator;
  14453. Owned<IEngineRowAllocator> outputAllocator;
  14454. };
  14455. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14456. {
  14457. public:
  14458. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14459. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14460. {
  14461. }
  14462. protected:
  14463. CAndMergeJoinProcessor andProcessor;
  14464. };
  14465. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14466. {
  14467. public:
  14468. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14469. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14470. {
  14471. }
  14472. protected:
  14473. CAndLeftMergeJoinProcessor andLeftProcessor;
  14474. };
  14475. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14476. {
  14477. public:
  14478. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14479. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14480. {
  14481. }
  14482. protected:
  14483. CMofNMergeJoinProcessor mofnProcessor;
  14484. };
  14485. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14486. {
  14487. public:
  14488. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14489. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14490. {
  14491. }
  14492. protected:
  14493. CProximityJoinProcessor proximityProcessor;
  14494. };
  14495. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14496. {
  14497. unsigned flags;
  14498. public:
  14499. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14500. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14501. {
  14502. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14503. flags = helper->getJoinFlags();
  14504. }
  14505. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14506. {
  14507. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14508. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14509. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14510. {
  14511. case IHThorNWayMergeJoinArg::MJFinner:
  14512. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14513. case IHThorNWayMergeJoinArg::MJFleftonly:
  14514. case IHThorNWayMergeJoinArg::MJFleftouter:
  14515. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14516. case IHThorNWayMergeJoinArg::MJFmofn:
  14517. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14518. default:
  14519. throwUnexpected();
  14520. }
  14521. }
  14522. };
  14523. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14524. {
  14525. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14526. }
  14527. //=================================================================================
  14528. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14529. {
  14530. IHThorNWaySelectArg &helper;
  14531. public:
  14532. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14533. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14534. helper((IHThorNWaySelectArg &)basehelper)
  14535. {
  14536. selectedInput = NULL;
  14537. }
  14538. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14539. {
  14540. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14541. unsigned whichInput = helper.getInputIndex();
  14542. selectedInput = NULL;
  14543. if (whichInput--)
  14544. {
  14545. for (unsigned i=0; i < numInputs; i++)
  14546. {
  14547. IRoxieInput * cur = inputArray[i];
  14548. unsigned numRealInputs = cur->numConcreteOutputs();
  14549. if (whichInput < numRealInputs)
  14550. {
  14551. selectedInput = cur->queryConcreteInput(whichInput);
  14552. break;
  14553. }
  14554. whichInput -= numRealInputs;
  14555. }
  14556. }
  14557. }
  14558. virtual void reset()
  14559. {
  14560. selectedInput = NULL;
  14561. CRoxieServerMultiInputActivity::reset();
  14562. }
  14563. const void * nextInGroup()
  14564. {
  14565. ActivityTimer t(totalCycles, timeActivities);
  14566. if (!selectedInput)
  14567. return NULL;
  14568. return selectedInput->nextInGroup();
  14569. }
  14570. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14571. {
  14572. if (!selectedInput)
  14573. return false;
  14574. return selectedInput->gatherConjunctions(collector);
  14575. }
  14576. virtual void resetEOF()
  14577. {
  14578. if (selectedInput)
  14579. selectedInput->resetEOF();
  14580. }
  14581. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14582. {
  14583. ActivityTimer t(totalCycles, timeActivities);
  14584. if (!selectedInput)
  14585. return NULL;
  14586. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14587. }
  14588. IInputSteppingMeta * querySteppingMeta()
  14589. {
  14590. if (selectedInput)
  14591. return selectedInput->querySteppingMeta();
  14592. return NULL;
  14593. }
  14594. protected:
  14595. IRoxieInput * selectedInput;
  14596. };
  14597. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14598. {
  14599. public:
  14600. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14601. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14602. {
  14603. }
  14604. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14605. {
  14606. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14607. }
  14608. };
  14609. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14610. {
  14611. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14612. }
  14613. //=================================================================================
  14614. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14615. {
  14616. protected:
  14617. IHThorRemoteArg &helper;
  14618. CRemoteResultAdaptor remote;
  14619. public:
  14620. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14621. : CRoxieServerActivity(_factory, _probeManager),
  14622. helper((IHThorRemoteArg &)basehelper),
  14623. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14624. {
  14625. }
  14626. virtual const IResolvedFile *queryVarFileInfo() const
  14627. {
  14628. return NULL;
  14629. }
  14630. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14631. {
  14632. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14633. remote.onCreate(this, this, _ctx, _colocalParent);
  14634. }
  14635. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14636. {
  14637. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14638. remote.onStart(parentExtractSize, parentExtract);
  14639. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14640. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14641. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14642. remote.flush();
  14643. remote.senddone();
  14644. }
  14645. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14646. {
  14647. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14648. }
  14649. virtual IRoxieInput *queryOutput(unsigned idx)
  14650. {
  14651. if (idx==(unsigned)-1)
  14652. idx = 0;
  14653. return idx ? NULL: &remote;
  14654. }
  14655. virtual void reset()
  14656. {
  14657. processed = remote.processed;
  14658. remote.processed = 0;
  14659. CRoxieServerActivity::reset();
  14660. }
  14661. virtual void onLimitExceeded(bool isKeyed)
  14662. {
  14663. if (traceLevel > 4)
  14664. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14665. helper.onLimitExceeded();
  14666. }
  14667. virtual const void *createLimitFailRow(bool isKeyed)
  14668. {
  14669. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14670. }
  14671. virtual const void *nextInGroup()
  14672. {
  14673. throwUnexpected(); // I am nobody's input
  14674. }
  14675. };
  14676. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14677. {
  14678. public:
  14679. RemoteActivityId remoteId;
  14680. bool isRoot;
  14681. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14682. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14683. {
  14684. }
  14685. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14686. {
  14687. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14688. }
  14689. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14690. {
  14691. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14692. }
  14693. virtual bool isSink() const
  14694. {
  14695. //I don't think the action version of this is implemented - but this would be the code
  14696. return isRoot && !meta.queryOriginal();
  14697. }
  14698. virtual const StatisticsMapping &queryStatsMapping() const
  14699. {
  14700. return allStatistics; // Child queries...
  14701. }
  14702. };
  14703. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14704. {
  14705. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14706. }
  14707. //=================================================================================
  14708. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14709. {
  14710. IHThorIterateArg &helper;
  14711. OwnedConstRoxieRow defaultRecord;
  14712. OwnedConstRoxieRow left;
  14713. OwnedConstRoxieRow right;
  14714. unsigned counter;
  14715. public:
  14716. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14717. : CRoxieServerActivity(_factory, _probeManager),
  14718. helper((IHThorIterateArg &)basehelper)
  14719. {
  14720. counter = 0;
  14721. }
  14722. virtual bool needsAllocator() const { return true; }
  14723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14724. {
  14725. counter = 0;
  14726. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14727. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14728. size32_t thisSize = helper.createDefault(rowBuilder);
  14729. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14730. }
  14731. virtual void reset()
  14732. {
  14733. defaultRecord.clear();
  14734. right.clear();
  14735. left.clear();
  14736. CRoxieServerActivity::reset();
  14737. }
  14738. virtual const void * nextInGroup()
  14739. {
  14740. ActivityTimer t(totalCycles, timeActivities);
  14741. loop
  14742. {
  14743. right.setown(input->nextInGroup());
  14744. if (!right)
  14745. {
  14746. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14747. left.clear();
  14748. counter = 0;
  14749. if (skippedGroup) continue;
  14750. return NULL;
  14751. }
  14752. try
  14753. {
  14754. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14755. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14756. if (outSize)
  14757. {
  14758. left.setown(rowBuilder.finalizeRowClear(outSize));
  14759. processed++;
  14760. return left.getLink();
  14761. }
  14762. }
  14763. catch (IException *E)
  14764. {
  14765. throw makeWrappedException(E);
  14766. }
  14767. }
  14768. }
  14769. };
  14770. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14771. {
  14772. public:
  14773. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14774. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14775. {
  14776. }
  14777. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14778. {
  14779. return new CRoxieServerIterateActivity(this, _probeManager);
  14780. }
  14781. };
  14782. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14783. {
  14784. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14785. }
  14786. //=================================================================================
  14787. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14788. {
  14789. IHThorProcessArg &helper;
  14790. OwnedConstRoxieRow curRight;
  14791. OwnedConstRoxieRow initialRight;
  14792. unsigned counter;
  14793. Owned<IEngineRowAllocator> rightRowAllocator;
  14794. public:
  14795. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14796. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14797. {
  14798. counter = 0;
  14799. }
  14800. virtual bool needsAllocator() const { return true; }
  14801. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14802. {
  14803. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14804. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14805. }
  14806. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14807. {
  14808. counter = 0;
  14809. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14810. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14811. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14812. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14813. curRight.set(initialRight);
  14814. }
  14815. virtual const void * nextInGroup()
  14816. {
  14817. ActivityTimer t(totalCycles, timeActivities);
  14818. try
  14819. {
  14820. loop
  14821. {
  14822. const void * in = input->nextInGroup();
  14823. if (!in)
  14824. {
  14825. bool eog = (curRight != initialRight); // processed any records?
  14826. counter = 0;
  14827. curRight.set(initialRight);
  14828. if (eog)
  14829. return NULL;
  14830. in = input->nextInGroup();
  14831. if (!in)
  14832. return NULL;
  14833. }
  14834. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14835. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14836. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14837. ReleaseRoxieRow(in);
  14838. if (outSize)
  14839. {
  14840. //MORE: This should be returned...
  14841. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14842. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14843. processed++;
  14844. return rowBuilder.finalizeRowClear(outSize);
  14845. }
  14846. }
  14847. }
  14848. catch (IException *E)
  14849. {
  14850. throw makeWrappedException(E);
  14851. }
  14852. }
  14853. };
  14854. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14855. {
  14856. public:
  14857. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14858. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14859. {
  14860. }
  14861. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14862. {
  14863. return new CRoxieServerProcessActivity(this, _probeManager);
  14864. }
  14865. };
  14866. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14867. {
  14868. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14869. }
  14870. //=================================================================================
  14871. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14872. {
  14873. IHThorGroupArg &helper;
  14874. bool endPending;
  14875. bool eof;
  14876. bool first;
  14877. const void *next;
  14878. public:
  14879. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14880. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14881. {
  14882. next = NULL;
  14883. endPending = false;
  14884. eof = false;
  14885. first = true;
  14886. }
  14887. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14888. {
  14889. endPending = false;
  14890. eof = false;
  14891. first = true;
  14892. assertex(next == NULL);
  14893. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14894. }
  14895. virtual void reset()
  14896. {
  14897. ReleaseClearRoxieRow(next);
  14898. CRoxieServerActivity::reset();
  14899. }
  14900. virtual const void * nextInGroup()
  14901. {
  14902. ActivityTimer t(totalCycles, timeActivities);
  14903. if (first)
  14904. {
  14905. next = input->nextInGroup();
  14906. first = false;
  14907. }
  14908. if (eof || endPending)
  14909. {
  14910. endPending = false;
  14911. return NULL;
  14912. }
  14913. const void * prev = next;
  14914. next = input->nextInGroup();
  14915. if (!next)
  14916. next = input->nextInGroup();
  14917. if (next)
  14918. {
  14919. assertex(prev);
  14920. if (!helper.isSameGroup(prev, next))
  14921. endPending = true;
  14922. }
  14923. else
  14924. eof = true;
  14925. if (prev)
  14926. processed++;
  14927. return prev;
  14928. }
  14929. };
  14930. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14931. {
  14932. public:
  14933. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14934. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14935. {
  14936. }
  14937. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14938. {
  14939. return new CRoxieServerGroupActivity(this, _probeManager);
  14940. }
  14941. };
  14942. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14943. {
  14944. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14945. }
  14946. //=================================================================================
  14947. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14948. {
  14949. unsigned __int64 limit;
  14950. unsigned __int64 skip;
  14951. unsigned doneThisGroup;
  14952. IHThorFirstNArg &helper;
  14953. public:
  14954. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14955. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14956. {
  14957. doneThisGroup = 0;
  14958. limit = 0;
  14959. skip = 0;
  14960. }
  14961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14962. {
  14963. doneThisGroup = 0;
  14964. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14965. limit = helper.getLimit();
  14966. skip = helper.numToSkip();
  14967. lateStart(parentExtractSize, parentExtract, limit > 0);
  14968. if (limit + skip >= limit)
  14969. limit += skip;
  14970. }
  14971. const void * nextInGroup()
  14972. {
  14973. ActivityTimer t(totalCycles, timeActivities);
  14974. if (eof)
  14975. return NULL;
  14976. const void *ret;
  14977. loop
  14978. {
  14979. ret = input->nextInGroup();
  14980. if (!ret)
  14981. {
  14982. if (meta.isGrouped())
  14983. {
  14984. if (doneThisGroup > skip)
  14985. {
  14986. doneThisGroup = 0;
  14987. return NULL;
  14988. }
  14989. doneThisGroup = 0;
  14990. }
  14991. ret = input->nextInGroup();
  14992. if (!ret)
  14993. {
  14994. eof = true;
  14995. return NULL;
  14996. }
  14997. }
  14998. doneThisGroup++;
  14999. if (doneThisGroup > skip)
  15000. break;
  15001. ReleaseRoxieRow(ret);
  15002. }
  15003. if (doneThisGroup <= limit)
  15004. {
  15005. processed++;
  15006. return ret;
  15007. }
  15008. ReleaseRoxieRow(ret);
  15009. if (meta.isGrouped())
  15010. {
  15011. while ((ret = input->nextInGroup()) != NULL)
  15012. ReleaseRoxieRow(ret);
  15013. doneThisGroup = 0;
  15014. }
  15015. else
  15016. eof = true;
  15017. return NULL;
  15018. }
  15019. };
  15020. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15021. {
  15022. public:
  15023. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15024. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15025. {
  15026. }
  15027. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15028. {
  15029. return new CRoxieServerFirstNActivity(this, _probeManager);
  15030. }
  15031. };
  15032. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15033. {
  15034. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15035. }
  15036. //=================================================================================
  15037. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15038. {
  15039. bool done;
  15040. IHThorSelectNArg &helper;
  15041. public:
  15042. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15043. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15044. {
  15045. done = false;
  15046. }
  15047. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15048. {
  15049. done = false;
  15050. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15051. }
  15052. const void *defaultRow()
  15053. {
  15054. if (!rowAllocator)
  15055. createRowAllocator(); // We delay as often not needed...
  15056. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15057. size32_t thisSize = helper.createDefault(rowBuilder);
  15058. return rowBuilder.finalizeRowClear(thisSize);
  15059. }
  15060. virtual const void * nextInGroup()
  15061. {
  15062. ActivityTimer t(totalCycles, timeActivities);
  15063. if (done)
  15064. return NULL;
  15065. done = true;
  15066. processed++; // always going to return a row!
  15067. unsigned __int64 index = helper.getRowToSelect();
  15068. while (--index)
  15069. {
  15070. const void * next = input->nextInGroup();
  15071. if (!next)
  15072. next = input->nextInGroup();
  15073. if (!next)
  15074. return defaultRow();
  15075. ReleaseRoxieRow(next);
  15076. }
  15077. const void * next = input->nextInGroup();
  15078. if (!next)
  15079. next = input->nextInGroup();
  15080. if (!next)
  15081. next = defaultRow();
  15082. return next;
  15083. }
  15084. };
  15085. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15086. {
  15087. public:
  15088. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15089. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15090. {
  15091. }
  15092. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15093. {
  15094. return new CRoxieServerSelectNActivity(this, _probeManager);
  15095. }
  15096. };
  15097. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15098. {
  15099. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15100. }
  15101. //=================================================================================
  15102. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15103. {
  15104. IHThorJoinArg &helper;
  15105. ICompare *collate;
  15106. OwnedRowArray group;
  15107. bool matchedLeft;
  15108. BoolArray matchedRight;
  15109. bool eof;
  15110. bool first;
  15111. unsigned leftIndex;
  15112. unsigned rightIndex;
  15113. unsigned rightOuterIndex;
  15114. unsigned joinLimit;
  15115. unsigned atmostLimit;
  15116. unsigned atmostsTriggered;
  15117. unsigned abortLimit;
  15118. unsigned keepLimit;
  15119. unsigned joinCounter;
  15120. bool leftOuterJoin;
  15121. bool rightOuterJoin;
  15122. bool exclude;
  15123. bool limitFail;
  15124. bool limitOnFail;
  15125. bool cloneLeft;
  15126. OwnedConstRoxieRow defaultLeft;
  15127. OwnedConstRoxieRow defaultRight;
  15128. OwnedConstRoxieRow lhs;
  15129. Owned<IException> failingLimit;
  15130. bool failingOuterAtmost;
  15131. Owned<IEngineRowAllocator> defaultAllocator;
  15132. Owned<IRHLimitedCompareHelper> limitedhelper;
  15133. Owned<CRHDualCache> dualcache;
  15134. IInputBase *dualCacheInput;
  15135. bool fillGroup()
  15136. {
  15137. group.clear();
  15138. matchedLeft = false;
  15139. matchedRight.kill();
  15140. failingOuterAtmost = false;
  15141. const void * next;
  15142. unsigned groupCount = 0;
  15143. while((next = input->nextInGroup()) != NULL)
  15144. {
  15145. if(groupCount==abortLimit)
  15146. {
  15147. if(limitFail)
  15148. failLimit(next);
  15149. if (ctx->queryDebugContext())
  15150. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15151. if(limitOnFail)
  15152. {
  15153. assertex(!failingLimit);
  15154. try
  15155. {
  15156. failLimit(next);
  15157. }
  15158. catch(IException * except)
  15159. {
  15160. failingLimit.setown(except);
  15161. }
  15162. assertex(failingLimit != NULL);
  15163. group.append(next);
  15164. groupCount++;
  15165. break;
  15166. }
  15167. group.clear();
  15168. groupCount = 0;
  15169. while(next)
  15170. {
  15171. ReleaseRoxieRow(next);
  15172. next = input->nextInGroup();
  15173. }
  15174. }
  15175. else if(groupCount==atmostLimit)
  15176. {
  15177. atmostsTriggered++;
  15178. if(leftOuterJoin)
  15179. {
  15180. group.append(next);
  15181. groupCount++;
  15182. failingOuterAtmost = true;
  15183. break;
  15184. }
  15185. else
  15186. {
  15187. group.clear();
  15188. groupCount = 0;
  15189. while (next)
  15190. {
  15191. ReleaseRoxieRow(next);
  15192. next = input->nextInGroup();
  15193. }
  15194. }
  15195. }
  15196. else
  15197. {
  15198. group.append(next);
  15199. groupCount++;
  15200. }
  15201. }
  15202. if(group.ordinality()==0)
  15203. {
  15204. eof = true;
  15205. return false;
  15206. }
  15207. leftIndex = 0;
  15208. rightIndex = 0;
  15209. rightOuterIndex = 0;
  15210. joinCounter = 0;
  15211. joinLimit = keepLimit;
  15212. ForEachItemIn(idx, group)
  15213. matchedRight.append(false);
  15214. return true;
  15215. }
  15216. void failLimit(const void * next)
  15217. {
  15218. helper.onMatchAbortLimitExceeded();
  15219. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15220. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15221. {
  15222. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15223. }
  15224. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15225. }
  15226. virtual bool needsAllocator() const { return true; }
  15227. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15228. {
  15229. try
  15230. {
  15231. if (cloneLeft && !except)
  15232. {
  15233. LinkRoxieRow(curLeft);
  15234. return curLeft;
  15235. }
  15236. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15237. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15238. if (outsize)
  15239. return rowBuilder.finalizeRowClear(outsize);
  15240. else
  15241. return NULL;
  15242. }
  15243. catch (IException *E)
  15244. {
  15245. throw makeWrappedException(E);
  15246. }
  15247. }
  15248. void createDefaultLeft()
  15249. {
  15250. if (!defaultLeft)
  15251. {
  15252. if (!defaultAllocator)
  15253. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15254. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15255. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15256. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15257. }
  15258. }
  15259. void createDefaultRight()
  15260. {
  15261. if (!defaultRight)
  15262. {
  15263. if (!defaultAllocator)
  15264. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15265. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15266. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15267. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15268. }
  15269. }
  15270. public:
  15271. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15272. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  15273. {
  15274. collate = helper.queryCompareLeftRight();
  15275. eof = false;
  15276. first = true;
  15277. keepLimit = 0;
  15278. atmostLimit = 0;
  15279. atmostsTriggered = 0;
  15280. unsigned joinFlags = helper.getJoinFlags();
  15281. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15282. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15283. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15284. exclude = (joinFlags & JFexclude) != 0;
  15285. abortLimit = 0;
  15286. joinLimit = 0;
  15287. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15288. getLimitType(joinFlags, limitFail, limitOnFail);
  15289. if((joinFlags & JFslidingmatch) != 0)
  15290. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15291. failingOuterAtmost = false;
  15292. matchedLeft = false;
  15293. leftIndex = 0;
  15294. rightIndex = 0;
  15295. rightOuterIndex = 0;
  15296. joinCounter = 0;
  15297. dualCacheInput = NULL;
  15298. }
  15299. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15300. {
  15301. eof = false;
  15302. first = true;
  15303. failingLimit.clear();
  15304. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15305. keepLimit = helper.getKeepLimit();
  15306. if(keepLimit == 0)
  15307. keepLimit = (unsigned)-1;
  15308. atmostsTriggered = 0;
  15309. atmostLimit = helper.getJoinLimit();
  15310. if(atmostLimit == 0)
  15311. atmostLimit = (unsigned)-1;
  15312. else
  15313. assertex(!rightOuterJoin);
  15314. abortLimit = helper.getMatchAbortLimit();
  15315. if (abortLimit == 0)
  15316. abortLimit = (unsigned)-1;
  15317. if (rightOuterJoin)
  15318. createDefaultLeft();
  15319. if (leftOuterJoin || limitOnFail)
  15320. createDefaultRight();
  15321. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15322. { //limited match join (s[1..n])
  15323. dualcache.setown(new CRHDualCache());
  15324. dualcache->init(CRoxieServerActivity::input);
  15325. dualCacheInput = dualcache->queryOut1();
  15326. failingOuterAtmost = false;
  15327. matchedLeft = false;
  15328. leftIndex = 0;
  15329. rightOuterIndex = 0;
  15330. joinCounter = 0;
  15331. limitedhelper.setown(createRHLimitedCompareHelper());
  15332. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15333. }
  15334. }
  15335. virtual void reset()
  15336. {
  15337. if (atmostsTriggered)
  15338. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15339. group.clear();
  15340. CRoxieServerActivity::reset();
  15341. defaultLeft.clear();
  15342. defaultRight.clear();
  15343. }
  15344. virtual const void * nextInGroup()
  15345. {
  15346. ActivityTimer t(totalCycles, timeActivities);
  15347. if (limitedhelper)
  15348. {
  15349. while(!eof) //limited match join
  15350. {
  15351. if (!group.isItem(rightIndex))
  15352. {
  15353. lhs.setown(dualCacheInput->nextInGroup());
  15354. if (lhs)
  15355. {
  15356. rightIndex = 0;
  15357. joinCounter = 0;
  15358. group.clear();
  15359. limitedhelper->getGroup(group,lhs);
  15360. }
  15361. else
  15362. {
  15363. eof = true;
  15364. }
  15365. }
  15366. if (group.isItem(rightIndex))
  15367. {
  15368. const void * rhs = group.item(rightIndex++);
  15369. if(helper.match(lhs, rhs))
  15370. {
  15371. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15372. return ret;
  15373. }
  15374. }
  15375. }
  15376. return NULL;
  15377. }
  15378. else
  15379. {
  15380. if (first)
  15381. {
  15382. first = false;
  15383. fillGroup();
  15384. }
  15385. while(!eof)
  15386. {
  15387. if(failingOuterAtmost)
  15388. while(group.isItem(leftIndex))
  15389. {
  15390. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  15391. if(ret)
  15392. {
  15393. processed++;
  15394. return ret;
  15395. }
  15396. }
  15397. if((joinLimit == 0) || !group.isItem(rightIndex))
  15398. {
  15399. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15400. {
  15401. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  15402. if(ret)
  15403. {
  15404. matchedLeft = true;
  15405. processed++;
  15406. return ret;
  15407. }
  15408. }
  15409. leftIndex++;
  15410. matchedLeft = false;
  15411. rightIndex = 0;
  15412. joinCounter = 0;
  15413. joinLimit = keepLimit;
  15414. }
  15415. if(!group.isItem(leftIndex))
  15416. {
  15417. if(failingLimit || failingOuterAtmost)
  15418. {
  15419. const void * lhs;
  15420. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15421. {
  15422. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15423. ReleaseRoxieRow(lhs);
  15424. if(ret)
  15425. {
  15426. processed++;
  15427. return ret;
  15428. }
  15429. }
  15430. failingLimit.clear();
  15431. }
  15432. if(rightOuterJoin && !failingLimit)
  15433. while(group.isItem(rightOuterIndex))
  15434. if(!matchedRight.item(rightOuterIndex++))
  15435. {
  15436. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  15437. if(ret)
  15438. {
  15439. processed++;
  15440. return ret;
  15441. }
  15442. }
  15443. if(!fillGroup())
  15444. return NULL;
  15445. continue;
  15446. }
  15447. const void * lhs = group.item(leftIndex);
  15448. if(failingLimit)
  15449. {
  15450. leftIndex++;
  15451. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15452. if(ret)
  15453. {
  15454. processed++;
  15455. return ret;
  15456. }
  15457. }
  15458. else
  15459. {
  15460. const void * rhs = group.item(rightIndex++);
  15461. if(helper.match(lhs, rhs))
  15462. {
  15463. matchedLeft = true;
  15464. matchedRight.replace(true, rightIndex-1);
  15465. if(!exclude)
  15466. {
  15467. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15468. if(ret)
  15469. {
  15470. processed++;
  15471. joinLimit--;
  15472. return ret;
  15473. }
  15474. }
  15475. }
  15476. }
  15477. }
  15478. return NULL;
  15479. }
  15480. }
  15481. };
  15482. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15483. {
  15484. public:
  15485. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15486. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15487. {
  15488. }
  15489. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15490. {
  15491. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15492. }
  15493. virtual const StatisticsMapping &queryStatsMapping() const
  15494. {
  15495. return joinStatistics;
  15496. }
  15497. };
  15498. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15499. {
  15500. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15501. }
  15502. //=====================================================================================================
  15503. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15504. {
  15505. private:
  15506. class LookupTable : public CInterface
  15507. {
  15508. public:
  15509. LookupTable(IHThorHashJoinArg &helper)
  15510. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  15511. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  15512. {
  15513. size = 0;
  15514. }
  15515. virtual const void *find(const void * left) const = 0;
  15516. virtual const void *findNext(const void * left) const = 0;
  15517. protected:
  15518. ICompare * leftRightCompare;
  15519. ICompare * rightCompare;
  15520. IHash * leftHash;
  15521. IHash * rightHash;
  15522. unsigned size;
  15523. };
  15524. class DedupLookupTable : public LookupTable
  15525. {
  15526. public:
  15527. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15528. : LookupTable(helper)
  15529. {
  15530. size = (4*rightRows.length())/3 + 1;
  15531. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  15532. ForEachItemIn(idx, rightRows)
  15533. add(rightRows.item(idx));
  15534. }
  15535. ~DedupLookupTable()
  15536. {
  15537. unsigned i;
  15538. for(i=0; i<size; i++)
  15539. ReleaseRoxieRow(table[i]);
  15540. free(table);
  15541. }
  15542. virtual const void *find(const void * left) const
  15543. {
  15544. unsigned index = leftHash->hash(left) % size;
  15545. unsigned start = index;
  15546. while (table[index])
  15547. {
  15548. if(leftRightCompare->docompare(left, table[index]) == 0)
  15549. return table[index];
  15550. index++;
  15551. if (index==size)
  15552. index = 0;
  15553. if (index==start)
  15554. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15555. }
  15556. return NULL;
  15557. }
  15558. virtual const void *findNext(const void * left) const
  15559. {
  15560. return NULL;
  15561. }
  15562. protected:
  15563. void add(const void * right)
  15564. {
  15565. unsigned index = rightHash->hash(right) % size;
  15566. unsigned start = index;
  15567. while (table[index])
  15568. {
  15569. if (rightCompare->docompare(table[index], right) == 0)
  15570. {
  15571. ReleaseRoxieRow(right);
  15572. return;
  15573. }
  15574. index++;
  15575. if (index==size)
  15576. index = 0;
  15577. if (index==start)
  15578. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  15579. }
  15580. table[index] = right;
  15581. }
  15582. const void * * table;
  15583. };
  15584. class FewLookupTable : public LookupTable
  15585. {
  15586. public:
  15587. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15588. : LookupTable(helper)
  15589. {
  15590. size = (4*rightRows.length())/3 + 1;
  15591. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  15592. findex = fstart = BadIndex;
  15593. ForEachItemIn(idx, rightRows)
  15594. add(rightRows.item(idx));
  15595. }
  15596. ~FewLookupTable()
  15597. {
  15598. unsigned i;
  15599. for(i=0; i<size; i++)
  15600. ReleaseRoxieRow(table[i]);
  15601. free(table);
  15602. }
  15603. virtual const void *find(const void * left) const
  15604. {
  15605. fstart = leftHash->hash(left) % size;
  15606. findex = fstart;
  15607. return doFind(left);
  15608. }
  15609. virtual const void *findNext(const void * left) const
  15610. {
  15611. if (findex == BadIndex)
  15612. return NULL;
  15613. advance();
  15614. return doFind(left);
  15615. }
  15616. protected:
  15617. void add(const void * right)
  15618. {
  15619. unsigned start = rightHash->hash(right) % size;
  15620. unsigned index = start;
  15621. while (table[index])
  15622. {
  15623. index++;
  15624. if (index==size)
  15625. index = 0;
  15626. if (index==start)
  15627. throwUnexpected(); //table is full, should never happen
  15628. }
  15629. table[index] = right;
  15630. }
  15631. void advance() const
  15632. {
  15633. findex++;
  15634. if(findex==size)
  15635. findex = 0;
  15636. if(findex==fstart)
  15637. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15638. }
  15639. const void *doFind(const void * left) const
  15640. {
  15641. while(table[findex])
  15642. {
  15643. if (leftRightCompare->docompare(left, table[findex]) == 0)
  15644. return table[findex];
  15645. advance();
  15646. }
  15647. findex = BadIndex;
  15648. return NULL;
  15649. }
  15650. const void * * table;
  15651. unsigned mutable fstart;
  15652. unsigned mutable findex;
  15653. static unsigned const BadIndex;
  15654. };
  15655. class ManyLookupTable : public LookupTable
  15656. {
  15657. public:
  15658. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15659. : LookupTable(helper)
  15660. {
  15661. rightRows.swapWith(rowtable);
  15662. UInt64Array groups;
  15663. unsigned numRows = rowtable.length();
  15664. if (numRows)
  15665. {
  15666. unsigned groupStart = 0;
  15667. const void *groupStartRow = rowtable.item(0);
  15668. for (unsigned i=1; i < numRows; i++)
  15669. {
  15670. const void *thisRow = rowtable.item(i);
  15671. if (rightCompare->docompare(groupStartRow, thisRow))
  15672. {
  15673. groups.append(makeint64(groupStart, i-groupStart));
  15674. groupStart = i;
  15675. groupStartRow = thisRow;
  15676. }
  15677. }
  15678. groups.append(makeint64(groupStart, numRows-groupStart));
  15679. }
  15680. size = (4*groups.length())/3 + 1;
  15681. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  15682. ForEachItemIn(idx, groups)
  15683. {
  15684. unsigned __int64 group = groups.item(idx);
  15685. unsigned groupstart = high(group);
  15686. const void *row = rowtable.item(groupstart);
  15687. add(row, group);
  15688. }
  15689. }
  15690. ~ManyLookupTable()
  15691. {
  15692. ForEachItemIn(idx, rowtable)
  15693. {
  15694. ReleaseRoxieRow(rowtable.item(idx));
  15695. }
  15696. free(table);
  15697. }
  15698. void add(const void *row, unsigned __int64 group)
  15699. {
  15700. unsigned start = rightHash->hash(row) % size;
  15701. unsigned index = start;
  15702. while (table[index])
  15703. {
  15704. index++;
  15705. if (index==size)
  15706. index = 0;
  15707. if (index==start)
  15708. throwUnexpected(); //table is full, should never happen
  15709. }
  15710. table[index] = group;
  15711. }
  15712. virtual const void *find(const void * left) const
  15713. {
  15714. unsigned index = leftHash->hash(left) % size;
  15715. unsigned start = index;
  15716. while (table[index])
  15717. {
  15718. __uint64 group = table[index];
  15719. currentMatch = high(group);
  15720. const void *right = rowtable.item(currentMatch);
  15721. if (leftRightCompare->docompare(left, right) == 0)
  15722. {
  15723. currentMatch++;
  15724. matchCount = low(group) - 1;
  15725. return right;
  15726. }
  15727. index++;
  15728. if (index==size)
  15729. index = 0;
  15730. if (index==start)
  15731. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15732. }
  15733. matchCount = 0;
  15734. return NULL;
  15735. }
  15736. virtual const void *findNext(const void * left) const
  15737. {
  15738. if (!matchCount)
  15739. return NULL;
  15740. matchCount--;
  15741. return rowtable.item(currentMatch++);
  15742. }
  15743. protected:
  15744. __uint64 *table;
  15745. ConstPointerArray rowtable;
  15746. mutable unsigned currentMatch;
  15747. mutable unsigned matchCount;
  15748. };
  15749. IHThorHashJoinArg &helper;
  15750. bool leftOuterJoin;
  15751. bool exclude;
  15752. bool eog;
  15753. bool many;
  15754. bool dedupRHS;
  15755. bool useFewTable;
  15756. bool matchedGroup;
  15757. const void *left;
  15758. OwnedConstRoxieRow defaultRight;
  15759. Owned<LookupTable> table;
  15760. unsigned keepLimit;
  15761. unsigned atmostLimit;
  15762. unsigned atmostsTriggered;
  15763. unsigned limitLimit;
  15764. unsigned joinCounter;
  15765. bool limitFail;
  15766. bool limitOnFail;
  15767. bool hasGroupLimit;
  15768. bool isSmartJoin;
  15769. unsigned keepCount;
  15770. bool gotMatch;
  15771. bool cloneLeft;
  15772. ConstPointerArray rightGroup;
  15773. aindex_t rightGroupIndex;
  15774. Owned<IException> failingLimit;
  15775. ConstPointerArray filteredRight;
  15776. ThorActivityKind activityKind;
  15777. Owned<IEngineRowAllocator> defaultRightAllocator;
  15778. void createDefaultRight()
  15779. {
  15780. if (!defaultRight)
  15781. {
  15782. if (!defaultRightAllocator)
  15783. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15784. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15785. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15786. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15787. }
  15788. }
  15789. public:
  15790. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  15791. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  15792. {
  15793. unsigned joinFlags = helper.getJoinFlags();
  15794. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15795. assertex((joinFlags & JFrightouter) == 0);
  15796. exclude = (joinFlags & JFexclude) != 0;
  15797. many = (joinFlags & JFmanylookup) != 0;
  15798. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15799. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15800. left = NULL;
  15801. activityKind = factory->getKind();
  15802. eog = false;
  15803. matchedGroup = false;
  15804. gotMatch = false;
  15805. keepLimit = 0;
  15806. keepCount = 0;
  15807. joinCounter = 0;
  15808. atmostLimit = 0;
  15809. atmostsTriggered = 0;
  15810. limitLimit = 0;
  15811. rightGroupIndex = 0;
  15812. hasGroupLimit = false;
  15813. isSmartJoin = (joinFlags & JFsmart) != 0;
  15814. getLimitType(joinFlags, limitFail, limitOnFail);
  15815. }
  15816. void loadRight()
  15817. {
  15818. ConstPointerArray rightset;
  15819. try
  15820. {
  15821. const void * next;
  15822. while(true)
  15823. {
  15824. next = input1->nextInGroup();
  15825. if(!next)
  15826. next = input1->nextInGroup();
  15827. if(!next)
  15828. break;
  15829. rightset.append(next);
  15830. }
  15831. if (!dedupRHS)
  15832. {
  15833. if (useFewTable)
  15834. {
  15835. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15836. }
  15837. else
  15838. {
  15839. if (!helper.isRightAlreadySorted())
  15840. {
  15841. if (helper.getJoinFlags() & JFunstable)
  15842. {
  15843. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  15844. }
  15845. else
  15846. {
  15847. unsigned rightord = rightset.ordinality();
  15848. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  15849. void **temp = (void **) tempAttr.bufferBase();
  15850. void **_rows = const_cast<void * *>(rightset.getArray());
  15851. memcpy(temp, _rows, rightord*sizeof(void **));
  15852. qsortvecstable(temp, rightord, *helper.queryCompareRight(), (void ***)_rows);
  15853. for (unsigned i = 0; i < rightord; i++)
  15854. {
  15855. *_rows = **((void ***)_rows);
  15856. _rows++;
  15857. }
  15858. }
  15859. }
  15860. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15861. }
  15862. }
  15863. else
  15864. {
  15865. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15866. }
  15867. }
  15868. catch (...)
  15869. {
  15870. ForEachItemIn(idx, rightset)
  15871. ReleaseRoxieRow(rightset.item(idx));
  15872. throw;
  15873. }
  15874. };
  15875. virtual void reset()
  15876. {
  15877. if (atmostsTriggered)
  15878. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15879. CRoxieServerTwoInputActivity::reset();
  15880. ReleaseClearRoxieRow(left);
  15881. defaultRight.clear();
  15882. table.clear();
  15883. }
  15884. virtual bool needsAllocator() const { return true; }
  15885. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15886. {
  15887. eog = false;
  15888. matchedGroup = false;
  15889. left = NULL;
  15890. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15891. keepLimit = helper.getKeepLimit();
  15892. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15893. atmostsTriggered = 0;
  15894. atmostLimit = helper.getJoinLimit();
  15895. limitLimit = helper.getMatchAbortLimit();
  15896. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15897. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15898. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15899. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15900. switch (activityKind)
  15901. {
  15902. case TAKlookupjoin:
  15903. case TAKlookupdenormalizegroup:
  15904. case TAKsmartjoin:
  15905. case TAKsmartdenormalizegroup:
  15906. if (leftOuterJoin)
  15907. createDefaultRight();
  15908. break;
  15909. }
  15910. if (limitOnFail)
  15911. createDefaultRight();
  15912. }
  15913. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15914. {
  15915. if (idx==1)
  15916. input1 = _in;
  15917. else
  15918. {
  15919. if ((helper.getJoinFlags() & JFparallel) != 0)
  15920. {
  15921. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15922. puller->setInput(0, _in);
  15923. _in = puller;
  15924. }
  15925. CRoxieServerActivity::setInput(idx, _in);
  15926. }
  15927. }
  15928. virtual const void * nextInGroup()
  15929. {
  15930. ActivityTimer t(totalCycles, timeActivities);
  15931. if(!table)
  15932. loadRight();
  15933. switch (activityKind)
  15934. {
  15935. case TAKlookupjoin:
  15936. case TAKsmartjoin:
  15937. return nextInGroupJoin();
  15938. case TAKlookupdenormalize:
  15939. case TAKlookupdenormalizegroup:
  15940. case TAKsmartdenormalize:
  15941. case TAKsmartdenormalizegroup:
  15942. return nextInGroupDenormalize();
  15943. }
  15944. throwUnexpected();
  15945. }
  15946. private:
  15947. const void * nextInGroupJoin()
  15948. {
  15949. if(!table)
  15950. loadRight();
  15951. while(true)
  15952. {
  15953. const void * right = NULL;
  15954. if(!left)
  15955. {
  15956. left = input->nextInGroup();
  15957. keepCount = keepLimit;
  15958. joinCounter = 0;
  15959. if(!left)
  15960. {
  15961. if (isSmartJoin)
  15962. left = input->nextInGroup();
  15963. if (!left)
  15964. {
  15965. if(matchedGroup || eog)
  15966. {
  15967. matchedGroup = false;
  15968. eog = true;
  15969. return NULL;
  15970. }
  15971. eog = true;
  15972. continue;
  15973. }
  15974. }
  15975. eog = false;
  15976. gotMatch = false;
  15977. right = getRightFirst();
  15978. }
  15979. else
  15980. right = getRightNext();
  15981. const void * ret = NULL;
  15982. if(failingLimit)
  15983. {
  15984. ret = joinException(left, failingLimit);
  15985. }
  15986. else
  15987. {
  15988. while(right)
  15989. {
  15990. if(helper.match(left, right))
  15991. {
  15992. gotMatch = true;
  15993. if(exclude)
  15994. break;
  15995. ret = joinRecords(left, right, ++joinCounter);
  15996. if(ret)
  15997. break;
  15998. }
  15999. right = getRightNext();
  16000. ret = NULL;
  16001. }
  16002. if(leftOuterJoin && !gotMatch)
  16003. {
  16004. ret = joinRecords(left, defaultRight, 0);
  16005. gotMatch = true;
  16006. }
  16007. }
  16008. if(ret)
  16009. {
  16010. matchedGroup = true;
  16011. processed++;
  16012. if(!many || (--keepCount == 0) || failingLimit)
  16013. {
  16014. ReleaseClearRoxieRow(left);
  16015. failingLimit.clear();
  16016. }
  16017. return ret;
  16018. }
  16019. ReleaseClearRoxieRow(left);
  16020. }
  16021. }
  16022. const void * nextInGroupDenormalize()
  16023. {
  16024. while(true)
  16025. {
  16026. left = input->nextInGroup();
  16027. if(!left)
  16028. {
  16029. if (!matchedGroup || isSmartJoin)
  16030. left = input->nextInGroup();
  16031. if (!left)
  16032. {
  16033. matchedGroup = false;
  16034. return NULL;
  16035. }
  16036. }
  16037. gotMatch = false;
  16038. const void * right = getRightFirst();
  16039. const void * ret = NULL;
  16040. if (failingLimit)
  16041. ret = joinException(left, failingLimit);
  16042. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16043. {
  16044. OwnedConstRoxieRow newLeft;
  16045. newLeft.set(left);
  16046. unsigned rowSize = 0;
  16047. unsigned leftCount = 0;
  16048. keepCount = keepLimit;
  16049. while (right)
  16050. {
  16051. try
  16052. {
  16053. if (helper.match(left, right))
  16054. {
  16055. gotMatch = true;
  16056. if (exclude)
  16057. break;
  16058. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16059. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16060. if (thisSize)
  16061. {
  16062. rowSize = thisSize;
  16063. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16064. }
  16065. if(!many || (--keepCount == 0))
  16066. break;
  16067. }
  16068. right = getRightNext();
  16069. }
  16070. catch (IException *E)
  16071. {
  16072. throw makeWrappedException(E);
  16073. }
  16074. }
  16075. if (rowSize)
  16076. ret = newLeft.getClear();
  16077. else if (leftOuterJoin && !gotMatch)
  16078. {
  16079. ret = left;
  16080. left = NULL;
  16081. }
  16082. }
  16083. else
  16084. {
  16085. filteredRight.kill();
  16086. keepCount = keepLimit;
  16087. while (right)
  16088. {
  16089. if (helper.match(left, right))
  16090. {
  16091. gotMatch = true;
  16092. if(exclude)
  16093. break;
  16094. filteredRight.append(right);
  16095. if(!many || (--keepCount == 0))
  16096. break;
  16097. }
  16098. right = getRightNext();
  16099. }
  16100. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16101. ret = denormalizeRecords(left, filteredRight);
  16102. filteredRight.kill();
  16103. }
  16104. ReleaseRoxieRow(left);
  16105. left = NULL;
  16106. failingLimit.clear();
  16107. if(ret)
  16108. {
  16109. matchedGroup = true;
  16110. processed++;
  16111. return ret;
  16112. }
  16113. }
  16114. }
  16115. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16116. {
  16117. if (cloneLeft)
  16118. {
  16119. LinkRoxieRow(left);
  16120. return left;
  16121. }
  16122. try
  16123. {
  16124. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16125. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16126. if (outSize)
  16127. return rowBuilder.finalizeRowClear(outSize);
  16128. else
  16129. return NULL;
  16130. }
  16131. catch (IException *E)
  16132. {
  16133. throw makeWrappedException(E);
  16134. }
  16135. }
  16136. const void * joinException(const void * left, IException * except)
  16137. {
  16138. try
  16139. {
  16140. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16141. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16142. if (outSize)
  16143. return rowBuilder.finalizeRowClear(outSize);
  16144. else
  16145. return NULL;
  16146. }
  16147. catch (IException *E)
  16148. {
  16149. throw makeWrappedException(E);
  16150. }
  16151. }
  16152. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16153. {
  16154. try
  16155. {
  16156. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16157. unsigned numRows = rows.ordinality();
  16158. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16159. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16160. if (outSize)
  16161. return rowBuilder.finalizeRowClear(outSize);
  16162. else
  16163. return NULL;
  16164. }
  16165. catch (IException *E)
  16166. {
  16167. throw makeWrappedException(E);
  16168. }
  16169. }
  16170. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16171. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16172. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16173. const void *fillRightGroup()
  16174. {
  16175. rightGroup.kill();
  16176. for(const void * right = table->find(left); right; right = table->findNext(left))
  16177. {
  16178. rightGroup.append(right);
  16179. if(rightGroup.ordinality() > limitLimit)
  16180. {
  16181. if(limitFail)
  16182. failLimit();
  16183. gotMatch = true;
  16184. if (ctx->queryDebugContext())
  16185. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16186. if(limitOnFail)
  16187. {
  16188. assertex(!failingLimit);
  16189. try
  16190. {
  16191. failLimit();
  16192. }
  16193. catch(IException * e)
  16194. {
  16195. failingLimit.setown(e);
  16196. }
  16197. assertex(failingLimit != NULL);
  16198. }
  16199. else
  16200. {
  16201. rightGroup.kill();
  16202. }
  16203. break;
  16204. }
  16205. if(rightGroup.ordinality() > atmostLimit)
  16206. {
  16207. atmostsTriggered++;
  16208. rightGroup.kill();
  16209. break;
  16210. }
  16211. }
  16212. rightGroupIndex = 0;
  16213. return readRightGroup();
  16214. }
  16215. void failLimit()
  16216. {
  16217. helper.onMatchAbortLimitExceeded();
  16218. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16219. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16220. {
  16221. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16222. }
  16223. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16224. }
  16225. };
  16226. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16227. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16228. {
  16229. public:
  16230. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16231. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16232. {
  16233. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16234. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16235. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16236. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16237. }
  16238. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16239. {
  16240. return new CRoxieServerLookupJoinActivity(this, _probeManager, useFewTable);
  16241. }
  16242. virtual const StatisticsMapping &queryStatsMapping() const
  16243. {
  16244. return joinStatistics;
  16245. }
  16246. protected:
  16247. bool useFewTable;
  16248. };
  16249. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16250. {
  16251. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16252. }
  16253. //=====================================================================================================
  16254. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16255. {
  16256. private:
  16257. IHThorAllJoinArg &helper;
  16258. bool leftOuterJoin;
  16259. bool rightOuterJoin;
  16260. bool exclude;
  16261. OwnedConstRoxieRow defaultRight;
  16262. OwnedConstRoxieRow defaultLeft;
  16263. Owned<IEngineRowAllocator> defaultRightAllocator;
  16264. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16265. const void *left;
  16266. unsigned countForLeft;
  16267. ConstPointerArray rightset;
  16268. BoolArray matchedRight; // MORE - could use a bitset...
  16269. unsigned keepLimit;
  16270. bool started;
  16271. bool eog;
  16272. bool eos;
  16273. bool matchedLeft;
  16274. bool matchedGroup;
  16275. bool leftIsGrouped;
  16276. bool cloneLeft;
  16277. unsigned rightIndex;
  16278. unsigned joinCounter;
  16279. unsigned rightOrdinality;
  16280. ThorActivityKind activityKind;
  16281. ConstPointerArray filteredRight;
  16282. void createDefaultLeft()
  16283. {
  16284. if (!defaultLeft)
  16285. {
  16286. if (!defaultLeftAllocator)
  16287. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  16288. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16289. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16290. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16291. }
  16292. }
  16293. void createDefaultRight()
  16294. {
  16295. if (!defaultRight)
  16296. {
  16297. if (!defaultRightAllocator)
  16298. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  16299. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16300. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16301. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16302. }
  16303. }
  16304. public:
  16305. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16306. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16307. {
  16308. unsigned joinFlags = helper.getJoinFlags();
  16309. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16310. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16311. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16312. keepLimit = (unsigned) -1;
  16313. exclude = (joinFlags & JFexclude) != 0;
  16314. left = NULL;
  16315. started = true;
  16316. eog = false;
  16317. eos = false;
  16318. matchedLeft = false;
  16319. matchedGroup = false;
  16320. activityKind = factory->getKind();
  16321. rightIndex = 0;
  16322. rightOrdinality = 0;
  16323. leftIsGrouped = false;
  16324. countForLeft = 0;
  16325. joinCounter = 0;
  16326. }
  16327. virtual void reset()
  16328. {
  16329. defaultRight.clear();
  16330. defaultLeft.clear();
  16331. ReleaseRoxieRowSet(rightset);
  16332. matchedRight.kill();
  16333. CRoxieServerTwoInputActivity::reset();
  16334. }
  16335. virtual bool needsAllocator() const { return true; }
  16336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16337. {
  16338. eog = false;
  16339. eos = false;
  16340. matchedLeft = false;
  16341. matchedGroup = false;
  16342. started = false;
  16343. left = NULL;
  16344. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16345. keepLimit = helper.getKeepLimit();
  16346. if(keepLimit==0)
  16347. keepLimit = (unsigned) -1;
  16348. countForLeft = keepLimit;
  16349. joinCounter = 0;
  16350. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16351. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16352. createDefaultRight();
  16353. if(rightOuterJoin)
  16354. createDefaultLeft();
  16355. }
  16356. void loadRight()
  16357. {
  16358. const void * next;
  16359. while(true)
  16360. {
  16361. next = input1->nextInGroup();
  16362. if(!next)
  16363. next = input1->nextInGroup();
  16364. if(!next)
  16365. break;
  16366. rightset.append(next);
  16367. matchedRight.append(false);
  16368. }
  16369. rightIndex = 0;
  16370. joinCounter = 0;
  16371. rightOrdinality = rightset.ordinality();
  16372. }
  16373. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16374. {
  16375. if (idx==1)
  16376. input1 = _in;
  16377. else
  16378. {
  16379. if ((helper.getJoinFlags() & JFparallel) != 0)
  16380. {
  16381. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  16382. puller->setInput(0, _in);
  16383. _in = puller;
  16384. }
  16385. CRoxieServerActivity::setInput(idx, _in);
  16386. }
  16387. }
  16388. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16389. {
  16390. // MORE - could share some code with lookup join
  16391. if (cloneLeft)
  16392. {
  16393. LinkRoxieRow(left);
  16394. return left;
  16395. }
  16396. try
  16397. {
  16398. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16399. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16400. if (outSize)
  16401. return rowBuilder.finalizeRowClear(outSize);
  16402. else
  16403. return NULL;
  16404. }
  16405. catch (IException *E)
  16406. {
  16407. throw makeWrappedException(E);
  16408. }
  16409. }
  16410. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  16411. {
  16412. try
  16413. {
  16414. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16415. unsigned numRows = rows.ordinality();
  16416. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16417. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  16418. if (outSize)
  16419. return rowBuilder.finalizeRowClear(outSize);
  16420. else
  16421. return NULL;
  16422. }
  16423. catch (IException *E)
  16424. {
  16425. throw makeWrappedException(E);
  16426. }
  16427. }
  16428. virtual const void *nextInGroup()
  16429. {
  16430. ActivityTimer t(totalCycles, timeActivities);
  16431. if(!started)
  16432. {
  16433. started = true;
  16434. left = input->nextInGroup();
  16435. matchedLeft = false;
  16436. countForLeft = keepLimit;
  16437. joinCounter = 0;
  16438. if(left == NULL)
  16439. {
  16440. eos = true;
  16441. return NULL;
  16442. }
  16443. loadRight();
  16444. }
  16445. const void * ret;
  16446. const void * right;
  16447. if(eos)
  16448. return NULL;
  16449. while(true)
  16450. {
  16451. ret = NULL;
  16452. if((rightIndex == rightOrdinality) || (countForLeft==0))
  16453. {
  16454. if(leftOuterJoin && left && !matchedLeft)
  16455. {
  16456. switch(activityKind)
  16457. {
  16458. case TAKalljoin:
  16459. ret = joinRecords(left, defaultRight, 0);
  16460. break;
  16461. case TAKalldenormalize:
  16462. ret = left;
  16463. left = NULL;
  16464. break;
  16465. case TAKalldenormalizegroup:
  16466. filteredRight.kill();
  16467. ret = denormalizeRecords(left, filteredRight);
  16468. break;
  16469. default:
  16470. throwUnexpected();
  16471. }
  16472. }
  16473. rightIndex = 0;
  16474. joinCounter = 0;
  16475. ReleaseRoxieRow(left);
  16476. left = NULL;
  16477. if(ret)
  16478. {
  16479. matchedGroup = true;
  16480. processed++;
  16481. return ret;
  16482. }
  16483. }
  16484. if(!left)
  16485. {
  16486. left = input->nextInGroup();
  16487. matchedLeft = false;
  16488. countForLeft = keepLimit;
  16489. joinCounter = 0;
  16490. }
  16491. if(!left)
  16492. {
  16493. if(eog)
  16494. {
  16495. eos = true;
  16496. matchedGroup = false;
  16497. return NULL;
  16498. }
  16499. eog = true;
  16500. if (matchedGroup && leftIsGrouped)
  16501. {
  16502. matchedGroup = false;
  16503. return NULL;
  16504. }
  16505. matchedGroup = false;
  16506. continue;
  16507. }
  16508. eog = false;
  16509. switch(activityKind)
  16510. {
  16511. case TAKalljoin:
  16512. while(rightIndex < rightOrdinality)
  16513. {
  16514. right = rightset.item(rightIndex);
  16515. if(helper.match(left, right))
  16516. {
  16517. matchedLeft = true;
  16518. matchedRight.replace(true, rightIndex);
  16519. if(!exclude)
  16520. ret = joinRecords(left, right, ++joinCounter);
  16521. }
  16522. rightIndex++;
  16523. if(ret)
  16524. {
  16525. countForLeft--;
  16526. matchedGroup = true;
  16527. processed++;
  16528. return ret;
  16529. }
  16530. }
  16531. break;
  16532. case TAKalldenormalize:
  16533. {
  16534. OwnedConstRoxieRow newLeft;
  16535. newLeft.set(left);
  16536. unsigned rowSize = 0;
  16537. unsigned leftCount = 0;
  16538. while((rightIndex < rightOrdinality) && countForLeft)
  16539. {
  16540. right = rightset.item(rightIndex);
  16541. if(helper.match(left, right))
  16542. {
  16543. matchedLeft = true;
  16544. matchedRight.replace(true, rightIndex);
  16545. if(!exclude)
  16546. {
  16547. try
  16548. {
  16549. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16550. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16551. if(thisSize)
  16552. {
  16553. rowSize = thisSize;
  16554. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16555. --countForLeft;
  16556. }
  16557. }
  16558. catch (IException *e)
  16559. {
  16560. throw makeWrappedException(e);
  16561. }
  16562. }
  16563. }
  16564. rightIndex++;
  16565. }
  16566. if(rowSize)
  16567. {
  16568. processed++;
  16569. return newLeft.getClear();
  16570. }
  16571. }
  16572. break;
  16573. case TAKalldenormalizegroup:
  16574. filteredRight.kill();
  16575. while((rightIndex < rightOrdinality) && countForLeft)
  16576. {
  16577. right = rightset.item(rightIndex);
  16578. if(helper.match(left, right))
  16579. {
  16580. matchedLeft = true;
  16581. matchedRight.replace(true, rightIndex);
  16582. filteredRight.append(right);
  16583. --countForLeft;
  16584. }
  16585. ++rightIndex;
  16586. }
  16587. if(!exclude && filteredRight.ordinality())
  16588. {
  16589. ret = denormalizeRecords(left, filteredRight);
  16590. filteredRight.kill();
  16591. if(ret)
  16592. {
  16593. processed++;
  16594. return ret;
  16595. }
  16596. }
  16597. break;
  16598. default:
  16599. throwUnexpected();
  16600. }
  16601. }
  16602. }
  16603. };
  16604. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16605. {
  16606. public:
  16607. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16608. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16609. {
  16610. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16611. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16612. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16613. }
  16614. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16615. {
  16616. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16617. }
  16618. virtual const StatisticsMapping &queryStatsMapping() const
  16619. {
  16620. return joinStatistics;
  16621. }
  16622. };
  16623. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16624. {
  16625. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16626. }
  16627. //=====================================================================================================
  16628. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16629. {
  16630. unsigned limit;
  16631. bool hasBest;
  16632. bool eoi;
  16633. const void **sorted;
  16634. unsigned sortedCount;
  16635. unsigned curIndex;
  16636. IHThorTopNArg &helper;
  16637. ICompare &compare;
  16638. public:
  16639. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16640. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16641. {
  16642. sorted = NULL;
  16643. sortedCount = 0;
  16644. curIndex = 0;
  16645. limit = 0;
  16646. eoi = false;
  16647. hasBest = false;
  16648. }
  16649. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16650. {
  16651. assertex(sorted == NULL);
  16652. sortedCount = 0;
  16653. curIndex = 0;
  16654. eoi = false;
  16655. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16656. limit = (unsigned) helper.getLimit();
  16657. hasBest = helper.hasBest();
  16658. lateStart(parentExtractSize, parentExtract, limit > 0);
  16659. // MORE - should we use an expanding array instead?
  16660. if (limit > 0)
  16661. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16662. }
  16663. virtual void reset()
  16664. {
  16665. if (sorted)
  16666. {
  16667. while(curIndex < sortedCount)
  16668. ReleaseRoxieRow(sorted[curIndex++]);
  16669. ReleaseRoxieRow(sorted);
  16670. }
  16671. sorted = NULL;
  16672. CRoxieServerLateStartActivity::reset();
  16673. }
  16674. bool abortEarly()
  16675. {
  16676. if (hasBest && (sortedCount == limit))
  16677. {
  16678. int compare = helper.compareBest(sorted[sortedCount-1]);
  16679. if (compare == 0)
  16680. {
  16681. if (meta.isGrouped())
  16682. {
  16683. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16684. const void * next;
  16685. while ((next = input->nextInGroup()) != NULL)
  16686. ReleaseRoxieRow(next);
  16687. }
  16688. else
  16689. eoi = true;
  16690. return true;
  16691. }
  16692. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16693. if (compare < 0)
  16694. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16695. }
  16696. return false;
  16697. }
  16698. void getSorted()
  16699. {
  16700. curIndex = 0;
  16701. sortedCount = 0;
  16702. if(eoi)
  16703. return;
  16704. const void * next;
  16705. while ((next = input->nextInGroup()) != NULL)
  16706. {
  16707. if (sortedCount < limit)
  16708. {
  16709. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16710. sortedCount++;
  16711. if(abortEarly())
  16712. return;
  16713. }
  16714. else
  16715. {
  16716. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16717. {
  16718. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16719. ReleaseRoxieRow(sorted[sortedCount]);
  16720. if(abortEarly())
  16721. return;
  16722. }
  16723. else
  16724. {
  16725. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16726. }
  16727. }
  16728. }
  16729. }
  16730. virtual const void * nextInGroup()
  16731. {
  16732. ActivityTimer t(totalCycles, timeActivities);
  16733. if (eof)
  16734. return NULL;
  16735. if (curIndex >= sortedCount)
  16736. {
  16737. bool eog = sortedCount != 0;
  16738. getSorted();
  16739. if(sortedCount == 0)
  16740. {
  16741. eof = true;
  16742. return NULL;
  16743. }
  16744. if (eog)
  16745. return NULL;
  16746. }
  16747. processed++;
  16748. return sorted[curIndex++];
  16749. }
  16750. };
  16751. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16752. {
  16753. public:
  16754. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16755. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16756. {
  16757. }
  16758. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16759. {
  16760. return new CRoxieServerTopNActivity(this, _probeManager);
  16761. }
  16762. };
  16763. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16764. {
  16765. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16766. }
  16767. //=================================================================================
  16768. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16769. {
  16770. protected:
  16771. unsigned __int64 rowLimit;
  16772. IHThorLimitArg &helper;
  16773. public:
  16774. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16775. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16776. {
  16777. rowLimit = 0;
  16778. }
  16779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16780. {
  16781. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16782. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16783. }
  16784. virtual const void *nextInGroup()
  16785. {
  16786. ActivityTimer t(totalCycles, timeActivities);
  16787. const void * ret = input->nextInGroup();
  16788. if (ret)
  16789. {
  16790. processed++;
  16791. if (processed > rowLimit)
  16792. {
  16793. ReleaseRoxieRow(ret);
  16794. if (traceLevel > 4)
  16795. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16796. helper.onLimitExceeded();
  16797. }
  16798. }
  16799. return ret;
  16800. }
  16801. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16802. {
  16803. ActivityTimer t(totalCycles, timeActivities);
  16804. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16805. if (ret)
  16806. {
  16807. if (wasCompleteMatch)
  16808. processed++;
  16809. if (processed > rowLimit)
  16810. {
  16811. ReleaseRoxieRow(ret);
  16812. if (traceLevel > 4)
  16813. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16814. helper.onLimitExceeded();
  16815. }
  16816. }
  16817. return ret;
  16818. }
  16819. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16820. {
  16821. return input->gatherConjunctions(collector);
  16822. }
  16823. virtual void resetEOF()
  16824. {
  16825. //Do not reset the rowLimit
  16826. input->resetEOF();
  16827. }
  16828. IInputSteppingMeta * querySteppingMeta()
  16829. {
  16830. return input->querySteppingMeta();
  16831. }
  16832. };
  16833. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16834. {
  16835. public:
  16836. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16837. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16838. {
  16839. }
  16840. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16841. {
  16842. return new CRoxieServerLimitActivity(this, _probeManager);
  16843. }
  16844. };
  16845. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16846. {
  16847. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16848. }
  16849. //=====================================================================================================
  16850. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16851. {
  16852. ConstPointerArray buff;
  16853. bool started;
  16854. unsigned index;
  16855. IHThorLimitTransformExtra * transformExtra;
  16856. public:
  16857. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16858. : CRoxieServerLimitActivity(_factory, _probeManager)
  16859. {
  16860. transformExtra = NULL;
  16861. started = false;
  16862. index = 0;
  16863. if (_onFail)
  16864. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16865. }
  16866. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16867. {
  16868. started = false;
  16869. index = 0;
  16870. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16871. }
  16872. virtual void reset()
  16873. {
  16874. while (buff.isItem(index))
  16875. ReleaseRoxieRow(buff.item(index++));
  16876. buff.kill();
  16877. started = false;
  16878. CRoxieServerLimitActivity::reset();
  16879. }
  16880. virtual const void *nextInGroup()
  16881. {
  16882. ActivityTimer t(totalCycles, timeActivities);
  16883. if (!started)
  16884. pullInput();
  16885. if (buff.isItem(index))
  16886. {
  16887. const void * next = buff.item(index++);
  16888. if(next)
  16889. processed++;
  16890. return next;
  16891. }
  16892. return NULL;
  16893. }
  16894. protected:
  16895. void pullInput()
  16896. {
  16897. unsigned count = 0;
  16898. loop
  16899. {
  16900. const void * next = input->nextInGroup();
  16901. if (next == NULL)
  16902. {
  16903. next = input->nextInGroup();
  16904. if(next == NULL)
  16905. break;
  16906. buff.append(NULL);
  16907. }
  16908. count++;
  16909. if (count > rowLimit)
  16910. {
  16911. ReleaseRoxieRow(next);
  16912. ReleaseRoxieRowSet(buff);
  16913. if (ctx->queryDebugContext())
  16914. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16915. if (transformExtra)
  16916. {
  16917. createRowAllocator();
  16918. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16919. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16920. if (outSize)
  16921. buff.append(rowBuilder.finalizeRowClear(outSize));
  16922. }
  16923. break;
  16924. }
  16925. buff.append(next);
  16926. }
  16927. started = true;
  16928. }
  16929. };
  16930. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16931. {
  16932. public:
  16933. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16934. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16935. {
  16936. }
  16937. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16938. {
  16939. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16940. }
  16941. };
  16942. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16943. {
  16944. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16945. }
  16946. //=================================================================================
  16947. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16948. {
  16949. IHThorCatchArg &helper;
  16950. public:
  16951. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16952. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16953. {
  16954. }
  16955. virtual const void *nextInGroup()
  16956. {
  16957. ActivityTimer t(totalCycles, timeActivities);
  16958. try
  16959. {
  16960. const void *ret = input->nextInGroup();
  16961. if (ret)
  16962. processed++;
  16963. return ret;
  16964. }
  16965. catch (IException *E)
  16966. {
  16967. E->Release();
  16968. helper.onExceptionCaught();
  16969. }
  16970. catch (...)
  16971. {
  16972. helper.onExceptionCaught();
  16973. }
  16974. throwUnexpected(); // onExceptionCaught should have thrown something
  16975. }
  16976. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16977. {
  16978. try
  16979. {
  16980. ActivityTimer t(totalCycles, timeActivities);
  16981. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16982. if (ret && wasCompleteMatch)
  16983. processed++;
  16984. return ret;
  16985. }
  16986. catch (IException *E)
  16987. {
  16988. E->Release();
  16989. helper.onExceptionCaught();
  16990. }
  16991. catch (...)
  16992. {
  16993. helper.onExceptionCaught();
  16994. }
  16995. throwUnexpected(); // onExceptionCaught should have thrown something
  16996. }
  16997. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16998. {
  16999. return input->gatherConjunctions(collector);
  17000. }
  17001. virtual void resetEOF()
  17002. {
  17003. input->resetEOF(); // MORE - why not in base class?
  17004. }
  17005. IInputSteppingMeta * querySteppingMeta()
  17006. {
  17007. return input->querySteppingMeta();
  17008. }
  17009. };
  17010. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17011. {
  17012. ConstPointerArray buff;
  17013. bool started;
  17014. unsigned index;
  17015. IHThorCatchArg &helper;
  17016. bool createRow;
  17017. public:
  17018. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17019. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17020. {
  17021. started = false;
  17022. index = 0;
  17023. }
  17024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17025. {
  17026. started = false;
  17027. index = 0;
  17028. try
  17029. {
  17030. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17031. }
  17032. catch (IException *E)
  17033. {
  17034. onException(E);
  17035. started = true;
  17036. }
  17037. catch (...)
  17038. {
  17039. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17040. started = true;
  17041. }
  17042. }
  17043. virtual void reset()
  17044. {
  17045. while (buff.isItem(index))
  17046. ReleaseRoxieRow(buff.item(index++));
  17047. buff.kill();
  17048. started = false;
  17049. CRoxieServerActivity::reset();
  17050. }
  17051. virtual const void *nextInGroup()
  17052. {
  17053. ActivityTimer t(totalCycles, timeActivities);
  17054. if (!started)
  17055. pullInput();
  17056. if (buff.isItem(index))
  17057. {
  17058. const void * next = buff.item(index++);
  17059. if(next)
  17060. processed++;
  17061. return next;
  17062. }
  17063. return NULL;
  17064. }
  17065. protected:
  17066. void onException(IException *E)
  17067. {
  17068. input->stop(true);
  17069. ReleaseRoxieRowSet(buff);
  17070. if (createRow)
  17071. {
  17072. createRowAllocator();
  17073. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17074. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17075. if (outSize)
  17076. buff.append(rowBuilder.finalizeRowClear(outSize));
  17077. }
  17078. E->Release();
  17079. }
  17080. void pullInput()
  17081. {
  17082. try
  17083. {
  17084. bool EOGseen = false;
  17085. loop
  17086. {
  17087. const void * next = input->nextInGroup();
  17088. buff.append(next);
  17089. if (next == NULL)
  17090. {
  17091. if (EOGseen)
  17092. break;
  17093. EOGseen = true;
  17094. }
  17095. else
  17096. EOGseen = false;
  17097. }
  17098. }
  17099. catch (IException *E)
  17100. {
  17101. onException(E);
  17102. }
  17103. catch (...)
  17104. {
  17105. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17106. }
  17107. started = true;
  17108. }
  17109. };
  17110. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17111. {
  17112. public:
  17113. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17114. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17115. {
  17116. }
  17117. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17118. {
  17119. switch (kind)
  17120. {
  17121. case TAKcatch:
  17122. return new CRoxieServerCatchActivity(this, _probeManager);
  17123. case TAKskipcatch:
  17124. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  17125. case TAKcreaterowcatch:
  17126. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  17127. default:
  17128. throwUnexpected();
  17129. }
  17130. }
  17131. };
  17132. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17133. {
  17134. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17135. }
  17136. //=================================================================================
  17137. class CRoxieServerCaseActivity : public CRoxieServerActivity
  17138. {
  17139. IHThorCaseArg &helper;
  17140. IRoxieInput **inputs;
  17141. unsigned cond;
  17142. bool unusedStopped;
  17143. IRoxieInput *in;
  17144. unsigned numInputs;
  17145. public:
  17146. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17147. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  17148. {
  17149. unusedStopped = false;
  17150. cond = 0;
  17151. inputs = new IRoxieInput*[numInputs];
  17152. for (unsigned i = 0; i < numInputs; i++)
  17153. inputs[i] = NULL;
  17154. in = NULL;
  17155. }
  17156. ~CRoxieServerCaseActivity()
  17157. {
  17158. delete [] inputs;
  17159. }
  17160. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17161. {
  17162. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17163. cond = helper.getBranch();
  17164. //CHOOSE defaults to the last argument if out of range.
  17165. if (cond >= numInputs)
  17166. cond = numInputs - 1;
  17167. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  17168. for (unsigned idx = 0; idx < numInputs; idx++)
  17169. {
  17170. if (idx!=cond)
  17171. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17172. }
  17173. in = inputs[cond];
  17174. unusedStopped = true;
  17175. }
  17176. virtual void stop(bool aborting)
  17177. {
  17178. for (unsigned idx = 0; idx < numInputs; idx++)
  17179. {
  17180. if (idx==cond || !unusedStopped)
  17181. inputs[idx]->stop(aborting);
  17182. }
  17183. CRoxieServerActivity::stop(aborting);
  17184. }
  17185. virtual void reset()
  17186. {
  17187. for (unsigned idx = 0; idx < numInputs; idx++)
  17188. {
  17189. inputs[idx]->reset();
  17190. }
  17191. unusedStopped = false;
  17192. in = NULL;
  17193. CRoxieServerActivity::reset();
  17194. }
  17195. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17196. {
  17197. assertex(idx < numInputs);
  17198. inputs[idx] = _in;
  17199. }
  17200. virtual const void *nextInGroup()
  17201. {
  17202. ActivityTimer t(totalCycles, timeActivities);
  17203. if (in)
  17204. {
  17205. const void *ret = in->nextInGroup();
  17206. if (ret)
  17207. processed++;
  17208. return ret;
  17209. }
  17210. return NULL;
  17211. }
  17212. };
  17213. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17214. {
  17215. bool graphInvariant;
  17216. public:
  17217. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17218. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17219. {
  17220. graphInvariant = _graphInvariant;
  17221. }
  17222. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17223. {
  17224. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  17225. }
  17226. virtual bool isGraphInvariant() const
  17227. {
  17228. return graphInvariant;
  17229. }
  17230. };
  17231. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17232. {
  17233. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17234. }
  17235. //=================================================================================
  17236. class CRoxieServerIfActivity : public CRoxieServerActivity
  17237. {
  17238. IHThorIfArg &helper;
  17239. IRoxieInput *inputTrue;
  17240. IRoxieInput *inputFalse;
  17241. bool cond;
  17242. bool unusedStopped;
  17243. public:
  17244. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17245. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17246. {
  17247. inputFalse = NULL;
  17248. inputTrue = NULL;
  17249. unusedStopped = false;
  17250. cond = false;
  17251. }
  17252. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17253. {
  17254. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17255. cond = helper.getCondition();
  17256. if (cond)
  17257. {
  17258. inputTrue->start(parentExtractSize, parentExtract, paused);
  17259. if (inputFalse)
  17260. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17261. }
  17262. else
  17263. {
  17264. if (inputFalse)
  17265. inputFalse->start(parentExtractSize, parentExtract, paused);
  17266. inputTrue->stop(false);
  17267. }
  17268. unusedStopped = true;
  17269. }
  17270. virtual void stop(bool aborting)
  17271. {
  17272. if (!unusedStopped || cond)
  17273. inputTrue->stop(aborting);
  17274. if (inputFalse && (!unusedStopped || !cond))
  17275. inputFalse->stop(aborting);
  17276. CRoxieServerActivity::stop(aborting);
  17277. }
  17278. virtual unsigned __int64 queryLocalCycles() const
  17279. {
  17280. __int64 localCycles = totalCycles.totalCycles;
  17281. localCycles -= inputTrue->queryTotalCycles();
  17282. if (inputFalse)
  17283. localCycles -= inputFalse->queryTotalCycles();
  17284. if (localCycles < 0)
  17285. localCycles = 0;
  17286. return localCycles;
  17287. }
  17288. virtual IRoxieInput *queryInput(unsigned idx) const
  17289. {
  17290. switch (idx)
  17291. {
  17292. case 0:
  17293. return inputTrue;
  17294. case 1:
  17295. return inputFalse;
  17296. default:
  17297. return NULL;
  17298. }
  17299. }
  17300. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  17301. {
  17302. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17303. if (in)
  17304. return in->queryIndexReadActivity();
  17305. return NULL;
  17306. }
  17307. virtual void reset()
  17308. {
  17309. CRoxieServerActivity::reset();
  17310. inputTrue->reset();
  17311. if (inputFalse)
  17312. inputFalse->reset();
  17313. unusedStopped = false;
  17314. }
  17315. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17316. {
  17317. if (idx==1)
  17318. inputFalse = _in;
  17319. else
  17320. {
  17321. assertex(!idx);
  17322. inputTrue = _in;
  17323. }
  17324. }
  17325. virtual const void *nextInGroup()
  17326. {
  17327. ActivityTimer t(totalCycles, timeActivities);
  17328. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17329. if (in)
  17330. {
  17331. const void * ret;
  17332. if ((ret = in->nextInGroup()) != NULL)
  17333. processed++;
  17334. return ret;
  17335. }
  17336. return NULL;
  17337. }
  17338. };
  17339. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  17340. {
  17341. unsigned input2;
  17342. unsigned input2idx;
  17343. bool graphInvariant;
  17344. public:
  17345. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17346. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17347. {
  17348. graphInvariant = _graphInvariant;
  17349. input2 = (unsigned)-1;
  17350. input2idx = (unsigned)-1;
  17351. }
  17352. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17353. {
  17354. return new CRoxieServerIfActivity(this, _probeManager);
  17355. }
  17356. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  17357. {
  17358. if (idx==1)
  17359. {
  17360. input2 = source;
  17361. input2idx = sourceidx;
  17362. }
  17363. else
  17364. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  17365. }
  17366. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  17367. {
  17368. switch (idx)
  17369. {
  17370. case 1:
  17371. sourceidx = input2idx;
  17372. return input2;
  17373. case 0:
  17374. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  17375. default:
  17376. return (unsigned) -1;
  17377. }
  17378. }
  17379. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  17380. virtual bool isGraphInvariant() const
  17381. {
  17382. return graphInvariant;
  17383. }
  17384. };
  17385. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17386. {
  17387. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17388. }
  17389. //=================================================================================
  17390. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  17391. {
  17392. CriticalSection ecrit;
  17393. Owned<IException> exception;
  17394. bool executed;
  17395. public:
  17396. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17397. : CRoxieServerActivity(_factory, _probeManager)
  17398. {
  17399. executed = false;
  17400. }
  17401. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  17402. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  17403. {
  17404. CriticalBlock b(ecrit);
  17405. if (exception)
  17406. throw(exception.getLink());
  17407. if (!executed)
  17408. {
  17409. try
  17410. {
  17411. executed = true;
  17412. start(parentExtractSize, parentExtract, false);
  17413. doExecuteAction(parentExtractSize, parentExtract);
  17414. stop(false);
  17415. }
  17416. catch (IException * E)
  17417. {
  17418. ctx->notifyAbort(E);
  17419. stop(true);
  17420. exception.set(E);
  17421. throw;
  17422. }
  17423. }
  17424. }
  17425. virtual void reset()
  17426. {
  17427. executed = false;
  17428. exception.clear();
  17429. CRoxieServerActivity::reset();
  17430. }
  17431. virtual const void *nextInGroup()
  17432. {
  17433. throwUnexpected(); // I am nobody's input
  17434. }
  17435. virtual IRoxieInput *queryInput(unsigned idx) const
  17436. {
  17437. throwUnexpected(); // I am nobody's input
  17438. }
  17439. };
  17440. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  17441. {
  17442. IHThorIfArg &helper;
  17443. public:
  17444. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17445. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17446. {
  17447. }
  17448. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17449. {
  17450. bool cond;
  17451. {
  17452. ActivityTimer t(totalCycles, timeActivities);
  17453. cond = helper.getCondition();
  17454. }
  17455. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  17456. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  17457. }
  17458. };
  17459. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  17460. {
  17461. bool isRoot;
  17462. public:
  17463. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17464. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17465. {
  17466. }
  17467. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17468. {
  17469. return new CRoxieServerIfActionActivity(this, _probeManager);
  17470. }
  17471. virtual bool isSink() const
  17472. {
  17473. return isRoot;
  17474. }
  17475. };
  17476. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17477. {
  17478. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17479. }
  17480. //=================================================================================
  17481. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  17482. {
  17483. public:
  17484. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17485. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17486. {
  17487. }
  17488. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17489. {
  17490. #ifdef PARALLEL_EXECUTE
  17491. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  17492. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  17493. #else
  17494. ForEachItemIn(idx, dependencies)
  17495. {
  17496. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  17497. }
  17498. #endif
  17499. }
  17500. };
  17501. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  17502. {
  17503. bool isRoot;
  17504. public:
  17505. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17506. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17507. {
  17508. assertex(!isRoot); // non-internal should be expanded out..
  17509. }
  17510. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17511. {
  17512. return new CRoxieServerParallelActionActivity(this, _probeManager);
  17513. }
  17514. virtual bool isSink() const
  17515. {
  17516. return isRoot;
  17517. }
  17518. };
  17519. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17520. {
  17521. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17522. }
  17523. //=================================================================================
  17524. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  17525. {
  17526. IHThorSequentialArg &helper;
  17527. public:
  17528. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17529. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  17530. {
  17531. }
  17532. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17533. {
  17534. unsigned numBranches = helper.numBranches();
  17535. for (unsigned branch=1; branch <= numBranches; branch++)
  17536. executeDependencies(parentExtractSize, parentExtract, branch);
  17537. }
  17538. };
  17539. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  17540. {
  17541. bool isRoot;
  17542. public:
  17543. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17544. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17545. {
  17546. }
  17547. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17548. {
  17549. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  17550. }
  17551. virtual bool isSink() const
  17552. {
  17553. return isRoot;
  17554. }
  17555. };
  17556. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17557. {
  17558. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17559. }
  17560. //=================================================================================
  17561. class CRoxieServerWhenActivity : public CRoxieServerActivity
  17562. {
  17563. public:
  17564. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17565. : CRoxieServerActivity(_factory, _probeManager)
  17566. {
  17567. savedExtractSize = 0;
  17568. savedExtract = NULL;
  17569. }
  17570. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17571. {
  17572. savedExtractSize = parentExtractSize;
  17573. savedExtract = parentExtract;
  17574. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17575. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17576. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17577. }
  17578. virtual void stop(bool aborting)
  17579. {
  17580. if (state == STATEreset)
  17581. {
  17582. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  17583. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  17584. }
  17585. else if (state != STATEstopped)
  17586. {
  17587. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  17588. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId); // These ones do
  17589. }
  17590. CRoxieServerActivity::stop(aborting);
  17591. }
  17592. virtual const void *nextInGroup()
  17593. {
  17594. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  17595. return input->nextInGroup();
  17596. }
  17597. protected:
  17598. unsigned savedExtractSize;
  17599. const byte *savedExtract;
  17600. };
  17601. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17602. {
  17603. public:
  17604. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17605. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17606. {
  17607. }
  17608. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17609. {
  17610. return new CRoxieServerWhenActivity(this, _probeManager);
  17611. }
  17612. };
  17613. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17614. {
  17615. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17616. }
  17617. //=================================================================================
  17618. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17619. {
  17620. public:
  17621. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17622. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17623. {
  17624. savedExtractSize = 0;
  17625. savedExtract = NULL;
  17626. }
  17627. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17628. {
  17629. savedExtractSize = parentExtractSize;
  17630. savedExtract = parentExtract;
  17631. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17632. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17633. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17634. }
  17635. virtual void stop(bool aborting)
  17636. {
  17637. if (state != STATEstopped)
  17638. {
  17639. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  17640. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17641. }
  17642. CRoxieServerActionBaseActivity::stop(aborting);
  17643. }
  17644. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17645. {
  17646. executeDependencies(parentExtractSize, parentExtract, 1);
  17647. }
  17648. protected:
  17649. unsigned savedExtractSize;
  17650. const byte *savedExtract;
  17651. };
  17652. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17653. {
  17654. public:
  17655. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17656. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17657. {
  17658. }
  17659. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17660. {
  17661. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17662. }
  17663. virtual bool isSink() const
  17664. {
  17665. return isRoot;
  17666. }
  17667. private:
  17668. bool isRoot;
  17669. };
  17670. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17671. {
  17672. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17673. }
  17674. //=================================================================================
  17675. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17676. {
  17677. IHThorParseArg &helper;
  17678. INlpParser * parser;
  17679. INlpResultIterator * rowIter;
  17680. const void * in;
  17681. char * curSearchText;
  17682. INlpParseAlgorithm * algorithm;
  17683. size32_t curSearchTextLen;
  17684. bool anyThisGroup;
  17685. bool processRecord(const void * inRec)
  17686. {
  17687. if (helper.searchTextNeedsFree())
  17688. rtlFree(curSearchText);
  17689. curSearchTextLen = 0;
  17690. curSearchText = NULL;
  17691. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17692. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17693. }
  17694. public:
  17695. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17696. : CRoxieServerActivity(_factory, _probeManager),
  17697. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17698. {
  17699. parser = NULL;
  17700. rowIter = NULL;
  17701. in = NULL;
  17702. curSearchText = NULL;
  17703. anyThisGroup = false;
  17704. curSearchTextLen = 0;
  17705. }
  17706. ~CRoxieServerParseActivity()
  17707. {
  17708. ::Release(parser);
  17709. }
  17710. virtual bool needsAllocator() const { return true; }
  17711. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17712. {
  17713. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17714. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17715. rowIter = parser->queryResultIter();
  17716. }
  17717. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17718. {
  17719. anyThisGroup = false;
  17720. curSearchTextLen = 0;
  17721. curSearchText = NULL;
  17722. in = NULL;
  17723. parser->reset();
  17724. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17725. }
  17726. virtual void reset()
  17727. {
  17728. if (helper.searchTextNeedsFree())
  17729. rtlFree(curSearchText);
  17730. curSearchText = NULL;
  17731. ReleaseClearRoxieRow(in);
  17732. CRoxieServerActivity::reset();
  17733. }
  17734. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17735. {
  17736. try
  17737. {
  17738. return helper.transform(self, curRecord, results, walker);
  17739. }
  17740. catch (IException *E)
  17741. {
  17742. throw makeWrappedException(E);
  17743. }
  17744. }
  17745. virtual const void * nextInGroup()
  17746. {
  17747. ActivityTimer t(totalCycles, timeActivities);
  17748. loop
  17749. {
  17750. if (rowIter->isValid())
  17751. {
  17752. anyThisGroup = true;
  17753. OwnedConstRoxieRow out = rowIter->getRow();
  17754. rowIter->next();
  17755. processed++;
  17756. return out.getClear();
  17757. }
  17758. ReleaseClearRoxieRow(in);
  17759. in = input->nextInGroup();
  17760. if (!in)
  17761. {
  17762. if (anyThisGroup)
  17763. {
  17764. anyThisGroup = false;
  17765. return NULL;
  17766. }
  17767. in = input->nextInGroup();
  17768. if (!in)
  17769. return NULL;
  17770. }
  17771. processRecord(in);
  17772. rowIter->first();
  17773. }
  17774. }
  17775. };
  17776. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17777. {
  17778. Owned<INlpParseAlgorithm> algorithm;
  17779. Owned<IHThorParseArg> helper;
  17780. public:
  17781. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17782. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17783. {
  17784. helper.setown((IHThorParseArg *) helperFactory());
  17785. algorithm.setown(createThorParser(rc, *helper));
  17786. }
  17787. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17788. {
  17789. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17790. }
  17791. };
  17792. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17793. {
  17794. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17795. }
  17796. //=====================================================================================================
  17797. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17798. {
  17799. IHThorWorkUnitWriteArg &helper;
  17800. bool isReread;
  17801. bool grouped;
  17802. IRoxieServerContext *serverContext;
  17803. public:
  17804. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  17805. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17806. {
  17807. grouped = (helper.getFlags() & POFgrouped) != 0;
  17808. serverContext = NULL;
  17809. }
  17810. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17811. {
  17812. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17813. serverContext = ctx->queryServerContext();
  17814. if (!serverContext)
  17815. {
  17816. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17817. }
  17818. }
  17819. virtual bool needsAllocator() const { return true; }
  17820. virtual void onExecute()
  17821. {
  17822. int sequence = helper.getSequence();
  17823. const char *storedName = helper.queryName();
  17824. if (!storedName)
  17825. storedName = "Dataset";
  17826. MemoryBuffer result;
  17827. FlushingStringBuffer *response = NULL;
  17828. bool saveInContext = (int) sequence < 0 || isReread;
  17829. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17830. meta.set(input->queryOutputMeta());
  17831. Owned<IOutputRowSerializer> rowSerializer;
  17832. Owned<IXmlWriter> writer;
  17833. if ((int) sequence >= 0)
  17834. {
  17835. response = serverContext->queryResult(sequence);
  17836. if (response)
  17837. {
  17838. const IProperties *xmlns = serverContext->queryXmlns(sequence);
  17839. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0, xmlns);
  17840. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17841. {
  17842. unsigned int writeFlags = serverContext->getXmlFlags();
  17843. if (response->mlFmt==MarkupFmt_JSON)
  17844. writeFlags |= XWFnoindent;
  17845. writer.setown(createIXmlWriterExt(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17846. writer->outputBeginArray("Row");
  17847. }
  17848. }
  17849. }
  17850. size32_t outputLimitBytes = 0;
  17851. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  17852. if (workunit)
  17853. {
  17854. size32_t outputLimit;
  17855. if (helper.getFlags() & POFmaxsize)
  17856. outputLimit = helper.getMaxSize();
  17857. else
  17858. {
  17859. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  17860. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  17861. }
  17862. if (outputLimit>defaultDaliResultOutputMax)
  17863. 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);
  17864. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  17865. outputLimitBytes = outputLimit * 0x100000;
  17866. }
  17867. if (workunit != NULL || (response && response->isRaw))
  17868. {
  17869. createRowAllocator();
  17870. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17871. }
  17872. __int64 initialProcessed = processed;
  17873. RtlLinkedDatasetBuilder builder(rowAllocator);
  17874. loop
  17875. {
  17876. const void *row = input->nextInGroup();
  17877. if (saveInContext)
  17878. {
  17879. if (row || grouped)
  17880. builder.append(row);
  17881. }
  17882. if (grouped && (processed != initialProcessed))
  17883. {
  17884. if (workunit)
  17885. result.append(row == NULL);
  17886. if (response)
  17887. {
  17888. if (response->isRaw)
  17889. response->append((char)(row == NULL));
  17890. else
  17891. {
  17892. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17893. }
  17894. }
  17895. }
  17896. if (!row)
  17897. {
  17898. row = input->nextInGroup();
  17899. if (!row)
  17900. break;
  17901. if (saveInContext)
  17902. builder.append(row);
  17903. }
  17904. processed++;
  17905. if (workunit)
  17906. {
  17907. CThorDemoRowSerializer serializerTarget(result);
  17908. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17909. }
  17910. if (response)
  17911. {
  17912. if (response->isRaw)
  17913. {
  17914. // MORE - should be able to serialize straight to the response...
  17915. MemoryBuffer rowbuff;
  17916. CThorDemoRowSerializer serializerTarget(rowbuff);
  17917. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17918. response->append(rowbuff.length(), rowbuff.toByteArray());
  17919. }
  17920. else if (writer)
  17921. {
  17922. writer->outputBeginNested("Row", false);
  17923. helper.serializeXml((byte *) row, *writer);
  17924. writer->outputEndNested("Row");
  17925. }
  17926. else
  17927. {
  17928. SimpleOutputWriter x;
  17929. helper.serializeXml((byte *) row, x);
  17930. x.newline();
  17931. response->append(x.str());
  17932. }
  17933. response->incrementRowCount();
  17934. response->flush(false);
  17935. }
  17936. ReleaseRoxieRow(row);
  17937. if (outputLimitBytes && result.length() > outputLimitBytes)
  17938. {
  17939. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  17940. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  17941. const char *name = helper.queryName();
  17942. if (name)
  17943. errMsg.append("name=").append(name);
  17944. else
  17945. errMsg.append("sequence=").append(helper.getSequence());
  17946. errMsg.append(")");
  17947. throw MakeStringExceptionDirect(0, errMsg.str());
  17948. }
  17949. }
  17950. if (writer)
  17951. writer->outputEndArray("Row");
  17952. if (saveInContext)
  17953. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17954. if (workunit)
  17955. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17956. }
  17957. };
  17958. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17959. {
  17960. bool isReread;
  17961. public:
  17962. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17963. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17964. {
  17965. isReread = usageCount > 0;
  17966. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17967. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17968. }
  17969. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17970. {
  17971. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread, usageCount);
  17972. }
  17973. };
  17974. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17975. {
  17976. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17977. }
  17978. //=====================================================================================================
  17979. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17980. {
  17981. IHThorDictionaryWorkUnitWriteArg &helper;
  17982. IRoxieServerContext *serverContext;
  17983. public:
  17984. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  17985. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17986. {
  17987. serverContext = NULL;
  17988. }
  17989. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17990. {
  17991. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17992. serverContext = ctx->queryServerContext();
  17993. if (!serverContext)
  17994. {
  17995. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17996. }
  17997. }
  17998. virtual bool needsAllocator() const { return true; }
  17999. virtual void onExecute()
  18000. {
  18001. int sequence = helper.getSequence();
  18002. const char *storedName = helper.queryName();
  18003. assertex(storedName && *storedName);
  18004. assertex(sequence < 0);
  18005. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  18006. loop
  18007. {
  18008. const void *row = input->nextInGroup();
  18009. if (!row)
  18010. {
  18011. row = input->nextInGroup();
  18012. if (!row)
  18013. break;
  18014. }
  18015. builder.appendOwn(row);
  18016. processed++;
  18017. }
  18018. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18019. }
  18020. };
  18021. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18022. {
  18023. public:
  18024. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18025. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18026. {
  18027. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18028. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18029. }
  18030. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18031. {
  18032. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager, usageCount);
  18033. }
  18034. };
  18035. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18036. {
  18037. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18038. }
  18039. //=================================================================================
  18040. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18041. {
  18042. IHThorRemoteResultArg &helper;
  18043. public:
  18044. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18045. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18046. {
  18047. }
  18048. virtual void onExecute()
  18049. {
  18050. OwnedConstRoxieRow row = input->nextInGroup();
  18051. helper.sendResult(row); // should be only one row or something has gone wrong!
  18052. }
  18053. };
  18054. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18055. {
  18056. public:
  18057. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18058. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18059. {
  18060. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18061. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18062. }
  18063. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18064. {
  18065. return new CRoxieServerRemoteResultActivity(this, _probeManager, usageCount);
  18066. }
  18067. };
  18068. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18069. {
  18070. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18071. }
  18072. //=================================================================================
  18073. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18074. {
  18075. IHThorXmlParseArg &helper;
  18076. Owned<IXMLParse> xmlParser;
  18077. const void * in;
  18078. char * srchStr;
  18079. unsigned numProcessedLastGroup;
  18080. bool srchStrNeedsFree;
  18081. Owned<IColumnProvider> lastMatch;
  18082. public:
  18083. IMPLEMENT_IINTERFACE;
  18084. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18085. : CRoxieServerActivity(_factory, _probeManager),
  18086. helper((IHThorXmlParseArg &)basehelper)
  18087. {
  18088. srchStrNeedsFree = helper.searchTextNeedsFree();
  18089. numProcessedLastGroup = 0;
  18090. srchStr = NULL;
  18091. in = NULL;
  18092. }
  18093. ~CRoxieServerXmlParseActivity()
  18094. {
  18095. }
  18096. virtual bool needsAllocator() const { return true; }
  18097. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18098. {
  18099. numProcessedLastGroup = 0;
  18100. srchStr = NULL;
  18101. in = NULL;
  18102. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18103. }
  18104. virtual void reset()
  18105. {
  18106. if (helper.searchTextNeedsFree())
  18107. rtlFree(srchStr);
  18108. srchStr = NULL;
  18109. ReleaseClearRoxieRow(in);
  18110. xmlParser.clear();
  18111. CRoxieServerActivity::reset();
  18112. }
  18113. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18114. {
  18115. lastMatch.set(&entry);
  18116. }
  18117. virtual const void *nextInGroup()
  18118. {
  18119. ActivityTimer t(totalCycles, timeActivities);
  18120. loop
  18121. {
  18122. if(xmlParser)
  18123. {
  18124. loop
  18125. {
  18126. if(!xmlParser->next())
  18127. {
  18128. if (srchStrNeedsFree)
  18129. {
  18130. rtlFree(srchStr);
  18131. srchStr = NULL;
  18132. }
  18133. xmlParser.clear();
  18134. break;
  18135. }
  18136. if(lastMatch)
  18137. {
  18138. try
  18139. {
  18140. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18141. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18142. lastMatch.clear();
  18143. if (outSize)
  18144. {
  18145. processed++;
  18146. return rowBuilder.finalizeRowClear(outSize);
  18147. }
  18148. }
  18149. catch (IException *E)
  18150. {
  18151. throw makeWrappedException(E);
  18152. }
  18153. }
  18154. }
  18155. }
  18156. ReleaseClearRoxieRow(in);
  18157. in = input->nextInGroup();
  18158. if(!in)
  18159. {
  18160. if(numProcessedLastGroup == processed)
  18161. in = input->nextInGroup();
  18162. if(!in)
  18163. {
  18164. numProcessedLastGroup = processed;
  18165. return NULL;
  18166. }
  18167. }
  18168. size32_t srchLen;
  18169. helper.getSearchText(srchLen, srchStr, in);
  18170. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  18171. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  18172. }
  18173. }
  18174. };
  18175. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  18176. {
  18177. public:
  18178. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18179. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  18180. {
  18181. }
  18182. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18183. {
  18184. return new CRoxieServerXmlParseActivity(this, _probeManager);
  18185. }
  18186. };
  18187. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18188. {
  18189. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  18190. }
  18191. //=====================================================================================================
  18192. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  18193. {
  18194. protected:
  18195. IHThorDiskReadBaseArg &helper;
  18196. IHThorCompoundExtra * compoundHelper;
  18197. RemoteActivityId remoteId; // Note we copy it rather than reference
  18198. Owned<CSkippableRemoteResultAdaptor> remote;
  18199. unsigned numParts;
  18200. unsigned __int64 rowLimit;
  18201. unsigned __int64 stopAfter;
  18202. Linked<IInMemoryIndexManager> manager;
  18203. Owned<IInMemoryIndexCursor> cursor;
  18204. Owned<IDirectReader> reader;
  18205. CThorContiguousRowBuffer deserializeSource;
  18206. Owned<ISourceRowPrefetcher> prefetcher;
  18207. bool eof;
  18208. bool isKeyed;
  18209. bool variableFileName;
  18210. bool isOpt;
  18211. bool sorted;
  18212. bool maySkip;
  18213. bool isLocal;
  18214. bool forceRemote;
  18215. CachedOutputMetaData diskSize;
  18216. Owned<const IResolvedFile> varFileInfo;
  18217. Owned<IFileIOArray> varFiles;
  18218. inline bool useRemote()
  18219. {
  18220. return remote != NULL && (forceRemote || numParts > 1);
  18221. }
  18222. public:
  18223. IMPLEMENT_IINTERFACE;
  18224. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18225. : CRoxieServerActivity(_factory, _probeManager),
  18226. helper((IHThorDiskReadBaseArg &)basehelper),
  18227. numParts(_numParts),
  18228. remoteId(_remoteId),
  18229. manager(_manager),
  18230. isLocal(_isLocal),
  18231. sorted(_sorted),
  18232. maySkip(_maySkip),
  18233. deserializeSource(NULL)
  18234. {
  18235. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  18236. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  18237. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  18238. compoundHelper = NULL;
  18239. eof = false;
  18240. rowLimit = (unsigned __int64) -1;
  18241. isKeyed = false;
  18242. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  18243. diskSize.set(helper.queryDiskRecordSize());
  18244. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18245. isOpt = (helper.getFlags() & TDRoptional) != 0;
  18246. }
  18247. virtual const IResolvedFile *queryVarFileInfo() const
  18248. {
  18249. return varFileInfo;
  18250. }
  18251. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18252. {
  18253. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18254. if (remote)
  18255. remote->onCreate(this, this, _ctx, _colocalParent);
  18256. }
  18257. virtual bool needsAllocator() const { return true; }
  18258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18259. {
  18260. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18261. if (compoundHelper)
  18262. {
  18263. rowLimit = compoundHelper->getRowLimit();
  18264. stopAfter = compoundHelper->getChooseNLimit();
  18265. }
  18266. if (!helper.canMatchAny())
  18267. eof = true;
  18268. else
  18269. {
  18270. if (variableFileName)
  18271. {
  18272. OwnedRoxieString fileName(helper.getFileName());
  18273. varFileInfo.setown(resolveLFN(fileName, isOpt));
  18274. numParts = 0;
  18275. if (varFileInfo)
  18276. numParts = varFileInfo->getNumParts();
  18277. }
  18278. if (!numParts)
  18279. {
  18280. eof = true;
  18281. }
  18282. else if (useRemote())
  18283. {
  18284. remote->onStart(parentExtractSize, parentExtract);
  18285. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  18286. unsigned fileNo = 0;
  18287. // Translation into a message per channel done elsewhere....
  18288. remote->getMem(0, fileNo, 0);
  18289. remote->flush();
  18290. remote->senddone();
  18291. }
  18292. else
  18293. {
  18294. if (variableFileName)
  18295. {
  18296. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  18297. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  18298. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  18299. }
  18300. assertex(manager != NULL);
  18301. helper.createSegmentMonitors(this);
  18302. if (cursor)
  18303. {
  18304. isKeyed = cursor->selectKey();
  18305. cursor->reset();
  18306. }
  18307. if (!isKeyed)
  18308. {
  18309. reader.setown(manager->createReader(0, 0, 1));
  18310. deserializeSource.setStream(reader);
  18311. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  18312. }
  18313. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  18314. }
  18315. }
  18316. }
  18317. virtual void append(IKeySegmentMonitor *segment)
  18318. {
  18319. if (!segment->isWild())
  18320. {
  18321. if (!cursor)
  18322. cursor.setown(manager->createCursor());
  18323. cursor->append(segment);
  18324. }
  18325. }
  18326. virtual unsigned ordinality() const
  18327. {
  18328. return cursor ? cursor->ordinality() : 0;
  18329. }
  18330. virtual IKeySegmentMonitor *item(unsigned idx) const
  18331. {
  18332. return cursor ? cursor->item(idx) : 0;
  18333. }
  18334. virtual void setMergeBarrier(unsigned barrierOffset)
  18335. {
  18336. // no merging so no issue...
  18337. }
  18338. virtual void stop(bool aborting)
  18339. {
  18340. if (useRemote())
  18341. remote->onStop(aborting);
  18342. CRoxieServerActivity::stop(aborting);
  18343. }
  18344. virtual void reset()
  18345. {
  18346. if (useRemote())
  18347. {
  18348. processed = remote->processed;
  18349. remote->processed = 0;
  18350. remote->onReset();
  18351. }
  18352. varFileInfo.clear();
  18353. eof = false;
  18354. if (cursor)
  18355. cursor->reset();
  18356. deserializeSource.clearStream();
  18357. CRoxieServerActivity::reset();
  18358. }
  18359. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18360. {
  18361. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18362. }
  18363. virtual void onLimitExceeded(bool isKeyed)
  18364. {
  18365. if (traceLevel > 4)
  18366. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18367. assertex(compoundHelper);
  18368. if (isKeyed) // MORE does this exist for diskread? should it?
  18369. {
  18370. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  18371. {
  18372. if (ctx->queryDebugContext())
  18373. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18374. throw makeLimitSkipException(true);
  18375. }
  18376. else
  18377. {
  18378. UNIMPLEMENTED;
  18379. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  18380. }
  18381. }
  18382. else
  18383. {
  18384. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  18385. {
  18386. if (ctx->queryDebugContext())
  18387. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18388. throw makeLimitSkipException(false);
  18389. }
  18390. else
  18391. compoundHelper->onLimitExceeded();
  18392. }
  18393. }
  18394. virtual const void * createLimitFailRow(bool isKeyed)
  18395. {
  18396. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18397. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  18398. assertex(limitTransformExtra);
  18399. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18400. if (outSize)
  18401. return rowBuilder.finalizeRowClear(outSize);
  18402. return NULL;
  18403. }
  18404. };
  18405. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  18406. {
  18407. IHThorCompoundReadExtra * readHelper;
  18408. ConstPointerArray readrows;
  18409. bool readAheadDone;
  18410. unsigned readIndex;
  18411. public:
  18412. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18413. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18414. {
  18415. compoundHelper = (IHThorDiskReadArg *)&helper;
  18416. readHelper = (IHThorDiskReadArg *)&helper;
  18417. readAheadDone = false;
  18418. readIndex = 0;
  18419. }
  18420. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18421. {
  18422. rowLimit = compoundHelper->getRowLimit();
  18423. stopAfter = compoundHelper->getChooseNLimit();
  18424. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18425. readAheadDone = false;
  18426. readIndex = 0;
  18427. }
  18428. virtual void reset()
  18429. {
  18430. while (readrows.isItem(readIndex))
  18431. ReleaseRoxieRow(readrows.item(readIndex++));
  18432. readrows.kill();
  18433. readAheadDone = false;
  18434. readIndex = 0;
  18435. CRoxieServerDiskReadBaseActivity::reset();
  18436. }
  18437. virtual const void *nextInGroup()
  18438. {
  18439. if (eof)
  18440. return NULL;
  18441. else if (useRemote())
  18442. return remote->nextInGroup();
  18443. else if (maySkip)
  18444. {
  18445. if (!readAheadDone)
  18446. {
  18447. unsigned preprocessed = 0;
  18448. while (!eof)
  18449. {
  18450. const void *row = _nextInGroup();
  18451. if (row)
  18452. preprocessed++;
  18453. if (preprocessed > rowLimit)
  18454. {
  18455. ReleaseRoxieRow(row);
  18456. while (readrows.isItem(readIndex))
  18457. ReleaseRoxieRow(readrows.item(readIndex++));
  18458. readrows.kill();
  18459. eof = true;
  18460. if (ctx->queryDebugContext())
  18461. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18462. if (helper.getFlags() & TDRlimitskips)
  18463. return NULL;
  18464. else if (helper.getFlags() & TDRlimitcreates)
  18465. return createLimitFailRow(false);
  18466. else
  18467. throwUnexpected();
  18468. }
  18469. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  18470. {
  18471. eof = true;
  18472. ReleaseRoxieRow(row);
  18473. break;
  18474. }
  18475. readrows.append(row);
  18476. }
  18477. readAheadDone = true;
  18478. }
  18479. if (readrows.isItem(readIndex))
  18480. {
  18481. const void *ret = readrows.item(readIndex++);
  18482. if (ret)
  18483. processed++;
  18484. return ret;
  18485. }
  18486. else
  18487. {
  18488. eof = true;
  18489. return NULL;
  18490. }
  18491. }
  18492. else
  18493. {
  18494. const void *ret = _nextInGroup();
  18495. if (ret)
  18496. {
  18497. processed++;
  18498. if (processed > rowLimit)
  18499. {
  18500. if (traceLevel > 4)
  18501. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18502. ReleaseRoxieRow(ret);
  18503. compoundHelper->onLimitExceeded();
  18504. throwUnexpected(); // onLimitExceeded is not supposed to return
  18505. }
  18506. if (processed > stopAfter) // MORE - bit of a strange place to check
  18507. {
  18508. eof = true;
  18509. ReleaseRoxieRow(ret);
  18510. return NULL;
  18511. }
  18512. }
  18513. return ret;
  18514. }
  18515. }
  18516. const void *_nextInGroup()
  18517. {
  18518. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18519. unsigned transformedSize = 0;
  18520. if (isKeyed)
  18521. {
  18522. loop
  18523. {
  18524. const void *nextCandidate = cursor->nextMatch();
  18525. if (!nextCandidate)
  18526. {
  18527. eof = true;
  18528. return NULL;
  18529. }
  18530. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  18531. if (transformedSize)
  18532. break;
  18533. }
  18534. }
  18535. else // use reader...
  18536. {
  18537. assertex(reader != NULL);
  18538. loop
  18539. {
  18540. if (deserializeSource.eos())
  18541. {
  18542. eof = true;
  18543. return NULL;
  18544. }
  18545. prefetcher->readAhead(deserializeSource);
  18546. const byte *nextRec = deserializeSource.queryRow();
  18547. if (cursor && cursor->isFiltered(nextRec))
  18548. transformedSize = 0;
  18549. else
  18550. transformedSize = readHelper->transform(rowBuilder, nextRec);
  18551. deserializeSource.finishedRow();
  18552. if (transformedSize)
  18553. break;
  18554. }
  18555. }
  18556. return rowBuilder.finalizeRowClear(transformedSize);
  18557. }
  18558. };
  18559. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  18560. {
  18561. IHThorXmlReadArg * readHelper;
  18562. Owned<IXmlToRowTransformer> rowTransformer;
  18563. Owned<IXMLParse> xmlParser;
  18564. Owned<IColumnProvider> lastMatch;
  18565. unsigned __int64 localOffset;
  18566. public:
  18567. IMPLEMENT_IINTERFACE;
  18568. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18569. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18570. {
  18571. compoundHelper = NULL;
  18572. readHelper = (IHThorXmlReadArg *)&helper;
  18573. localOffset = 0;
  18574. }
  18575. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18576. {
  18577. rowLimit = readHelper->getRowLimit();
  18578. stopAfter = readHelper->getChooseNLimit();
  18579. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18580. if (!useRemote())
  18581. {
  18582. rowTransformer.set(readHelper->queryTransformer());
  18583. assertex(reader != NULL);
  18584. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  18585. if (factory->getKind()==TAKjsonread)
  18586. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18587. else
  18588. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18589. }
  18590. }
  18591. virtual void reset()
  18592. {
  18593. CRoxieServerDiskReadBaseActivity::reset();
  18594. rowTransformer.clear();
  18595. xmlParser.clear();
  18596. }
  18597. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18598. {
  18599. localOffset = startOffset;
  18600. lastMatch.set(&entry);
  18601. }
  18602. virtual const void *nextInGroup()
  18603. {
  18604. if (eof)
  18605. return NULL;
  18606. else if (useRemote())
  18607. return remote->nextInGroup();
  18608. assertex(xmlParser != NULL);
  18609. try
  18610. {
  18611. while (!eof)
  18612. {
  18613. //call to next() will callback on the IXmlSelect interface
  18614. bool gotNext = false;
  18615. gotNext = xmlParser->next();
  18616. if(!gotNext)
  18617. eof = true;
  18618. else if (lastMatch)
  18619. {
  18620. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18621. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18622. lastMatch.clear();
  18623. localOffset = 0;
  18624. if (sizeGot)
  18625. {
  18626. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18627. if (processed > rowLimit)
  18628. {
  18629. if (traceLevel > 4)
  18630. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18631. readHelper->onLimitExceeded();
  18632. throwUnexpected(); // onLimitExceeded is not supposed to return
  18633. }
  18634. processed++;
  18635. if (processed > stopAfter) // MORE - bit of a strange place to check
  18636. {
  18637. eof = true;
  18638. return NULL;
  18639. }
  18640. return ret.getClear();
  18641. }
  18642. }
  18643. }
  18644. return NULL;
  18645. }
  18646. catch(IException *E)
  18647. {
  18648. throw makeWrappedException(E);
  18649. }
  18650. }
  18651. };
  18652. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18653. {
  18654. IHThorCsvReadArg *readHelper;
  18655. ICsvParameters * csvInfo;
  18656. unsigned headerLines;
  18657. unsigned maxDiskSize;
  18658. CSVSplitter csvSplitter;
  18659. unsigned __int64 localOffset;
  18660. const char *quotes;
  18661. const char *separators;
  18662. const char *terminators;
  18663. const char *escapes;
  18664. size32_t maxRowSize;
  18665. public:
  18666. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18667. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18668. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  18669. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18670. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  18671. {
  18672. compoundHelper = NULL;
  18673. readHelper = (IHThorCsvReadArg *)&helper;
  18674. rowLimit = readHelper->getRowLimit();
  18675. stopAfter = readHelper->getChooseNLimit();
  18676. csvInfo = readHelper->queryCsvParameters();
  18677. maxDiskSize = csvInfo->queryMaxSize();
  18678. localOffset = 0;
  18679. headerLines = 0;
  18680. }
  18681. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18682. {
  18683. rowLimit = readHelper->getRowLimit();
  18684. stopAfter = readHelper->getChooseNLimit();
  18685. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18686. if (!useRemote())
  18687. {
  18688. headerLines = csvInfo->queryHeaderLen();
  18689. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18690. 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...
  18691. if (!eof)
  18692. {
  18693. if (varFileInfo)
  18694. {
  18695. const IPropertyTree *options = varFileInfo->queryProperties();
  18696. if (options)
  18697. {
  18698. quotes = options->queryProp("@csvQuote");
  18699. separators = options->queryProp("@csvSeparate");
  18700. terminators = options->queryProp("@csvTerminate");
  18701. escapes = options->queryProp("@csvEscape");
  18702. }
  18703. }
  18704. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18705. }
  18706. }
  18707. }
  18708. virtual const void *nextInGroup()
  18709. {
  18710. if (eof)
  18711. return NULL;
  18712. else if (useRemote())
  18713. return remote->nextInGroup();
  18714. try
  18715. {
  18716. while (!eof)
  18717. {
  18718. if (reader->eos())
  18719. {
  18720. eof = true;
  18721. break;
  18722. }
  18723. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18724. size32_t rowSize = 4096; // MORE - make configurable
  18725. size32_t thisLineLength;
  18726. loop
  18727. {
  18728. size32_t avail;
  18729. const void *peek = reader->peek(rowSize, avail);
  18730. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18731. if (thisLineLength < rowSize || avail < rowSize)
  18732. break;
  18733. if (rowSize == maxRowSize)
  18734. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  18735. if (rowSize >= maxRowSize/2)
  18736. rowSize = maxRowSize;
  18737. else
  18738. rowSize += rowSize;
  18739. }
  18740. if (headerLines)
  18741. {
  18742. headerLines--;
  18743. reader->skip(thisLineLength);
  18744. }
  18745. else
  18746. {
  18747. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18748. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18749. reader->skip(thisLineLength);
  18750. if (transformedSize)
  18751. {
  18752. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18753. if (processed > rowLimit)
  18754. {
  18755. readHelper->onLimitExceeded();
  18756. throwUnexpected(); // onLimitExceeded is not supposed to return
  18757. }
  18758. processed++;
  18759. if (processed > stopAfter) // MORE - bit of a strange place to check
  18760. {
  18761. eof = true;
  18762. return NULL;
  18763. }
  18764. return ret.getClear();
  18765. }
  18766. }
  18767. }
  18768. return NULL;
  18769. }
  18770. catch(IException *E)
  18771. {
  18772. throw makeWrappedException(E);
  18773. }
  18774. }
  18775. virtual void reset()
  18776. {
  18777. CRoxieServerDiskReadBaseActivity::reset();
  18778. csvSplitter.reset();
  18779. localOffset = 0;
  18780. }
  18781. virtual unsigned __int64 getFilePosition(const void * row)
  18782. {
  18783. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18784. }
  18785. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18786. {
  18787. UNIMPLEMENTED;
  18788. }
  18789. };
  18790. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18791. {
  18792. IHThorDiskNormalizeArg *normalizeHelper;
  18793. bool firstPending;
  18794. public:
  18795. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18796. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18797. {
  18798. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18799. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18800. firstPending = true;
  18801. }
  18802. virtual void reset()
  18803. {
  18804. firstPending = true;
  18805. CRoxieServerDiskReadBaseActivity::reset();
  18806. }
  18807. virtual const void *nextInGroup()
  18808. {
  18809. if (eof)
  18810. return NULL;
  18811. else if (useRemote())
  18812. return remote->nextInGroup();
  18813. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18814. unsigned transformedSize = 0;
  18815. if (isKeyed)
  18816. {
  18817. loop
  18818. {
  18819. while (firstPending)
  18820. {
  18821. const void *nextCandidate = cursor->nextMatch();
  18822. if (!nextCandidate)
  18823. {
  18824. eof = true;
  18825. return NULL;
  18826. }
  18827. if (normalizeHelper->first(nextCandidate))
  18828. {
  18829. firstPending = false;
  18830. break;
  18831. }
  18832. }
  18833. transformedSize = normalizeHelper->transform(rowBuilder);
  18834. firstPending = !normalizeHelper->next();
  18835. if (transformedSize)
  18836. break;
  18837. }
  18838. }
  18839. else
  18840. {
  18841. assertex(reader != NULL);
  18842. loop
  18843. {
  18844. while (firstPending)
  18845. {
  18846. if (deserializeSource.eos())
  18847. {
  18848. eof = true;
  18849. return NULL;
  18850. }
  18851. prefetcher->readAhead(deserializeSource);
  18852. const byte *nextRec = deserializeSource.queryRow();
  18853. if (!cursor || !cursor->isFiltered(nextRec))
  18854. {
  18855. if (normalizeHelper->first(nextRec))
  18856. firstPending = false;
  18857. }
  18858. deserializeSource.finishedRow();
  18859. }
  18860. transformedSize = normalizeHelper->transform(rowBuilder);
  18861. firstPending = !normalizeHelper->next();
  18862. if (transformedSize)
  18863. break;
  18864. }
  18865. }
  18866. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18867. processed++;
  18868. if (processed > rowLimit)
  18869. {
  18870. compoundHelper->onLimitExceeded();
  18871. throwUnexpected(); // onLimitExceeded is not supposed to return
  18872. }
  18873. if (processed > stopAfter) // MORE - bit of a strange place to check
  18874. {
  18875. eof = true;
  18876. return NULL;
  18877. }
  18878. return recBuffer.getClear();
  18879. }
  18880. };
  18881. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18882. {
  18883. protected:
  18884. bool done;
  18885. public:
  18886. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18887. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18888. done(false)
  18889. {
  18890. }
  18891. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18892. {
  18893. done = false;
  18894. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18895. }
  18896. virtual IRoxieInput *queryOutput(unsigned idx)
  18897. {
  18898. if (idx==(unsigned)-1)
  18899. idx = 0;
  18900. return idx ? NULL: this;
  18901. }
  18902. };
  18903. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18904. {
  18905. IHThorDiskCountArg & countHelper;
  18906. unsigned __int64 choosenLimit;
  18907. IHThorSourceCountLimit *limitHelper;
  18908. unsigned __int64 getSkippedCount()
  18909. {
  18910. unsigned flags = countHelper.getFlags();
  18911. if (flags & TDRlimitskips)
  18912. return 0;
  18913. else if (flags & TDRlimitcreates)
  18914. return 1;
  18915. else
  18916. {
  18917. assertex(limitHelper);
  18918. if (traceLevel > 4)
  18919. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18920. limitHelper->onLimitExceeded();
  18921. throwUnexpected(); // onLimitExceeded should always throw exception
  18922. }
  18923. }
  18924. public:
  18925. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18926. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18927. countHelper((IHThorDiskCountArg &)basehelper)
  18928. {
  18929. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18930. choosenLimit = 0;
  18931. }
  18932. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18933. {
  18934. choosenLimit = countHelper.getChooseNLimit();
  18935. if (limitHelper)
  18936. {
  18937. rowLimit = limitHelper->getRowLimit();
  18938. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18939. }
  18940. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18941. }
  18942. virtual const void *nextInGroup()
  18943. {
  18944. ActivityTimer t(totalCycles, timeActivities);
  18945. if (done) return NULL;
  18946. done = true;
  18947. unsigned __int64 totalCount = 0;
  18948. if (helper.canMatchAny() && !eof)
  18949. {
  18950. if (useRemote())
  18951. {
  18952. loop
  18953. {
  18954. const void * next = remote->nextInGroup();
  18955. if (!next)
  18956. break;
  18957. if (meta.getFixedSize() == 1)
  18958. totalCount += *(byte *)next;
  18959. else
  18960. totalCount += *(unsigned __int64 *)next;
  18961. ReleaseRoxieRow(next);
  18962. if (totalCount > rowLimit)
  18963. {
  18964. totalCount = getSkippedCount();
  18965. break;
  18966. }
  18967. else if (totalCount >= choosenLimit)
  18968. {
  18969. totalCount = choosenLimit;
  18970. break;
  18971. }
  18972. }
  18973. }
  18974. else
  18975. {
  18976. if (isKeyed)
  18977. {
  18978. loop
  18979. {
  18980. const void *nextCandidate = cursor->nextMatch();
  18981. if (!nextCandidate)
  18982. break;
  18983. totalCount += countHelper.numValid(nextCandidate);
  18984. if (totalCount > rowLimit)
  18985. {
  18986. totalCount = getSkippedCount();
  18987. break;
  18988. }
  18989. else if (totalCount >= choosenLimit)
  18990. {
  18991. totalCount = choosenLimit;
  18992. break;
  18993. }
  18994. }
  18995. }
  18996. else
  18997. {
  18998. assertex(reader != NULL);
  18999. while (!deserializeSource.eos())
  19000. {
  19001. prefetcher->readAhead(deserializeSource);
  19002. const byte *nextRec = deserializeSource.queryRow();
  19003. if (!cursor || !cursor->isFiltered(nextRec))
  19004. {
  19005. totalCount += countHelper.numValid(nextRec);
  19006. }
  19007. deserializeSource.finishedRow();
  19008. if (totalCount > rowLimit)
  19009. {
  19010. totalCount = getSkippedCount();
  19011. break;
  19012. }
  19013. else if (totalCount >= choosenLimit)
  19014. {
  19015. totalCount = choosenLimit;
  19016. break;
  19017. }
  19018. }
  19019. }
  19020. }
  19021. }
  19022. size32_t rowSize = meta.getFixedSize();
  19023. void * result = rowAllocator->createRow();
  19024. if (rowSize == 1)
  19025. *(byte *)result = (byte)totalCount;
  19026. else
  19027. {
  19028. assertex(rowSize == sizeof(unsigned __int64));
  19029. *(unsigned __int64 *)result = totalCount;
  19030. }
  19031. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19032. }
  19033. };
  19034. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19035. {
  19036. IHThorCompoundAggregateExtra & aggregateHelper;
  19037. public:
  19038. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19039. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19040. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19041. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19042. {
  19043. }
  19044. const void * gatherMerged()
  19045. {
  19046. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19047. size32_t finalSize = 0;
  19048. if (useRemote())
  19049. {
  19050. const void * firstRow = remote->nextInGroup();
  19051. if (!firstRow)
  19052. {
  19053. rowBuilder.ensureRow();
  19054. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19055. }
  19056. else
  19057. {
  19058. // NOTE need to clone this because going to modify below, could special case 1 row only
  19059. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19060. ReleaseRoxieRow(firstRow);
  19061. }
  19062. loop
  19063. {
  19064. const void * next = remote->nextInGroup();
  19065. if (!next)
  19066. break;
  19067. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19068. ReleaseRoxieRow(next);
  19069. }
  19070. }
  19071. else
  19072. {
  19073. aggregateHelper.clearAggregate(rowBuilder);
  19074. if (helper.canMatchAny() && !eof)
  19075. {
  19076. if (isKeyed)
  19077. {
  19078. loop
  19079. {
  19080. const void *next = cursor->nextMatch();
  19081. if (!next)
  19082. break;
  19083. aggregateHelper.processRow(rowBuilder, next);
  19084. }
  19085. }
  19086. else
  19087. {
  19088. assertex(reader != NULL);
  19089. while (!deserializeSource.eos())
  19090. {
  19091. prefetcher->readAhead(deserializeSource);
  19092. const byte *nextRec = deserializeSource.queryRow();
  19093. if (!cursor || !cursor->isFiltered(nextRec))
  19094. {
  19095. aggregateHelper.processRow(rowBuilder, nextRec);
  19096. }
  19097. deserializeSource.finishedRow();
  19098. }
  19099. }
  19100. }
  19101. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19102. }
  19103. return rowBuilder.finalizeRowClear(finalSize);
  19104. }
  19105. virtual const void *nextInGroup()
  19106. {
  19107. ActivityTimer t(totalCycles, timeActivities);
  19108. if (done) return NULL;
  19109. const void * ret = gatherMerged();
  19110. done = true;
  19111. return ret;
  19112. }
  19113. };
  19114. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19115. {
  19116. IHThorDiskGroupAggregateArg & aggregateHelper;
  19117. RowAggregator resultAggregator;
  19118. bool gathered;
  19119. public:
  19120. IMPLEMENT_IINTERFACE;
  19121. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19122. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19123. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19124. resultAggregator(aggregateHelper, aggregateHelper),
  19125. gathered(false)
  19126. {
  19127. }
  19128. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19129. {
  19130. gathered= false;
  19131. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19132. resultAggregator.start(rowAllocator);
  19133. }
  19134. virtual void reset()
  19135. {
  19136. resultAggregator.reset();
  19137. CRoxieServerDiskAggregateBaseActivity::reset();
  19138. }
  19139. void gatherMerged()
  19140. {
  19141. if (useRemote())
  19142. {
  19143. loop
  19144. {
  19145. const void * next = remote->nextInGroup();
  19146. if (!next)
  19147. break;
  19148. resultAggregator.mergeElement(next);
  19149. ReleaseRoxieRow(next);
  19150. }
  19151. }
  19152. else
  19153. {
  19154. if (helper.canMatchAny() && !eof)
  19155. {
  19156. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  19157. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  19158. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  19159. ctx->queryCodeContext(), activityId);
  19160. processor->doQuery(NULL, 0, 0, 0);
  19161. }
  19162. }
  19163. gathered = true;
  19164. }
  19165. virtual const void *nextInGroup()
  19166. {
  19167. ActivityTimer t(totalCycles, timeActivities);
  19168. if (done)
  19169. return NULL;
  19170. if (!gathered)
  19171. gatherMerged();
  19172. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  19173. if (next)
  19174. {
  19175. processed++;
  19176. return next->finalizeRowClear();
  19177. }
  19178. done = true;
  19179. return NULL;
  19180. }
  19181. };
  19182. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  19183. {
  19184. public:
  19185. RemoteActivityId remoteId;
  19186. bool isLocal;
  19187. bool sorted;
  19188. bool maySkip;
  19189. bool variableFileName;
  19190. Owned<IFileIOArray> files;
  19191. Owned<IInMemoryIndexManager> manager;
  19192. Owned<const IResolvedFile> datafile;
  19193. const char *quotes;
  19194. const char *separators;
  19195. const char *terminators;
  19196. const char *escapes;
  19197. size32_t maxCsvRowSize;
  19198. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19199. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19200. {
  19201. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19202. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19203. sorted = (helper->getFlags() & TDRunsorted) == 0;
  19204. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19205. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  19206. quotes = separators = terminators = escapes = NULL;
  19207. if (!variableFileName)
  19208. {
  19209. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  19210. OwnedRoxieString fileName(helper->getFileName());
  19211. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit()));
  19212. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  19213. if (isLocal || isSimple)
  19214. {
  19215. if (datafile)
  19216. {
  19217. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  19218. files.setown(datafile->getIFileIOArray(isOpt, channel));
  19219. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  19220. const IPropertyTree *options = datafile->queryProperties();
  19221. if (options)
  19222. {
  19223. quotes = options->queryProp("@csvQuote");
  19224. separators = options->queryProp("@csvSeparate");
  19225. terminators = options->queryProp("@csvTerminate");
  19226. escapes = options->queryProp("@csvEscape");
  19227. }
  19228. }
  19229. else
  19230. manager.setown(getEmptyIndexManager());
  19231. }
  19232. }
  19233. switch (kind)
  19234. {
  19235. case TAKcsvread:
  19236. {
  19237. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  19238. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  19239. if (workunit)
  19240. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  19241. break;
  19242. }
  19243. default:
  19244. maxCsvRowSize = 0; // unused
  19245. }
  19246. }
  19247. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19248. {
  19249. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  19250. switch (kind)
  19251. {
  19252. case TAKcsvread:
  19253. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  19254. quotes, separators, terminators, escapes, maxCsvRowSize);
  19255. case TAKxmlread:
  19256. case TAKjsonread:
  19257. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19258. case TAKdiskread:
  19259. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19260. case TAKdisknormalize:
  19261. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  19262. case TAKdiskcount:
  19263. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19264. case TAKdiskaggregate:
  19265. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19266. case TAKdiskgroupaggregate:
  19267. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19268. }
  19269. throwUnexpected();
  19270. }
  19271. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19272. {
  19273. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  19274. }
  19275. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19276. {
  19277. if (datafile)
  19278. addXrefFileInfo(reply, datafile);
  19279. else
  19280. {
  19281. // Temporarily resolve the file
  19282. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19283. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  19284. {
  19285. OwnedRoxieString fileName(helper->getFileName());
  19286. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit());
  19287. if (temp)
  19288. addXrefFileInfo(reply, temp);
  19289. }
  19290. }
  19291. }
  19292. virtual const StatisticsMapping &queryStatsMapping() const
  19293. {
  19294. return diskStatistics;
  19295. }
  19296. };
  19297. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19298. {
  19299. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19300. }
  19301. //=================================================================================
  19302. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  19303. {
  19304. protected:
  19305. IHThorIndexReadBaseArg &indexHelper;
  19306. IHThorSteppedSourceExtra * steppedExtra;
  19307. Linked<IKeyArray> keySet;
  19308. Linked<TranslatorArray> translators;
  19309. CSkippableRemoteResultAdaptor remote;
  19310. CIndexTransformCallback callback;
  19311. bool sorted;
  19312. bool variableFileName;
  19313. bool variableInfoPending;
  19314. bool isOpt;
  19315. bool isLocal;
  19316. unsigned __int64 rowLimit;
  19317. unsigned __int64 keyedLimit;
  19318. unsigned __int64 choosenLimit;
  19319. unsigned accepted;
  19320. unsigned rejected;
  19321. unsigned seekGEOffset;
  19322. Owned<IKeyManager> tlk;
  19323. Owned<const IResolvedFile> varFileInfo;
  19324. const RemoteActivityId &remoteId;
  19325. void setVariableFileInfo()
  19326. {
  19327. OwnedRoxieString indexName(indexHelper.getFileName());
  19328. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19329. if (varFileInfo)
  19330. {
  19331. translators.setown(new TranslatorArray) ;
  19332. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19333. }
  19334. variableInfoPending = false;
  19335. }
  19336. public:
  19337. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19338. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19339. : CRoxieServerActivity(_factory, _probeManager),
  19340. keySet(_keySet),
  19341. translators(_translators),
  19342. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  19343. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  19344. remoteId(_remoteId),
  19345. sorted(_sorted),
  19346. isLocal(_isLocal)
  19347. {
  19348. indexHelper.setCallback(&callback);
  19349. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19350. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19351. variableInfoPending = false;
  19352. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  19353. seekGEOffset = 0;
  19354. // started = false;
  19355. rejected = accepted = 0;
  19356. rowLimit = choosenLimit = keyedLimit = 0;
  19357. }
  19358. virtual const IResolvedFile *queryVarFileInfo() const
  19359. {
  19360. return varFileInfo;
  19361. }
  19362. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  19363. {
  19364. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  19365. remote.onCreate(this, this, _ctx, _colocalParent);
  19366. }
  19367. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19368. {
  19369. accepted = 0;
  19370. rejected = 0;
  19371. rowLimit = (unsigned __int64) -1;
  19372. keyedLimit = (unsigned __int64 ) -1;
  19373. choosenLimit = I64C(0x7fffffffffffffff);
  19374. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19375. remote.onStart(parentExtractSize, parentExtract);
  19376. variableInfoPending = variableFileName;
  19377. }
  19378. void processAllKeys()
  19379. {
  19380. try
  19381. {
  19382. if (indexHelper.canMatchAny())
  19383. {
  19384. if (variableInfoPending)
  19385. setVariableFileInfo();
  19386. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  19387. if (keySet)
  19388. {
  19389. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  19390. // 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
  19391. // However order is probably better to iterate fileno's inside partnos
  19392. // MORE - also not properly supporting STEPPED I fear.
  19393. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  19394. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  19395. {
  19396. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  19397. if (thisBase)
  19398. {
  19399. unsigned fileNo = 0;
  19400. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  19401. if (!thisKey->isTopLevelKey())
  19402. {
  19403. if (keyedLimit != (unsigned __int64) -1)
  19404. {
  19405. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19406. {
  19407. Owned<IKeyManager> countKey;
  19408. countKey.setown(createKeyManager(thisKey, 0, this));
  19409. countKey->setLayoutTranslator(translators->item(fileNo));
  19410. createSegmentMonitors(countKey);
  19411. unsigned __int64 count = countKey->checkCount(keyedLimit);
  19412. if (count > keyedLimit)
  19413. {
  19414. if (traceLevel > 4)
  19415. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19416. onLimitExceeded(true);
  19417. }
  19418. }
  19419. }
  19420. }
  19421. if (seekGEOffset && !thisKey->isTopLevelKey())
  19422. {
  19423. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  19424. }
  19425. else
  19426. {
  19427. tlk.setown(createKeyManager(thisKey, 0, this));
  19428. tlk->setLayoutTranslator(translators->item(fileNo));
  19429. }
  19430. createSegmentMonitors(tlk);
  19431. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19432. {
  19433. StringBuffer out;
  19434. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19435. CTXLOG("Using filter %s", out.str());
  19436. if (ctx->queryProbeManager())
  19437. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19438. }
  19439. tlk->reset();
  19440. loop // for each file part
  19441. {
  19442. //block for TransformCallbackAssociation
  19443. {
  19444. TransformCallbackAssociation associate(callback, tlk);
  19445. if (thisKey->isTopLevelKey())
  19446. {
  19447. if (thisKey->isFullySorted())
  19448. {
  19449. while (tlk->lookup(false))
  19450. {
  19451. unsigned slavePart = (unsigned) tlk->queryFpos();
  19452. if (slavePart)
  19453. {
  19454. accepted++;
  19455. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  19456. if (sorted && numChannels>1)
  19457. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  19458. }
  19459. }
  19460. }
  19461. else
  19462. {
  19463. // MORE - we could check whether there are any matching parts if we wanted.
  19464. // If people are in the habit of sending null values that would be worthwhile
  19465. remote.getMem(0, fileNo, 0);
  19466. }
  19467. }
  19468. else
  19469. {
  19470. if (processSingleKey(thisKey, translators->item(fileNo)))
  19471. break;
  19472. }
  19473. }
  19474. if (++fileNo < thisBase->numParts())
  19475. {
  19476. thisKey = thisBase->queryPart(fileNo);
  19477. tlk->setKey(thisKey);
  19478. tlk->setLayoutTranslator(translators->item(fileNo));
  19479. tlk->reset();
  19480. }
  19481. else
  19482. break;
  19483. }
  19484. tlk->releaseSegmentMonitors();
  19485. tlk->setKey(NULL);
  19486. }
  19487. }
  19488. }
  19489. }
  19490. remote.flush();
  19491. remote.senddone();
  19492. }
  19493. catch (IException *E)
  19494. {
  19495. remote.setException(E);
  19496. }
  19497. }
  19498. virtual void createSegmentMonitors(IKeyManager *key)
  19499. {
  19500. indexHelper.createSegmentMonitors(key);
  19501. key->finishSegmentMonitors();
  19502. }
  19503. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  19504. virtual void reset()
  19505. {
  19506. if (accepted)
  19507. noteStatistic(StNumIndexAccepted, accepted);
  19508. if (rejected)
  19509. noteStatistic(StNumIndexRejected, rejected);
  19510. remote.onReset();
  19511. CRoxieServerActivity::reset();
  19512. if (varFileInfo)
  19513. {
  19514. keySet.clear();
  19515. varFileInfo.clear();
  19516. }
  19517. variableInfoPending = false;
  19518. }
  19519. virtual void stop(bool aborting)
  19520. {
  19521. remote.onStop(aborting);
  19522. CRoxieServerActivity::stop(aborting);
  19523. }
  19524. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19525. {
  19526. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19527. }
  19528. };
  19529. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  19530. {
  19531. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19532. public:
  19533. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19534. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19535. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  19536. {
  19537. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19538. }
  19539. virtual void reset()
  19540. {
  19541. remote.onReset();
  19542. CRoxieServerIndexActivity::reset();
  19543. }
  19544. virtual const void *nextInGroup()
  19545. {
  19546. ActivityTimer t(totalCycles, timeActivities);
  19547. try
  19548. {
  19549. const void *ret = remote.nextInGroup();
  19550. if (ret)
  19551. processed++;
  19552. return ret;
  19553. }
  19554. catch (IException *E)
  19555. {
  19556. throw makeWrappedException(E);
  19557. }
  19558. }
  19559. protected:
  19560. virtual const void * createLimitFailRow(bool isKeyed)
  19561. {
  19562. createRowAllocator();
  19563. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19564. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19565. if (outSize)
  19566. return rowBuilder.finalizeRowClear(outSize);
  19567. return NULL;
  19568. }
  19569. };
  19570. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  19571. {
  19572. protected:
  19573. IHThorCompoundReadExtra & readHelper;
  19574. ISteppingMeta *rawMeta;
  19575. CSteppingMeta steppingMeta;
  19576. unsigned * seekSizes;
  19577. bool optimizeSteppedPostFilter;
  19578. ISteppingMeta * projectedMeta;
  19579. unsigned maxSeekLookahead;
  19580. public:
  19581. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19582. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  19583. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  19584. readHelper((IHThorIndexReadArg &)basehelper)
  19585. {
  19586. rawMeta = readHelper.queryRawSteppingMeta();
  19587. unsigned flags = indexHelper.getFlags();
  19588. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19589. seekSizes = NULL;
  19590. maxSeekLookahead = _maxSeekLookahead;
  19591. if (rawMeta)
  19592. {
  19593. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19594. unsigned maxFields = rawMeta->getNumFields();
  19595. seekGEOffset = fields[0].offset;
  19596. seekSizes = new unsigned[maxFields];
  19597. seekSizes[0] = fields[0].size;
  19598. for (unsigned i=1; i < maxFields; i++)
  19599. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19600. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19601. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  19602. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  19603. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19604. steppingMeta.init(useMeta, hasPostFilter);
  19605. }
  19606. }
  19607. ~CRoxieServerIndexReadActivity()
  19608. {
  19609. delete [] seekSizes;
  19610. }
  19611. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19612. {
  19613. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19614. steppingMeta.setDistributed();
  19615. if (steppedExtra)
  19616. steppingMeta.setExtra(steppedExtra);
  19617. rowLimit = readHelper.getRowLimit();
  19618. keyedLimit = readHelper.getKeyedLimit();
  19619. choosenLimit = readHelper.getChooseNLimit();
  19620. if (!paused)
  19621. processAllKeys();
  19622. }
  19623. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  19624. {
  19625. public:
  19626. IMPLEMENT_IINTERFACE;
  19627. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  19628. {
  19629. Link();
  19630. return const_cast<LazyLocalKeyReader*> (this);
  19631. }
  19632. virtual const void *getMessageHeader(unsigned &length) const
  19633. {
  19634. length = 0;
  19635. return NULL;
  19636. }
  19637. virtual const void *getMessageMetadata(unsigned &length) const
  19638. {
  19639. length = 0;
  19640. return NULL;
  19641. }
  19642. virtual void discard() const
  19643. {
  19644. // nothing to do.
  19645. }
  19646. unsigned keyedCount;
  19647. unsigned matched;
  19648. bool EOFseen;
  19649. Owned<IKeyIndexSet> keySet;
  19650. Owned<IKeyManager> tlk;
  19651. CRoxieServerIndexReadActivity &owner;
  19652. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19653. : owner(_owner)
  19654. {
  19655. keyedCount = 0;
  19656. matched = 0;
  19657. EOFseen = false;
  19658. keySet.setown(createKeyIndexSet());
  19659. keySet->addIndex(LINK(key));
  19660. if (owner.seekGEOffset)
  19661. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19662. else
  19663. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19664. tlk->setLayoutTranslator(trans);
  19665. owner.indexHelper.createSegmentMonitors(tlk);
  19666. tlk->finishSegmentMonitors();
  19667. tlk->reset();
  19668. }
  19669. virtual const void *getNext(int length)
  19670. {
  19671. TransformCallbackAssociation associate(owner.callback, tlk);
  19672. while (tlk->lookup(true))
  19673. {
  19674. keyedCount++;
  19675. if (keyedCount > owner.keyedLimit)
  19676. {
  19677. owner.onLimitExceeded(true); // Should throw exception
  19678. throwUnexpected();
  19679. }
  19680. size32_t transformedSize;
  19681. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19682. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19683. try
  19684. {
  19685. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19686. owner.callback.finishedRow();
  19687. }
  19688. catch (IException *E)
  19689. {
  19690. throw owner.makeWrappedException(E);
  19691. }
  19692. if (transformedSize)
  19693. {
  19694. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19695. matched++;
  19696. if (matched > owner.rowLimit)
  19697. {
  19698. owner.onLimitExceeded(false); // Should throw exception
  19699. throwUnexpected();
  19700. }
  19701. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19702. {
  19703. break;
  19704. }
  19705. owner.accepted++;
  19706. return result.getClear();
  19707. }
  19708. else
  19709. owner.rejected++;
  19710. }
  19711. EOFseen = true;
  19712. return NULL;
  19713. }
  19714. virtual bool atEOF() const
  19715. {
  19716. return EOFseen;
  19717. }
  19718. virtual bool isSerialized() const
  19719. {
  19720. return false;
  19721. }
  19722. };
  19723. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19724. {
  19725. createRowAllocator();
  19726. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19727. return false;
  19728. }
  19729. virtual void onLimitExceeded(bool isKeyed)
  19730. {
  19731. if (traceLevel > 4)
  19732. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19733. if (isKeyed)
  19734. {
  19735. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19736. {
  19737. if (ctx->queryDebugContext())
  19738. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19739. throw makeLimitSkipException(true);
  19740. }
  19741. else
  19742. readHelper.onKeyedLimitExceeded();
  19743. }
  19744. else
  19745. {
  19746. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19747. {
  19748. if (ctx->queryDebugContext())
  19749. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19750. throw makeLimitSkipException(false);
  19751. }
  19752. else
  19753. readHelper.onLimitExceeded();
  19754. }
  19755. }
  19756. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19757. {
  19758. out.append((unsigned short) numFields);
  19759. out.append((unsigned short) seekLen);
  19760. out.append((unsigned short) stepExtra.queryFlags());
  19761. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19762. if (seeks)
  19763. {
  19764. unsigned lookahead = 40000/seekLen;
  19765. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19766. lookahead = maxSeekLookahead;
  19767. seeks->ensureFilled(seek, numFields, lookahead);
  19768. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19769. unsigned serialized = 1; // rawseek is always serialized...
  19770. unsigned patchLength = out.length();
  19771. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19772. out.append(seekLen, rawSeek);
  19773. if (seeks->ordinality())
  19774. {
  19775. const void *lastSeek = rawSeek;
  19776. byte *nextSeek = NULL;
  19777. if (projectedMeta)
  19778. nextSeek = (byte *) alloca(seekLen);
  19779. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19780. {
  19781. if (projectedMeta)
  19782. {
  19783. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19784. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19785. }
  19786. else
  19787. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19788. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19789. if (diff > 0)
  19790. {
  19791. serialized++;
  19792. out.append(seekLen, nextSeek);
  19793. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19794. }
  19795. }
  19796. unsigned length = out.length();
  19797. out.setWritePos(patchLength);
  19798. out.append(serialized);
  19799. out.setWritePos(length);
  19800. }
  19801. }
  19802. else
  19803. {
  19804. out.append(false);
  19805. out.append(1);
  19806. out.append(seekLen, rawSeek);
  19807. }
  19808. }
  19809. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19810. {
  19811. ActivityTimer t(totalCycles, timeActivities);
  19812. try
  19813. {
  19814. unsigned seeklen = 0;
  19815. const void *rawSeek = NULL;
  19816. if (seek && numFields)
  19817. {
  19818. seeklen = seekSizes[numFields-1];
  19819. rawSeek = (const byte *)seek + seekGEOffset;
  19820. if (projectedMeta)
  19821. {
  19822. byte * temp = (byte *) alloca(seeklen);
  19823. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19824. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19825. rawSeek = (byte *)temp;
  19826. }
  19827. }
  19828. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19829. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19830. processed++;
  19831. return ret;
  19832. }
  19833. catch (IException *E)
  19834. {
  19835. throw makeWrappedException(E);
  19836. }
  19837. }
  19838. virtual IInputSteppingMeta * querySteppingMeta()
  19839. {
  19840. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19841. return &steppingMeta;
  19842. return NULL;
  19843. }
  19844. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19845. {
  19846. if (variableInfoPending)
  19847. setVariableFileInfo();
  19848. return this;
  19849. }
  19850. virtual IKeyArray *getKeySet() const
  19851. {
  19852. return keySet.getLink();
  19853. }
  19854. virtual const IResolvedFile *getVarFileInfo() const
  19855. {
  19856. return varFileInfo.getLink();
  19857. }
  19858. virtual TranslatorArray *getTranslators() const
  19859. {
  19860. return translators.getLink();
  19861. }
  19862. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19863. {
  19864. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19865. }
  19866. virtual IRoxieServerActivity *queryActivity() { return this; }
  19867. virtual const RemoteActivityId& queryRemoteId() const
  19868. {
  19869. return remoteId;
  19870. }
  19871. };
  19872. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19873. {
  19874. IHThorCompoundReadExtra & readHelper;
  19875. IHThorIndexReadBaseArg & indexHelper;
  19876. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19877. IHThorSteppedSourceExtra * steppedExtra;
  19878. bool eof;
  19879. Linked<IKeyArray>keySet;
  19880. Owned<IKeyIndexSet>keyIndexSet;
  19881. Owned<IKeyManager> tlk;
  19882. Linked<TranslatorArray> translators;
  19883. CIndexTransformCallback callback;
  19884. unsigned __int64 keyedLimit;
  19885. unsigned rowLimit;
  19886. unsigned chooseNLimit;
  19887. unsigned accepted;
  19888. unsigned rejected;
  19889. unsigned keyedCount;
  19890. ISteppingMeta * rawMeta;
  19891. ISteppingMeta * projectedMeta;
  19892. size32_t seekGEOffset;
  19893. unsigned * seekSizes;
  19894. CSteppingMeta steppingMeta;
  19895. Owned<const IResolvedFile> varFileInfo;
  19896. const RemoteActivityId &remoteId;
  19897. bool firstRead;
  19898. bool variableFileName;
  19899. bool variableInfoPending;
  19900. bool isOpt;
  19901. bool isLocal;
  19902. bool optimizeSteppedPostFilter;
  19903. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19904. void initKeySet()
  19905. {
  19906. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19907. {
  19908. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19909. }
  19910. keyIndexSet.setown(createKeyIndexSet());
  19911. for (unsigned part = 0; part < keySet->length(); part++)
  19912. {
  19913. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19914. if (kib)
  19915. {
  19916. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19917. {
  19918. IKeyIndex *k = kib->queryPart(subpart);
  19919. if (k)
  19920. {
  19921. assertex(!k->isTopLevelKey());
  19922. keyIndexSet->addIndex(LINK(k));
  19923. }
  19924. }
  19925. }
  19926. }
  19927. }
  19928. void setVariableFileInfo()
  19929. {
  19930. OwnedRoxieString indexName(indexHelper.getFileName());
  19931. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19932. translators.setown(new TranslatorArray) ;
  19933. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19934. initKeySet();
  19935. variableInfoPending = false;
  19936. }
  19937. void onEOF()
  19938. {
  19939. callback.setManager(NULL);
  19940. eof = true;
  19941. tlk.clear();
  19942. }
  19943. public:
  19944. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19945. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19946. : CRoxieServerActivity(_factory, _probeManager),
  19947. readHelper((IHThorIndexReadArg &)basehelper),
  19948. indexHelper((IHThorIndexReadArg &)basehelper),
  19949. translators(_translatorArray),
  19950. keySet(_keyArray),
  19951. isLocal(_isLocal),
  19952. remoteId(_remoteId)
  19953. {
  19954. rowLimit = 0;
  19955. keyedLimit = 0;
  19956. chooseNLimit = 0;
  19957. indexHelper.setCallback(&callback);
  19958. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19959. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19960. unsigned flags = indexHelper.getFlags();
  19961. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19962. variableInfoPending = false;
  19963. isOpt = (flags & TIRoptional) != 0;
  19964. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19965. firstRead = true;
  19966. accepted = 0;
  19967. rejected = 0;
  19968. keyedCount = 0;
  19969. eof = false;
  19970. rawMeta = readHelper.queryRawSteppingMeta();
  19971. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19972. seekGEOffset = 0;
  19973. seekSizes = NULL;
  19974. if (rawMeta)
  19975. {
  19976. // MORE - should check all keys in maxFields list can actually be keyed.
  19977. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19978. unsigned maxFields = rawMeta->getNumFields();
  19979. seekGEOffset = fields[0].offset;
  19980. seekSizes = new unsigned[maxFields];
  19981. seekSizes[0] = fields[0].size;
  19982. for (unsigned i=1; i < maxFields; i++)
  19983. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19984. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19985. if (projectedMeta)
  19986. steppingMeta.init(projectedMeta, hasPostFilter);
  19987. else
  19988. steppingMeta.init(rawMeta, hasPostFilter);
  19989. }
  19990. }
  19991. virtual const IResolvedFile *queryVarFileInfo() const
  19992. {
  19993. return varFileInfo;
  19994. }
  19995. ~CRoxieServerSimpleIndexReadActivity()
  19996. {
  19997. delete [] seekSizes;
  19998. }
  19999. virtual bool needsAllocator() const { return true; }
  20000. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20001. {
  20002. firstRead = true;
  20003. accepted = 0;
  20004. rejected = 0;
  20005. keyedCount = 0;
  20006. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20007. if (steppedExtra)
  20008. steppingMeta.setExtra(steppedExtra);
  20009. eof = !indexHelper.canMatchAny();
  20010. if (variableFileName)
  20011. variableInfoPending = true;
  20012. else
  20013. {
  20014. variableInfoPending = false;
  20015. if (!keyIndexSet)
  20016. initKeySet();
  20017. }
  20018. }
  20019. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20020. {
  20021. if (variableInfoPending)
  20022. setVariableFileInfo();
  20023. return this;
  20024. }
  20025. virtual IKeyArray *getKeySet() const
  20026. {
  20027. return keySet.getLink();
  20028. }
  20029. virtual const IResolvedFile *getVarFileInfo() const
  20030. {
  20031. return varFileInfo.getLink();
  20032. }
  20033. virtual TranslatorArray *getTranslators() const
  20034. {
  20035. return translators.getLink();
  20036. }
  20037. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20038. {
  20039. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20040. }
  20041. virtual IRoxieServerActivity *queryActivity() { return this; }
  20042. virtual const RemoteActivityId& queryRemoteId() const
  20043. {
  20044. return remoteId;
  20045. }
  20046. const void *nextInGroup()
  20047. {
  20048. bool matched = true;
  20049. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  20050. }
  20051. unsigned __int64 checkCount(unsigned __int64 limit)
  20052. {
  20053. unsigned numParts = keyIndexSet->numParts();
  20054. unsigned __int64 result = 0;
  20055. for (unsigned i = 0; i < numParts; i++)
  20056. {
  20057. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20058. countTlk->setLayoutTranslator(translators->item(i));
  20059. indexHelper.createSegmentMonitors(countTlk);
  20060. countTlk->finishSegmentMonitors();
  20061. result += countTlk->checkCount(limit-result);
  20062. if (result > limit)
  20063. break;
  20064. }
  20065. return result;
  20066. }
  20067. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20068. {
  20069. ActivityTimer t(totalCycles, timeActivities);
  20070. if (eof)
  20071. return NULL;
  20072. if (firstRead)
  20073. {
  20074. if (variableInfoPending)
  20075. setVariableFileInfo();
  20076. rowLimit = (unsigned) readHelper.getRowLimit();
  20077. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20078. unsigned numParts = keyIndexSet->numParts();
  20079. if (!numParts)
  20080. {
  20081. onEOF();
  20082. return NULL;
  20083. }
  20084. if (numParts > 1 || seekGEOffset)
  20085. {
  20086. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20087. // note that we don't set up translator because we don't support it. If that ever changes...
  20088. }
  20089. else
  20090. {
  20091. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20092. tlk->setLayoutTranslator(translators->item(0));
  20093. }
  20094. indexHelper.createSegmentMonitors(tlk);
  20095. tlk->finishSegmentMonitors();
  20096. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20097. {
  20098. StringBuffer out;
  20099. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20100. CTXLOG("Using filter %s", out.str());
  20101. if (ctx->queryProbeManager())
  20102. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20103. }
  20104. tlk->reset();
  20105. callback.setManager(tlk);
  20106. keyedLimit = readHelper.getKeyedLimit();
  20107. if (keyedLimit != (unsigned __int64) -1)
  20108. {
  20109. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20110. {
  20111. unsigned __int64 count = checkCount(keyedLimit);
  20112. if (count > keyedLimit)
  20113. {
  20114. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20115. readHelper.onKeyedLimitExceeded();
  20116. const void * ret = NULL;
  20117. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20118. ret = createKeyedLimitOnFailRow();
  20119. onEOF();
  20120. return ret;
  20121. }
  20122. keyedLimit = (unsigned __int64) -1;
  20123. }
  20124. }
  20125. firstRead = false;
  20126. }
  20127. if (accepted == chooseNLimit)
  20128. {
  20129. onEOF();
  20130. return NULL;
  20131. }
  20132. const byte * rawSeek = NULL;
  20133. unsigned seekSize = 0;
  20134. if (seek)
  20135. {
  20136. seekSize = seekSizes[numFields-1];
  20137. rawSeek = (const byte *)seek + seekGEOffset;
  20138. if (projectedMeta)
  20139. {
  20140. byte *temp = (byte *) alloca(seekSize);
  20141. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20142. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20143. rawSeek = (byte *)temp;
  20144. }
  20145. #ifdef _DEBUG
  20146. // StringBuffer seekStr;
  20147. // for (unsigned i = 0; i < seekSize; i++)
  20148. // {
  20149. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  20150. // }
  20151. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  20152. #endif
  20153. }
  20154. const byte * originalRawSeek = rawSeek;
  20155. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20156. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  20157. {
  20158. checkAbort();
  20159. keyedCount++;
  20160. if (keyedCount > keyedLimit)
  20161. {
  20162. readHelper.onKeyedLimitExceeded();
  20163. break;
  20164. }
  20165. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  20166. #ifdef _DEBUG
  20167. // StringBuffer recstr;
  20168. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  20169. // for (unsigned i = 0; i < size; i++)
  20170. // {
  20171. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  20172. // }
  20173. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  20174. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  20175. assertex(!"smart seek failure");
  20176. #endif
  20177. size32_t transformedSize;
  20178. rowBuilder.ensureRow();
  20179. try
  20180. {
  20181. transformedSize = readHelper.transform(rowBuilder, keyRow);
  20182. //if the post filter causes a mismatch, and the stepping condition no longer matches
  20183. //then return a mismatch record - so the join code can start seeking on the other input.
  20184. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  20185. {
  20186. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  20187. {
  20188. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  20189. if (transformedSize != 0)
  20190. wasCompleteMatch = false;
  20191. }
  20192. }
  20193. callback.finishedRow();
  20194. }
  20195. catch (IException *E)
  20196. {
  20197. throw makeWrappedException(E);
  20198. }
  20199. if (transformedSize)
  20200. {
  20201. accepted++;
  20202. if (accepted > rowLimit)
  20203. {
  20204. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  20205. {
  20206. throwUnexpected(); // should not have used simple variant if maySkip set...
  20207. }
  20208. if (traceLevel > 4)
  20209. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20210. readHelper.onLimitExceeded();
  20211. break;
  20212. }
  20213. processed++;
  20214. #ifdef _DEBUG
  20215. // const byte *ret = (const byte *) out.get();
  20216. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  20217. // queryOutputMeta()->toXML(ret, xmlwrite);
  20218. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  20219. #endif
  20220. return rowBuilder.finalizeRowClear(transformedSize);
  20221. }
  20222. else
  20223. rejected++;
  20224. rawSeek = NULL;
  20225. }
  20226. onEOF();
  20227. return NULL;
  20228. }
  20229. virtual void reset()
  20230. {
  20231. onEOF();
  20232. if (accepted)
  20233. noteStatistic(StNumIndexAccepted, accepted);
  20234. if (rejected)
  20235. noteStatistic(StNumIndexRejected, rejected);
  20236. if (variableFileName)
  20237. {
  20238. varFileInfo.clear();
  20239. translators.clear();
  20240. }
  20241. variableInfoPending = false;
  20242. CRoxieServerActivity::reset();
  20243. }
  20244. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20245. {
  20246. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20247. }
  20248. virtual IInputSteppingMeta * querySteppingMeta()
  20249. {
  20250. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20251. return &steppingMeta;
  20252. return NULL;
  20253. }
  20254. protected:
  20255. const void * createKeyedLimitOnFailRow()
  20256. {
  20257. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20258. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  20259. if (outSize)
  20260. return rowBuilder.finalizeRowClear(outSize);
  20261. return NULL;
  20262. }
  20263. };
  20264. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20265. {
  20266. public:
  20267. Owned<IKeyArray> keySet;
  20268. Owned<TranslatorArray> translatorArray;
  20269. Owned<IDefRecordMeta> activityMeta;
  20270. RemoteActivityId remoteId;
  20271. bool isSimple;
  20272. bool isLocal;
  20273. bool maySkip;
  20274. bool sorted;
  20275. bool variableFileName;
  20276. bool enableFieldTranslation;
  20277. unsigned maxSeekLookahead;
  20278. Owned<const IResolvedFile> indexfile;
  20279. CRoxieServerSideCache *cache;
  20280. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20281. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20282. {
  20283. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20284. unsigned flags = indexHelper->getFlags();
  20285. sorted = (flags & TIRunordered) == 0;
  20286. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20287. rtlDataAttr indexLayoutMeta;
  20288. size32_t indexLayoutSize;
  20289. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  20290. assertex(indexLayoutSize==0);
  20291. MemoryBuffer m;
  20292. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  20293. activityMeta.setown(deserializeRecordMeta(m, true));
  20294. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  20295. translatorArray.setown(new TranslatorArray);
  20296. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20297. if (!variableFileName)
  20298. {
  20299. bool isOpt = (flags & TIRoptional) != 0;
  20300. OwnedRoxieString indexName(indexHelper->getFileName());
  20301. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20302. if (indexfile)
  20303. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  20304. }
  20305. isSimple = isLocal;
  20306. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20307. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20308. {
  20309. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20310. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20311. isSimple = true;
  20312. }
  20313. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20314. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20315. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20316. }
  20317. ~CRoxieServerBaseIndexActivityFactory()
  20318. {
  20319. delete cache;
  20320. }
  20321. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20322. {
  20323. if (indexfile)
  20324. addXrefFileInfo(reply, indexfile);
  20325. else
  20326. {
  20327. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20328. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20329. {
  20330. OwnedRoxieString indexName(indexHelper->getFileName());
  20331. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit());
  20332. if (temp)
  20333. addXrefFileInfo(reply, temp);
  20334. }
  20335. }
  20336. }
  20337. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20338. {
  20339. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20340. }
  20341. virtual IRoxieServerSideCache *queryServerSideCache() const
  20342. {
  20343. return cache;
  20344. }
  20345. virtual bool getEnableFieldTranslation() const
  20346. {
  20347. return enableFieldTranslation;
  20348. }
  20349. virtual IDefRecordMeta *queryActivityMeta() const
  20350. {
  20351. return activityMeta;
  20352. }
  20353. virtual const StatisticsMapping &queryStatsMapping() const
  20354. {
  20355. return indexStatistics;
  20356. }
  20357. };
  20358. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20359. {
  20360. public:
  20361. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20362. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20363. {
  20364. }
  20365. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20366. {
  20367. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20368. return new CRoxieServerNullActivity(this, _probeManager);
  20369. else if (isSimple && !maySkip)
  20370. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20371. else
  20372. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  20373. }
  20374. };
  20375. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20376. {
  20377. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20378. }
  20379. //--------------------------------------------------------------------------------------------------------------------------
  20380. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  20381. {
  20382. bool done;
  20383. public:
  20384. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20385. : CRoxieServerActivity(_factory, _probeManager)
  20386. {
  20387. done = false;
  20388. }
  20389. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20390. {
  20391. done = false;
  20392. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20393. }
  20394. virtual bool needsAllocator() const { return true; }
  20395. virtual const void *nextInGroup()
  20396. {
  20397. ActivityTimer t(totalCycles, timeActivities);
  20398. if (done) return NULL;
  20399. done = true;
  20400. size32_t rowSize = meta.getFixedSize();
  20401. void * nullRow = rowAllocator->createRow();
  20402. if (rowSize == 1)
  20403. *(byte *)nullRow = 0;
  20404. else
  20405. {
  20406. assertex(rowSize == sizeof(unsigned __int64));
  20407. *(unsigned __int64 *)nullRow = 0;
  20408. }
  20409. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  20410. }
  20411. };
  20412. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  20413. {
  20414. IHThorCompoundCountExtra & countHelper;
  20415. IHThorSourceCountLimit * limitHelper;
  20416. bool done;
  20417. public:
  20418. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20419. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20420. countHelper((IHThorIndexCountArg &)basehelper),
  20421. done(false)
  20422. {
  20423. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  20424. }
  20425. virtual bool needsAllocator() const { return true; }
  20426. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20427. {
  20428. done = false;
  20429. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20430. choosenLimit = countHelper.getChooseNLimit();
  20431. if (limitHelper)
  20432. {
  20433. rowLimit = limitHelper->getRowLimit();
  20434. keyedLimit = limitHelper->getKeyedLimit();
  20435. }
  20436. if (!paused)
  20437. processAllKeys();
  20438. }
  20439. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20440. {
  20441. unsigned __int64 count = 0;
  20442. if (countHelper.hasFilter())
  20443. {
  20444. while (tlk->lookup(true))
  20445. {
  20446. try
  20447. {
  20448. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  20449. callback.finishedRow();
  20450. }
  20451. catch (IException *E)
  20452. {
  20453. throw makeWrappedException(E);
  20454. }
  20455. accepted++;
  20456. if (count >= choosenLimit) // MORE - what about limit?
  20457. break;
  20458. }
  20459. }
  20460. else
  20461. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  20462. if (count)
  20463. {
  20464. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  20465. if (count > choosenLimit)
  20466. count = choosenLimit;
  20467. void * recBuffer = rowAllocator->createRow();
  20468. if (meta.getFixedSize() == 1)
  20469. *(byte *)recBuffer = (byte)count;
  20470. else
  20471. {
  20472. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20473. *(unsigned __int64 *)recBuffer = count;
  20474. }
  20475. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  20476. result->append(recBuffer);
  20477. remote.injectResult(result.getClear());
  20478. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  20479. if (count >= choosenLimit)
  20480. return true;
  20481. }
  20482. return false;
  20483. }
  20484. virtual void onLimitExceeded(bool isKeyed)
  20485. {
  20486. if (traceLevel > 4)
  20487. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20488. if (isKeyed)
  20489. {
  20490. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20491. {
  20492. if (ctx->queryDebugContext())
  20493. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20494. throw makeLimitSkipException(true);
  20495. }
  20496. else
  20497. {
  20498. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  20499. limitHelper->onKeyedLimitExceeded();
  20500. }
  20501. }
  20502. else
  20503. {
  20504. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20505. {
  20506. if (ctx->queryDebugContext())
  20507. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20508. throw makeLimitSkipException(false);
  20509. }
  20510. else
  20511. {
  20512. assertex(limitHelper);
  20513. limitHelper->onLimitExceeded();
  20514. }
  20515. }
  20516. }
  20517. virtual const void *createLimitFailRow(bool isKeyed)
  20518. {
  20519. throwUnexpected();
  20520. }
  20521. virtual const void *nextInGroup()
  20522. {
  20523. ActivityTimer t(totalCycles, timeActivities);
  20524. if (done) return NULL;
  20525. done = true;
  20526. unsigned __int64 totalCount = 0;
  20527. bool hasLimit = rowLimit != (unsigned __int64) -1;
  20528. try
  20529. {
  20530. loop
  20531. {
  20532. const void * next = remote.nextInGroup();
  20533. if (!next)
  20534. break;
  20535. if (meta.getFixedSize() == 1)
  20536. totalCount += *(byte *)next;
  20537. else
  20538. totalCount += *(unsigned __int64 *) next;
  20539. ReleaseRoxieRow(next);
  20540. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  20541. break;
  20542. }
  20543. if (totalCount > rowLimit)
  20544. {
  20545. unsigned flags = indexHelper.getFlags();
  20546. if (flags & TIRlimitskips)
  20547. totalCount = 0;
  20548. else if (flags & TIRlimitcreates)
  20549. totalCount = 1;
  20550. else
  20551. {
  20552. assertex(limitHelper);
  20553. limitHelper->onLimitExceeded();
  20554. }
  20555. }
  20556. else if (totalCount > choosenLimit)
  20557. totalCount = choosenLimit;
  20558. }
  20559. catch (IException *E)
  20560. {
  20561. if (QUERYINTERFACE(E, LimitSkipException))
  20562. {
  20563. totalCount = 0;
  20564. unsigned flags = indexHelper.getFlags();
  20565. if (E->errorCode() == KeyedLimitSkipErrorCode)
  20566. {
  20567. if (flags & TIRkeyedlimitcreates)
  20568. totalCount++;
  20569. }
  20570. else
  20571. {
  20572. if (flags & TIRlimitcreates)
  20573. totalCount++;
  20574. }
  20575. if (totalCount > choosenLimit)
  20576. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  20577. E->Release();
  20578. }
  20579. else
  20580. throw ;
  20581. }
  20582. void * result = rowAllocator->createRow();
  20583. if (meta.getFixedSize() == 1)
  20584. *(byte *)result = (byte)totalCount;
  20585. else
  20586. {
  20587. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20588. *(unsigned __int64 *)result = totalCount;
  20589. }
  20590. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  20591. }
  20592. };
  20593. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20594. {
  20595. public:
  20596. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20597. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20598. {
  20599. }
  20600. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20601. {
  20602. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20603. return new CRoxieServerNullCountActivity(this, _probeManager);
  20604. // else if (isSimple)
  20605. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20606. else
  20607. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20608. }
  20609. };
  20610. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20611. {
  20612. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20613. }
  20614. //--------------------------------------------------------------------------------------------------------------------------
  20615. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  20616. {
  20617. IHThorIndexAggregateArg &aggregateHelper;
  20618. bool done;
  20619. public:
  20620. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20621. : CRoxieServerActivity(_factory, _probeManager),
  20622. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  20623. {
  20624. done = false;
  20625. }
  20626. virtual bool needsAllocator() const { return true; }
  20627. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20628. {
  20629. done = false;
  20630. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20631. }
  20632. virtual const void *nextInGroup()
  20633. {
  20634. ActivityTimer t(totalCycles, timeActivities);
  20635. if (done) return NULL;
  20636. done = true;
  20637. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20638. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  20639. return rowBuilder.finalizeRowClear(thisSize);
  20640. }
  20641. };
  20642. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  20643. {
  20644. IHThorCompoundAggregateExtra & aggregateHelper;
  20645. bool done;
  20646. public:
  20647. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20648. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20649. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20650. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  20651. done(false)
  20652. {
  20653. }
  20654. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20655. {
  20656. done = false;
  20657. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20658. if (!paused)
  20659. processAllKeys();
  20660. }
  20661. virtual bool needsAllocator() const { return true; }
  20662. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20663. {
  20664. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20665. while (tlk->lookup(true))
  20666. {
  20667. if (!rowBuilder.exists())
  20668. {
  20669. rowBuilder.ensureRow();
  20670. aggregateHelper.clearAggregate(rowBuilder);
  20671. }
  20672. try
  20673. {
  20674. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20675. callback.finishedRow();
  20676. }
  20677. catch (IException *E)
  20678. {
  20679. throw makeWrappedException(E);
  20680. }
  20681. accepted++;
  20682. }
  20683. if (aggregateHelper.processedAnyRows())
  20684. {
  20685. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20686. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20687. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20688. result->append(recBuffer);
  20689. remote.injectResult(result.getClear());
  20690. }
  20691. return false;
  20692. }
  20693. virtual void onLimitExceeded(bool isKeyed)
  20694. {
  20695. if (traceLevel > 4)
  20696. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20697. throwUnexpected();
  20698. }
  20699. virtual const void *createLimitFailRow(bool isKeyed)
  20700. {
  20701. throwUnexpected();
  20702. }
  20703. const void * gatherMerged()
  20704. {
  20705. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20706. const void * firstRow = remote.nextInGroup();
  20707. size32_t finalSize = 0;
  20708. if (!firstRow)
  20709. {
  20710. rowBuilder.ensureRow();
  20711. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20712. }
  20713. else
  20714. {
  20715. // NOTE need to clone this because going to modify below, could special case 1 row only
  20716. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20717. ReleaseRoxieRow(firstRow);
  20718. }
  20719. loop
  20720. {
  20721. const void * next = remote.nextInGroup();
  20722. if (!next)
  20723. break;
  20724. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20725. ReleaseRoxieRow(next);
  20726. }
  20727. return rowBuilder.finalizeRowClear(finalSize);
  20728. }
  20729. virtual const void *nextInGroup()
  20730. {
  20731. ActivityTimer t(totalCycles, timeActivities);
  20732. if (done) return NULL;
  20733. const void * ret = gatherMerged();
  20734. done = true;
  20735. return ret;
  20736. }
  20737. };
  20738. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20739. {
  20740. public:
  20741. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20742. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20743. {
  20744. }
  20745. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20746. {
  20747. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20748. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20749. // else if (isSimple)
  20750. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20751. else
  20752. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20753. }
  20754. };
  20755. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20756. {
  20757. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20758. }
  20759. //--------------------------------------------------------------------------------------------------------------------------
  20760. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20761. {
  20762. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20763. RowAggregator singleAggregator;
  20764. RowAggregator resultAggregator;
  20765. unsigned groupSegCount;
  20766. bool gathered;
  20767. bool eof;
  20768. public:
  20769. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20770. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20771. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20772. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20773. singleAggregator(aggregateHelper, aggregateHelper),
  20774. resultAggregator(aggregateHelper, aggregateHelper),
  20775. gathered(false), eof(true)
  20776. {
  20777. groupSegCount = 0;
  20778. }
  20779. IMPLEMENT_IINTERFACE
  20780. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20781. {
  20782. eof = false;
  20783. gathered= false;
  20784. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20785. groupSegCount = 0;
  20786. if (!paused)
  20787. processAllKeys();
  20788. resultAggregator.start(rowAllocator);
  20789. }
  20790. virtual bool needsAllocator() const { return true; }
  20791. virtual void reset()
  20792. {
  20793. resultAggregator.reset();
  20794. CRoxieServerIndexActivity::reset();
  20795. }
  20796. virtual void processRow(const void * next)
  20797. {
  20798. singleAggregator.addRow(next);
  20799. }
  20800. virtual void createSegmentMonitors(IKeyManager *key)
  20801. {
  20802. unsigned groupSegSize;
  20803. ThorActivityKind kind = factory->getKind();
  20804. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20805. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20806. else
  20807. groupSegSize = 0;
  20808. if (groupSegSize)
  20809. {
  20810. key->setMergeBarrier(groupSegSize);
  20811. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20812. unsigned numSegs = tlk->ordinality();
  20813. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20814. {
  20815. IKeySegmentMonitor *seg = tlk->item(segNo);
  20816. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20817. {
  20818. groupSegCount = segNo+1;
  20819. break;
  20820. }
  20821. }
  20822. assertex(groupSegCount);
  20823. }
  20824. else
  20825. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20826. }
  20827. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20828. {
  20829. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20830. singleAggregator.start(rowAllocator);
  20831. ThorActivityKind kind = factory->getKind();
  20832. while (tlk->lookup(true))
  20833. {
  20834. try
  20835. {
  20836. if (groupSegCount && !trans)
  20837. {
  20838. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20839. callback.finishedRow();
  20840. if (kind==TAKindexgroupcount)
  20841. {
  20842. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20843. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20844. }
  20845. if (!tlk->nextRange(groupSegCount))
  20846. break;
  20847. }
  20848. else
  20849. {
  20850. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20851. callback.finishedRow();
  20852. }
  20853. }
  20854. catch (IException *E)
  20855. {
  20856. throw makeWrappedException(E);
  20857. }
  20858. accepted++;
  20859. }
  20860. loop
  20861. {
  20862. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20863. if (!next)
  20864. break;
  20865. size32_t size = next->querySize();
  20866. result->append(next->finalizeRowClear());
  20867. }
  20868. remote.injectResult(result.getClear());
  20869. singleAggregator.reset();
  20870. return false;
  20871. }
  20872. virtual void onLimitExceeded(bool isKeyed)
  20873. {
  20874. if (traceLevel > 4)
  20875. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20876. throwUnexpected();
  20877. }
  20878. virtual const void *createLimitFailRow(bool isKeyed)
  20879. {
  20880. throwUnexpected();
  20881. }
  20882. void gatherMerged()
  20883. {
  20884. gathered = true;
  20885. loop
  20886. {
  20887. const void * next = remote.nextInGroup();
  20888. if (!next)
  20889. break;
  20890. resultAggregator.mergeElement(next);
  20891. ReleaseRoxieRow(next);
  20892. }
  20893. }
  20894. virtual const void *nextInGroup()
  20895. {
  20896. ActivityTimer t(totalCycles, timeActivities);
  20897. if (eof)
  20898. return NULL;
  20899. if (!gathered)
  20900. gatherMerged();
  20901. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20902. if (next)
  20903. {
  20904. processed++;
  20905. return next->finalizeRowClear();
  20906. }
  20907. eof = true;
  20908. return NULL;
  20909. }
  20910. };
  20911. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20912. {
  20913. public:
  20914. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20915. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20916. {
  20917. }
  20918. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20919. {
  20920. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20921. return new CRoxieServerNullActivity(this, _probeManager);
  20922. // else if (isSimple)
  20923. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20924. else
  20925. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20926. }
  20927. };
  20928. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20929. {
  20930. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20931. }
  20932. //--------------------------------------------------------------------------------------------------------------------------
  20933. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20934. {
  20935. IHThorCompoundNormalizeExtra & readHelper;
  20936. public:
  20937. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20938. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20939. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20940. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20941. {
  20942. }
  20943. virtual bool needsAllocator() const { return true; }
  20944. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20945. {
  20946. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20947. rowLimit = readHelper.getRowLimit();
  20948. keyedLimit = readHelper.getKeyedLimit();
  20949. choosenLimit = readHelper.getChooseNLimit();
  20950. if (!paused)
  20951. processAllKeys();
  20952. }
  20953. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20954. {
  20955. unsigned keyedCount = 0;
  20956. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20957. while (tlk->lookup(true))
  20958. {
  20959. keyedCount++;
  20960. if (keyedCount > keyedLimit)
  20961. {
  20962. if (traceLevel > 4)
  20963. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20964. onLimitExceeded(true);
  20965. break;
  20966. }
  20967. size32_t transformedSize;
  20968. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20969. {
  20970. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20971. do
  20972. {
  20973. if (accepted>=choosenLimit)
  20974. break;
  20975. rowBuilder.ensureRow();
  20976. try
  20977. {
  20978. transformedSize = readHelper.transform(rowBuilder);
  20979. }
  20980. catch (IException *E)
  20981. {
  20982. throw makeWrappedException(E);
  20983. }
  20984. if (transformedSize)
  20985. {
  20986. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20987. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20988. accepted++;
  20989. }
  20990. else
  20991. rejected++;
  20992. } while (readHelper.next());
  20993. remote.injectResult(result.getClear());
  20994. callback.finishedRow();
  20995. if (accepted>=choosenLimit)
  20996. return true;
  20997. }
  20998. }
  20999. return false;
  21000. }
  21001. virtual void onLimitExceeded(bool isKeyed)
  21002. {
  21003. if (traceLevel > 4)
  21004. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21005. if (isKeyed)
  21006. {
  21007. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21008. {
  21009. if (ctx->queryDebugContext())
  21010. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21011. throw makeLimitSkipException(true);
  21012. }
  21013. else
  21014. readHelper.onKeyedLimitExceeded();
  21015. }
  21016. else
  21017. {
  21018. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21019. {
  21020. if (ctx->queryDebugContext())
  21021. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21022. throw makeLimitSkipException(false);
  21023. }
  21024. else
  21025. readHelper.onLimitExceeded();
  21026. }
  21027. }
  21028. virtual const void *createLimitFailRow(bool isKeyed)
  21029. {
  21030. UNIMPLEMENTED;
  21031. }
  21032. };
  21033. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21034. {
  21035. public:
  21036. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21037. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  21038. {
  21039. }
  21040. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21041. {
  21042. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21043. return new CRoxieServerNullActivity(this, _probeManager);
  21044. else
  21045. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21046. }
  21047. };
  21048. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21049. {
  21050. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21051. }
  21052. //=================================================================================
  21053. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21054. {
  21055. IHThorFetchBaseArg &helper;
  21056. IHThorFetchContext * fetchContext;
  21057. Linked<IFilePartMap> map;
  21058. CRemoteResultAdaptor remote;
  21059. RecordPullerThread puller;
  21060. bool needsRHS;
  21061. bool variableFileName;
  21062. bool isOpt;
  21063. Owned<const IResolvedFile> varFileInfo;
  21064. public:
  21065. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21066. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21067. {
  21068. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21069. needsRHS = helper.transformNeedsRhs();
  21070. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21071. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21072. }
  21073. virtual const IResolvedFile *queryVarFileInfo() const
  21074. {
  21075. return varFileInfo;
  21076. }
  21077. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21078. {
  21079. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21080. remote.onCreate(this, this, _ctx, _colocalParent);
  21081. }
  21082. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21083. {
  21084. if (idx)
  21085. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21086. puller.setInput(this, _in);
  21087. }
  21088. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21089. {
  21090. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21091. remote.onStart(parentExtractSize, parentExtract);
  21092. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21093. if (variableFileName)
  21094. {
  21095. OwnedRoxieString fname(fetchContext->getFileName());
  21096. varFileInfo.setown(resolveLFN(fname, isOpt));
  21097. if (varFileInfo)
  21098. map.setown(varFileInfo->getFileMap());
  21099. }
  21100. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21101. }
  21102. virtual void stop(bool aborting)
  21103. {
  21104. // Called from remote, so no need to call back to it....
  21105. puller.stop(aborting);
  21106. CRoxieServerActivity::stop(aborting);
  21107. }
  21108. virtual void reset()
  21109. {
  21110. processed = remote.processed;
  21111. remote.processed = 0;
  21112. puller.reset();
  21113. if (variableFileName)
  21114. {
  21115. varFileInfo.clear();
  21116. map.clear();
  21117. }
  21118. CRoxieServerActivity::reset();
  21119. }
  21120. virtual IRoxieInput *queryOutput(unsigned idx)
  21121. {
  21122. if (idx==(unsigned)-1)
  21123. idx = 0;
  21124. return idx ? NULL : &remote;
  21125. }
  21126. virtual void processRow(const void *row)
  21127. {
  21128. // called from puller thread
  21129. offset_t rp = fetchContext->extractPosition(row);
  21130. unsigned partNo;
  21131. if (isLocalFpos(rp))
  21132. partNo = getLocalFposPart(rp) + 1;
  21133. else
  21134. partNo = map->mapOffset(rp);
  21135. if (needsRHS)
  21136. {
  21137. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  21138. RtlDynamicRowBuilder rb(extractAllocator, true);
  21139. unsigned rhsSize = helper.extractJoinFields(rb, row);
  21140. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  21141. *(offset_t *) block = rp;
  21142. block += sizeof(rp);
  21143. *(unsigned *) block = rhsSize;
  21144. block += sizeof(rhsSize);
  21145. memcpy(block, rb.row(), rhsSize);
  21146. }
  21147. else
  21148. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  21149. ReleaseRoxieRow(row);
  21150. }
  21151. void processEOG()
  21152. {
  21153. #ifdef FETCH_PRESERVES_GROUPING
  21154. UNIMPLEMENTED;
  21155. #endif
  21156. // else discard is correct
  21157. }
  21158. void processGroup(const ConstPointerArray &)
  21159. {
  21160. throwUnexpected();
  21161. }
  21162. void processDone()
  21163. {
  21164. // called from puller thread
  21165. remote.flush();
  21166. remote.senddone();
  21167. }
  21168. virtual bool fireException(IException *e)
  21169. {
  21170. return remote.fireException(e);
  21171. }
  21172. virtual void onLimitExceeded(bool isKeyed)
  21173. {
  21174. if (traceLevel > 4)
  21175. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21176. if (isKeyed)
  21177. throwUnexpected();
  21178. helper.onLimitExceeded();
  21179. }
  21180. virtual const void *createLimitFailRow(bool isKeyed)
  21181. {
  21182. UNIMPLEMENTED;
  21183. }
  21184. virtual const void *nextInGroup()
  21185. {
  21186. throwUnexpected(); // I am nobody's input
  21187. }
  21188. };
  21189. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  21190. {
  21191. RemoteActivityId remoteId;
  21192. Owned<IFilePartMap> map;
  21193. bool variableFileName;
  21194. Owned<const IResolvedFile> datafile;
  21195. public:
  21196. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21197. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  21198. {
  21199. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21200. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21201. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21202. if (!variableFileName)
  21203. {
  21204. OwnedRoxieString fname(fetchContext->getFileName());
  21205. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  21206. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  21207. true, true,
  21208. _queryFactory.queryWorkUnit()));
  21209. if (datafile)
  21210. map.setown(datafile->getFileMap());
  21211. }
  21212. }
  21213. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21214. {
  21215. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  21216. }
  21217. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21218. {
  21219. if (datafile)
  21220. addXrefFileInfo(reply, datafile);
  21221. else
  21222. {
  21223. // Temporarily resolve the file
  21224. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21225. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21226. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  21227. {
  21228. OwnedRoxieString fileName(fetchContext->getFileName());
  21229. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit());
  21230. if (temp)
  21231. addXrefFileInfo(reply, temp);
  21232. }
  21233. }
  21234. }
  21235. virtual const StatisticsMapping &queryStatsMapping() const
  21236. {
  21237. return diskStatistics;
  21238. }
  21239. };
  21240. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21241. {
  21242. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21243. }
  21244. // MORE - is there any point keeping this now?
  21245. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  21246. {
  21247. public:
  21248. Owned<const IResolvedFile> indexfile;
  21249. Owned<const IResolvedFile> datafile;
  21250. StringAttr fileName;
  21251. StringAttr indexName;
  21252. Owned<IKeyArray> keySet;
  21253. Owned<IFileIOArray> files;
  21254. TranslatorArray layoutTranslators;
  21255. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21256. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  21257. {
  21258. try // does not want any missing file errors to be fatal, or throw traps - just log it
  21259. {
  21260. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  21261. return; // ignore 'spills'
  21262. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21263. ThorActivityKind kind = getActivityKind(_graphNode);
  21264. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  21265. {
  21266. fileName.set(queryNodeFileName(_graphNode, kind));
  21267. indexName.set(queryNodeIndexName(_graphNode, kind));
  21268. if (indexName && !allFilesDynamic)
  21269. {
  21270. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  21271. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  21272. if (indexfile)
  21273. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  21274. }
  21275. if (fileName && !allFilesDynamic)
  21276. {
  21277. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  21278. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  21279. if (datafile)
  21280. {
  21281. if (isLocal)
  21282. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  21283. }
  21284. }
  21285. }
  21286. }
  21287. catch(IException *E)
  21288. {
  21289. StringBuffer errors;
  21290. E->errorMessage(errors);
  21291. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  21292. E->Release();
  21293. }
  21294. }
  21295. 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__); }
  21296. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21297. {
  21298. if (!allFilesDynamic)
  21299. {
  21300. if (datafile)
  21301. addXrefFileInfo(reply, datafile);
  21302. if (indexfile)
  21303. addXrefFileInfo(reply, indexfile);
  21304. }
  21305. else
  21306. {
  21307. Owned<const IResolvedFile> temp;
  21308. if (fileName.length())
  21309. {
  21310. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit()));
  21311. if (temp)
  21312. addXrefFileInfo(reply, temp);
  21313. }
  21314. if (indexName.length())
  21315. {
  21316. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit()));
  21317. if (temp)
  21318. addXrefFileInfo(reply, temp);
  21319. }
  21320. }
  21321. }
  21322. };
  21323. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21324. {
  21325. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  21326. }
  21327. //=====================================================================================================
  21328. // Keyed joins...
  21329. //
  21330. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  21331. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  21332. // 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
  21333. // the transform and returns rows that are created.
  21334. // 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)
  21335. //
  21336. //=====================================================================================================
  21337. class CJoinGroup;
  21338. interface IJoinProcessor
  21339. {
  21340. virtual void processEOG() = 0;
  21341. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  21342. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  21343. virtual bool fireException(IException *E) = 0;
  21344. virtual void processCompletedGroups() = 0;
  21345. };
  21346. //------------------------------------------------------------------------------------------------------
  21347. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  21348. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  21349. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  21350. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  21351. // per-query limits etc (Note that the pointer array block is not though).
  21352. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  21353. //
  21354. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  21355. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  21356. // initial count when created.
  21357. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  21358. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  21359. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  21360. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  21361. // remaining reference and the JoinGroup will be processed and destroyed.
  21362. //
  21363. //------------------------------------------------------------------------------------------------------
  21364. class CJoinGroup : public CInterface, implements IInterface
  21365. {
  21366. protected:
  21367. const void *left; // LHS row
  21368. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  21369. atomic_t endMarkersPending; // How many slave responses still waiting for
  21370. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  21371. unsigned lastPartNo;
  21372. unsigned pos;
  21373. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  21374. public:
  21375. #undef new
  21376. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  21377. {
  21378. return a->allocate(size, activityId);
  21379. }
  21380. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21381. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21382. #endif
  21383. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  21384. {
  21385. ReleaseRoxieRow(ptr);
  21386. }
  21387. void operator delete(void *ptr)
  21388. {
  21389. ReleaseRoxieRow(ptr);
  21390. }
  21391. public:
  21392. IMPLEMENT_IINTERFACE;
  21393. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  21394. {
  21395. #ifdef TRACE_JOINGROUPS
  21396. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  21397. #endif
  21398. candidates = 0;
  21399. lastPartNo = 0;
  21400. pos = 0;
  21401. left = _left;
  21402. groupStart = _groupStart;
  21403. if (_groupStart)
  21404. {
  21405. atomic_inc(&_groupStart->endMarkersPending);
  21406. }
  21407. atomic_set(&endMarkersPending, 1);
  21408. }
  21409. ~CJoinGroup()
  21410. {
  21411. #ifdef TRACE_JOINGROUPS
  21412. DBGLOG("Destroying joinGroup %p", this);
  21413. #endif
  21414. if (left)
  21415. {
  21416. ReleaseRoxieRow(left);
  21417. ForEachItemIn(idx, rows)
  21418. ReleaseRoxieRow(rows.item(idx));
  21419. rows.kill();
  21420. }
  21421. }
  21422. inline bool isHeadRecord() const
  21423. {
  21424. return left==NULL;
  21425. }
  21426. inline bool complete() const
  21427. {
  21428. return atomic_read(&endMarkersPending) == 0;
  21429. }
  21430. #ifdef TRACE_JOINGROUPS
  21431. inline void notePending(unsigned lineNo)
  21432. #else
  21433. inline void notePending()
  21434. #endif
  21435. {
  21436. assert(!complete());
  21437. atomic_inc(&endMarkersPending);
  21438. #ifdef TRACE_JOINGROUPS
  21439. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  21440. #endif
  21441. }
  21442. inline bool inGroup(CJoinGroup *leader) const
  21443. {
  21444. return groupStart==leader;
  21445. }
  21446. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  21447. {
  21448. // Single threaded by now
  21449. assert(complete());
  21450. return rows.item(idx);
  21451. }
  21452. #ifdef TRACE_JOINGROUPS
  21453. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  21454. #else
  21455. bool noteEndReceived(unsigned candidateCount)
  21456. #endif
  21457. {
  21458. assert(!complete());
  21459. if (candidateCount)
  21460. {
  21461. candidates += candidateCount;
  21462. }
  21463. #ifdef TRACE_JOINGROUPS
  21464. 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);
  21465. #endif
  21466. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  21467. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  21468. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  21469. CJoinGroup *localGroupStart = groupStart;
  21470. if (atomic_dec_and_test(&endMarkersPending))
  21471. {
  21472. if (localGroupStart)
  21473. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  21474. else
  21475. return true;
  21476. }
  21477. else
  21478. return false;
  21479. }
  21480. inline const void *queryLeft() const
  21481. {
  21482. return left;
  21483. }
  21484. void addRightMatch(KeyedJoinHeader *right)
  21485. {
  21486. assert(!complete());
  21487. unsigned short partNo = right->partNo;
  21488. if (partNo != lastPartNo)
  21489. {
  21490. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  21491. if (partNo > lastPartNo)
  21492. pos = rows.length();
  21493. while (pos>0)
  21494. {
  21495. if (rows.item(pos-1)->partNo <= partNo)
  21496. break;
  21497. pos--;
  21498. }
  21499. lastPartNo = partNo;
  21500. }
  21501. rows.add(right, pos);
  21502. pos++;
  21503. }
  21504. inline unsigned rowsSeen() const
  21505. {
  21506. assert(complete());
  21507. return rows.length();
  21508. }
  21509. inline unsigned candidateCount() const
  21510. {
  21511. assert(complete());
  21512. return candidates;
  21513. }
  21514. };
  21515. #ifdef TRACE_JOINGROUPS
  21516. #define notePending() notePending(__LINE__)
  21517. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  21518. #endif
  21519. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  21520. {
  21521. private:
  21522. SafeQueueOf<const void, true> ready;
  21523. public:
  21524. IHThorKeyedJoinArg &helper;
  21525. unsigned joinProcessed;
  21526. bool isFullKey;
  21527. bool eof;
  21528. bool isSimple;
  21529. bool allPulled;
  21530. ActivityTimeAccumulator totalCycles;
  21531. unsigned activityId;
  21532. RecordPullerThread &puller;
  21533. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  21534. Owned<IEngineRowAllocator> ccdRecordAllocator;
  21535. IJoinProcessor &processor;
  21536. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  21537. RecordPullerThread &_puller, IJoinProcessor &_processor)
  21538. : helper(_helper),
  21539. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  21540. isFullKey(_isFullKey),
  21541. isSimple(_isSimple),
  21542. puller(_puller),
  21543. processor(_processor),
  21544. activityId(_activity.queryId())
  21545. {
  21546. joinProcessed = 0;
  21547. allPulled = false;
  21548. eof = false;
  21549. }
  21550. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  21551. {
  21552. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  21553. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  21554. }
  21555. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21556. {
  21557. eof = false;
  21558. joinProcessed = 0;
  21559. totalCycles.totalCycles = 0;
  21560. allPulled = false;
  21561. assertex(ready.ordinality()==0);
  21562. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  21563. }
  21564. virtual void reset()
  21565. {
  21566. CRemoteResultAdaptor::reset();
  21567. while (ready.ordinality())
  21568. {
  21569. const void *goer = ready.dequeue();
  21570. if (goer)
  21571. ReleaseRoxieRow(goer);
  21572. }
  21573. while (injected.ordinality())
  21574. {
  21575. const void *goer = injected.dequeue();
  21576. if (goer)
  21577. ReleaseRoxieRow(goer);
  21578. }
  21579. }
  21580. inline void addResult(const void *row)
  21581. {
  21582. ready.enqueue(row);
  21583. }
  21584. virtual unsigned __int64 queryTotalCycles() const
  21585. {
  21586. return totalCycles.totalCycles;
  21587. }
  21588. virtual IOutputMetaData * queryOutputMeta() const
  21589. {
  21590. return owner->queryOutputMeta();
  21591. }
  21592. virtual const void *nextInGroup()
  21593. {
  21594. ActivityTimer t(totalCycles, timeActivities);
  21595. loop
  21596. {
  21597. if (eof)
  21598. return NULL;
  21599. processSlaveResults();
  21600. if (ready.ordinality())
  21601. {
  21602. const void *result = ready.dequeue();
  21603. if (result)
  21604. joinProcessed++;
  21605. return result;
  21606. }
  21607. else
  21608. eof = true;
  21609. }
  21610. }
  21611. private:
  21612. void processSlaveResults()
  21613. {
  21614. while (!ready.ordinality())
  21615. {
  21616. KeyedJoinHeader *fetchedData;
  21617. if (isSimple)
  21618. {
  21619. while (!allPulled && !injected.ordinality())
  21620. {
  21621. if (!puller.pullRecords(1))
  21622. {
  21623. puller.done();
  21624. allPulled = true;
  21625. }
  21626. }
  21627. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21628. }
  21629. else
  21630. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21631. if (fetchedData)
  21632. {
  21633. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21634. if (fetchedData->partNo == (unsigned short) -1)
  21635. {
  21636. #ifdef TRACE_JOINGROUPS
  21637. CTXLOG("Got end for group %p", thisGroup);
  21638. #endif
  21639. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21640. ReleaseRoxieRow(fetchedData);
  21641. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21642. }
  21643. else
  21644. {
  21645. #ifdef TRACE_JOINGROUPS
  21646. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21647. #endif
  21648. thisGroup->addRightMatch(fetchedData);
  21649. if (isFullKey)
  21650. {
  21651. #ifdef TRACE_JOINGROUPS
  21652. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21653. #endif
  21654. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21655. }
  21656. }
  21657. }
  21658. else
  21659. break;
  21660. }
  21661. }
  21662. };
  21663. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21664. {
  21665. IHThorKeyedJoinArg &helper;
  21666. Owned<IKeyManager> tlk;
  21667. Linked<IKeyArray> keySet;
  21668. Linked<TranslatorArray> translators;
  21669. CRemoteResultAdaptor remote;
  21670. RecordPullerThread puller;
  21671. IOutputMetaData *indexReadMeta;
  21672. IJoinProcessor *joinHandler;
  21673. bool variableIndexFileName;
  21674. bool indexReadInputRecordVariable;
  21675. bool isLocal;
  21676. Owned<IEngineRowAllocator> indexReadAllocator;
  21677. Owned<const IResolvedFile> varFileInfo;
  21678. IRoxieInput *indexReadInput;
  21679. IIndexReadActivityInfo *rootIndex;
  21680. public:
  21681. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21682. : CRoxieServerActivity(_factory, _probeManager),
  21683. helper((IHThorKeyedJoinArg &)basehelper),
  21684. tlk(createKeyManager(NULL, 0, this)),
  21685. translators(_translators),
  21686. keySet(_keySet),
  21687. remote(_remoteId, 0, helper, *this, true, true),
  21688. indexReadMeta(_indexReadMeta),
  21689. joinHandler(_joinHandler),
  21690. puller(false),
  21691. isLocal(_isLocal)
  21692. {
  21693. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  21694. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21695. indexReadInput = NULL;
  21696. rootIndex = NULL;
  21697. }
  21698. virtual const IResolvedFile *queryVarFileInfo() const
  21699. {
  21700. return varFileInfo;
  21701. }
  21702. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21703. {
  21704. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21705. remote.onCreate(this, this, _ctx, _colocalParent);
  21706. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21707. }
  21708. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21709. {
  21710. if (!idx)
  21711. puller.setInput(this, _in);
  21712. else if (idx==1)
  21713. indexReadInput = _in;
  21714. else
  21715. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21716. }
  21717. virtual void serializeExtra(MemoryBuffer &out)
  21718. {
  21719. if (helper.getJoinFlags() & JFindexfromactivity)
  21720. {
  21721. assertex(rootIndex);
  21722. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21723. indexId.serialize(out);
  21724. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21725. MemoryBuffer tmp;
  21726. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21727. if (rootIndex->queryActivity()->queryVarFileInfo())
  21728. {
  21729. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21730. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21731. }
  21732. unsigned ctxlen = tmp.length();
  21733. out.append(ctxlen).append(tmp);
  21734. }
  21735. }
  21736. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21737. {
  21738. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21739. if (indexReadInput)
  21740. {
  21741. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21742. rootIndex = indexReadInput->queryIndexReadActivity();
  21743. if (!rootIndex)
  21744. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21745. }
  21746. remote.onStart(parentExtractSize, parentExtract);
  21747. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21748. if (rootIndex)
  21749. {
  21750. varFileInfo.setown(rootIndex->getVarFileInfo());
  21751. translators.setown(rootIndex->getTranslators());
  21752. keySet.setown(rootIndex->getKeySet());
  21753. }
  21754. else if (variableIndexFileName)
  21755. {
  21756. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21757. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21758. if (varFileInfo)
  21759. {
  21760. translators.setown(new TranslatorArray);
  21761. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  21762. }
  21763. }
  21764. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  21765. }
  21766. virtual void stop(bool aborting)
  21767. {
  21768. puller.stop(aborting);
  21769. CRoxieServerActivity::stop(aborting);
  21770. }
  21771. virtual void reset()
  21772. {
  21773. CRoxieServerActivity::reset();
  21774. puller.reset();
  21775. if (varFileInfo)
  21776. {
  21777. keySet.clear();
  21778. varFileInfo.clear();
  21779. }
  21780. }
  21781. virtual IRoxieInput *queryOutput(unsigned idx)
  21782. {
  21783. if (idx==(unsigned)-1)
  21784. idx = 0;
  21785. return idx ? NULL : &remote;
  21786. }
  21787. virtual void processRow(const void *row)
  21788. {
  21789. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21790. // called from front puller thread
  21791. // buffer up an IndexRead request
  21792. if (helper.leftCanMatch(row))
  21793. {
  21794. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21795. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21796. OwnedConstRoxieRow extracted;
  21797. if (indexReadSize)
  21798. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21799. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21800. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21801. {
  21802. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21803. if (thisBase)
  21804. {
  21805. unsigned fileNo = 0;
  21806. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21807. try
  21808. {
  21809. tlk->setKey(thisKey);
  21810. tlk->setLayoutTranslator(translators->item(fileNo));
  21811. helper.createSegmentMonitors(tlk, extracted);
  21812. if (rootIndex)
  21813. rootIndex->mergeSegmentMonitors(tlk);
  21814. tlk->finishSegmentMonitors();
  21815. tlk->reset();
  21816. loop
  21817. {
  21818. typedef const void * cvp;
  21819. if (thisKey->isTopLevelKey())
  21820. {
  21821. bool locallySorted = !thisKey->isFullySorted();
  21822. while (locallySorted || tlk->lookup(false))
  21823. {
  21824. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21825. if (locallySorted || slavePart)
  21826. {
  21827. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21828. *outputBuffer++ = jg;
  21829. if (indexReadInputRecordVariable)
  21830. {
  21831. *(unsigned *) outputBuffer = indexReadSize;
  21832. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21833. }
  21834. jg->notePending();
  21835. memcpy(outputBuffer, extracted, indexReadSize);
  21836. if (locallySorted)
  21837. {
  21838. for (unsigned i = 1; i < numChannels; i++)
  21839. jg->notePending();
  21840. break;
  21841. }
  21842. }
  21843. }
  21844. }
  21845. else
  21846. {
  21847. // MORE - this code seems to be duplicated in half keyed
  21848. unsigned accepted = 0;
  21849. unsigned rejected = 0;
  21850. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21851. jg->notePending();
  21852. unsigned candidateCount = 0;
  21853. while (tlk->lookup(true))
  21854. {
  21855. candidateCount++;
  21856. atomic_inc(&indexRecordsRead);
  21857. KLBlobProviderAdapter adapter(tlk);
  21858. offset_t recptr;
  21859. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21860. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21861. {
  21862. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21863. rhs->fpos = recptr;
  21864. rhs->thisGroup = jg;
  21865. rhs->partNo = partNo;
  21866. result->append(rhs);
  21867. }
  21868. else
  21869. {
  21870. rejected++;
  21871. atomic_inc(&postFiltered);
  21872. }
  21873. }
  21874. // output an end marker for the matches to this group
  21875. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21876. endMarker->fpos = (offset_t) candidateCount;
  21877. endMarker->thisGroup = jg;
  21878. endMarker->partNo = (unsigned short) -1;
  21879. result->append(endMarker);
  21880. remote.injectResult(result.getClear());
  21881. if (accepted)
  21882. noteStatistic(StNumIndexAccepted, accepted);
  21883. if (rejected)
  21884. noteStatistic(StNumIndexRejected, rejected);
  21885. }
  21886. if (++fileNo < thisBase->numParts())
  21887. {
  21888. thisKey = thisBase->queryPart(fileNo);
  21889. tlk->setKey(thisKey);
  21890. tlk->setLayoutTranslator(translators->item(fileNo));
  21891. tlk->reset();
  21892. }
  21893. else
  21894. break;
  21895. }
  21896. tlk->releaseSegmentMonitors();
  21897. tlk->setKey(NULL);
  21898. }
  21899. catch (...)
  21900. {
  21901. tlk->releaseSegmentMonitors();
  21902. tlk->setKey(NULL);
  21903. throw;
  21904. }
  21905. }
  21906. }
  21907. joinHandler->noteEndReceived(jg, 0);
  21908. }
  21909. else
  21910. {
  21911. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21912. }
  21913. }
  21914. void processGroup(const ConstPointerArray &)
  21915. {
  21916. throwUnexpected();
  21917. }
  21918. virtual void processEOG()
  21919. {
  21920. joinHandler->processEOG();
  21921. }
  21922. virtual void processDone()
  21923. {
  21924. // called from puller thread
  21925. remote.flush();
  21926. remote.senddone();
  21927. }
  21928. virtual void onLimitExceeded(bool isKeyed)
  21929. {
  21930. if (traceLevel > 4)
  21931. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21932. if (isKeyed)
  21933. throwUnexpected();
  21934. helper.onLimitExceeded();
  21935. }
  21936. virtual const void *createLimitFailRow(bool isKeyed)
  21937. {
  21938. throwUnexpected();
  21939. }
  21940. virtual bool fireException(IException *e)
  21941. {
  21942. // called from puller thread on failure
  21943. remote.fireException(LINK(e));
  21944. return joinHandler->fireException(e);
  21945. }
  21946. virtual const void *nextInGroup()
  21947. {
  21948. throwUnexpected(); // I am nobody's input
  21949. }
  21950. };
  21951. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21952. {
  21953. protected:
  21954. IHThorKeyedJoinArg &helper;
  21955. KeyedJoinRemoteAdaptor remote;
  21956. RecordPullerThread puller;
  21957. OwnedConstRoxieRow defaultRight;
  21958. Owned<IEngineRowAllocator> defaultRightAllocator;
  21959. unsigned joinFlags;
  21960. unsigned atMost;
  21961. unsigned atmostsTriggered;
  21962. unsigned abortLimit;
  21963. unsigned keepLimit;
  21964. bool limitFail;
  21965. bool limitOnFail;
  21966. bool preserveGroups;
  21967. bool cloneLeft;
  21968. bool isSimple;
  21969. bool isLocal;
  21970. ThorActivityKind activityKind;
  21971. CJoinGroup *groupStart;
  21972. CriticalSection groupsCrit;
  21973. QueueOf<CJoinGroup, false> groups;
  21974. IRoxieInput *indexReadInput;
  21975. IIndexReadActivityInfo *rootIndex;
  21976. void createDefaultRight()
  21977. {
  21978. if (!defaultRight)
  21979. {
  21980. if (!defaultRightAllocator)
  21981. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21982. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21983. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21984. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21985. }
  21986. }
  21987. public:
  21988. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21989. , bool isFull, bool _isSimple, bool _isLocal)
  21990. : CRoxieServerActivity(_factory, _probeManager),
  21991. helper((IHThorKeyedJoinArg &)basehelper),
  21992. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21993. joinFlags(_joinFlags),
  21994. preserveGroups(meta.isGrouped()),
  21995. puller(false),
  21996. isSimple(_isSimple),
  21997. isLocal(_isLocal),
  21998. abortLimit(0),
  21999. keepLimit(0),
  22000. atMost(0),
  22001. limitFail(false),
  22002. limitOnFail(false),
  22003. cloneLeft(false)
  22004. {
  22005. groupStart = NULL;
  22006. activityKind = _factory->getKind();
  22007. indexReadInput = NULL;
  22008. rootIndex = NULL;
  22009. atmostsTriggered = 0;
  22010. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22011. }
  22012. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22013. {
  22014. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  22015. remote.onCreate(this, this, _ctx, _colocalParent);
  22016. }
  22017. virtual void setInput(unsigned idx, IRoxieInput *_in)
  22018. {
  22019. if (!idx)
  22020. puller.setInput(this, _in);
  22021. else if (idx==1)
  22022. indexReadInput = _in;
  22023. else
  22024. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22025. }
  22026. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22027. {
  22028. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22029. if (indexReadInput)
  22030. {
  22031. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22032. rootIndex = indexReadInput->queryIndexReadActivity();
  22033. if (!rootIndex)
  22034. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22035. }
  22036. remote.onStart(parentExtractSize, parentExtract);
  22037. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22038. atmostsTriggered = 0;
  22039. atMost = helper.getJoinLimit();
  22040. if (atMost == 0) atMost = (unsigned)-1;
  22041. abortLimit = helper.getMatchAbortLimit();
  22042. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22043. keepLimit = helper.getKeepLimit();
  22044. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22045. getLimitType(joinFlags, limitFail, limitOnFail);
  22046. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22047. if (joinFlags & JFleftouter)
  22048. createDefaultRight();
  22049. }
  22050. virtual void stop(bool aborting)
  22051. {
  22052. puller.stop(aborting);
  22053. if (indexReadInput)
  22054. indexReadInput->stop(aborting);
  22055. CRoxieServerActivity::stop(aborting);
  22056. }
  22057. virtual unsigned __int64 queryLocalCycles() const
  22058. {
  22059. __int64 localCycles = remote.totalCycles.totalCycles;
  22060. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22061. if (localCycles < 0)
  22062. localCycles = 0;
  22063. return localCycles;
  22064. }
  22065. virtual IRoxieInput *queryInput(unsigned idx)
  22066. {
  22067. if (idx==0)
  22068. return puller.queryInput();
  22069. else if (idx==1)
  22070. return indexReadInput;
  22071. else
  22072. return NULL;
  22073. }
  22074. virtual void reset()
  22075. {
  22076. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22077. remote.totalCycles.totalCycles = 0;
  22078. processed = remote.joinProcessed;
  22079. remote.joinProcessed = 0;
  22080. defaultRight.clear();
  22081. if (indexReadInput)
  22082. indexReadInput->reset();
  22083. if (atmostsTriggered)
  22084. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22085. CRoxieServerActivity::reset();
  22086. puller.reset();
  22087. while (groups.ordinality())
  22088. {
  22089. ::Release(groups.dequeue());
  22090. }
  22091. }
  22092. virtual IRoxieInput *queryOutput(unsigned idx)
  22093. {
  22094. if (idx==(unsigned)-1)
  22095. idx = 0;
  22096. return idx ? NULL : &remote;
  22097. }
  22098. #undef new
  22099. virtual CJoinGroup *createJoinGroup(const void *row)
  22100. {
  22101. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22102. CriticalBlock c(groupsCrit);
  22103. if (preserveGroups && !groupStart)
  22104. {
  22105. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22106. groups.enqueue(groupStart);
  22107. }
  22108. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  22109. groups.enqueue(jg);
  22110. return jg;
  22111. }
  22112. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22113. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22114. #endif
  22115. void endGroup()
  22116. {
  22117. CriticalBlock c(groupsCrit);
  22118. if (groupStart)
  22119. noteEndReceived(groupStart, 0);
  22120. groupStart = NULL;
  22121. }
  22122. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  22123. {
  22124. if (jg->noteEndReceived(candidateCount))
  22125. processCompletedGroups();
  22126. }
  22127. void processCompletedGroups()
  22128. {
  22129. loop
  22130. {
  22131. CriticalBlock c(groupsCrit);
  22132. if (!groups.head()->complete())
  22133. break;
  22134. Owned<CJoinGroup> head = groups.dequeue();
  22135. if (preserveGroups)
  22136. {
  22137. assert(head->isHeadRecord());
  22138. assert(groups.head()->inGroup(head));
  22139. unsigned joinGroupSize = 0;
  22140. while (groups.ordinality() && groups.head()->inGroup(head))
  22141. {
  22142. Owned<CJoinGroup> finger = groups.dequeue();
  22143. joinGroupSize += doJoinGroup(finger);
  22144. }
  22145. if (joinGroupSize)
  22146. remote.addResult(NULL);
  22147. }
  22148. else
  22149. doJoinGroup(head);
  22150. if (!groups.ordinality())
  22151. break;
  22152. }
  22153. }
  22154. void failLimit(const void * left)
  22155. {
  22156. helper.onMatchAbortLimitExceeded();
  22157. CommonXmlWriter xmlwrite(0);
  22158. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  22159. {
  22160. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  22161. }
  22162. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  22163. }
  22164. virtual bool needsAllocator() const { return true; }
  22165. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  22166. {
  22167. if (cloneLeft && !except)
  22168. {
  22169. LinkRoxieRow(left);
  22170. remote.addResult((void *) left);
  22171. return 1;
  22172. }
  22173. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22174. unsigned outSize;
  22175. try
  22176. {
  22177. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  22178. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  22179. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  22180. }
  22181. catch (IException *E)
  22182. {
  22183. throw makeWrappedException(E);
  22184. }
  22185. if (outSize)
  22186. {
  22187. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  22188. remote.addResult(shrunk);
  22189. return 1;
  22190. }
  22191. else
  22192. return 0;
  22193. }
  22194. unsigned doJoinGroup(CJoinGroup *jg)
  22195. {
  22196. unsigned matched = jg->rowsSeen();
  22197. unsigned added = 0;
  22198. const void *left = jg->queryLeft();
  22199. if (jg->candidateCount() > abortLimit)
  22200. {
  22201. if (limitFail)
  22202. failLimit(left);
  22203. if (ctx->queryDebugContext())
  22204. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22205. if (limitOnFail)
  22206. {
  22207. Owned<IException> except;
  22208. try
  22209. {
  22210. failLimit(left);
  22211. }
  22212. catch(IException * e)
  22213. {
  22214. except.setown(e);
  22215. }
  22216. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  22217. }
  22218. }
  22219. else if (!matched || jg->candidateCount() > atMost)
  22220. {
  22221. if (jg->candidateCount() > atMost)
  22222. atmostsTriggered++;
  22223. switch (joinFlags & JFtypemask)
  22224. {
  22225. case JFleftouter:
  22226. case JFleftonly:
  22227. switch (activityKind)
  22228. {
  22229. case TAKkeyedjoin:
  22230. case TAKkeyeddenormalizegroup:
  22231. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  22232. break;
  22233. case TAKkeyeddenormalize:
  22234. LinkRoxieRow(left);
  22235. remote.addResult((void *) left);
  22236. added++;
  22237. break;
  22238. }
  22239. break;
  22240. }
  22241. }
  22242. else if (!(joinFlags & JFexclude))
  22243. {
  22244. unsigned idx = 0;
  22245. switch (activityKind)
  22246. {
  22247. case TAKkeyedjoin:
  22248. while (idx < matched)
  22249. {
  22250. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22251. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  22252. if (added==keepLimit)
  22253. break;
  22254. idx++;
  22255. }
  22256. break;
  22257. case TAKkeyeddenormalize:
  22258. {
  22259. OwnedConstRoxieRow newLeft;
  22260. newLeft.set(left);
  22261. unsigned rowSize = 0;
  22262. unsigned rightAdded = 0;
  22263. while (idx < matched)
  22264. {
  22265. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22266. try
  22267. {
  22268. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22269. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  22270. if (transformedSize)
  22271. {
  22272. rowSize = transformedSize;
  22273. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  22274. rightAdded++;
  22275. if (rightAdded==keepLimit)
  22276. break;
  22277. }
  22278. idx++;
  22279. }
  22280. catch (IException *E)
  22281. {
  22282. throw makeWrappedException(E);
  22283. }
  22284. }
  22285. if (rowSize)
  22286. {
  22287. remote.addResult(newLeft.getClear());
  22288. added++;
  22289. }
  22290. }
  22291. break;
  22292. case TAKkeyeddenormalizegroup:
  22293. {
  22294. ConstPointerArray extractedRows;
  22295. while (idx < matched && idx < keepLimit)
  22296. {
  22297. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22298. extractedRows.append((void *) &rhs->rhsdata);
  22299. idx++;
  22300. }
  22301. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  22302. }
  22303. break;
  22304. }
  22305. }
  22306. return added;
  22307. }
  22308. virtual void processDone()
  22309. {
  22310. // called from puller thread
  22311. remote.flush();
  22312. remote.senddone();
  22313. }
  22314. virtual void onLimitExceeded(bool isKeyed)
  22315. {
  22316. if (traceLevel > 4)
  22317. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22318. if (isKeyed)
  22319. throwUnexpected();
  22320. helper.onLimitExceeded();
  22321. }
  22322. virtual const void *createLimitFailRow(bool isKeyed)
  22323. {
  22324. throwUnexpected();
  22325. }
  22326. virtual bool fireException(IException *e)
  22327. {
  22328. // called from puller thread on failure
  22329. return remote.fireException(e);
  22330. }
  22331. virtual const void *nextInGroup()
  22332. {
  22333. throwUnexpected(); // I am nobody's input
  22334. }
  22335. };
  22336. #ifdef _MSC_VER
  22337. #pragma warning ( push )
  22338. #pragma warning ( disable: 4355 )
  22339. #endif
  22340. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22341. {
  22342. CRoxieServerFullKeyedJoinHead head;
  22343. Owned<IEngineRowAllocator> fetchInputAllocator;
  22344. Linked<IFilePartMap> map;
  22345. bool variableFetchFileName;
  22346. Owned<const IResolvedFile> varFetchFileInfo;
  22347. CachedOutputMetaData fetchInputFields;
  22348. public:
  22349. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  22350. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  22351. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  22352. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  22353. map(_map)
  22354. {
  22355. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  22356. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22357. }
  22358. virtual const IResolvedFile *queryVarFileInfo() const
  22359. {
  22360. return varFetchFileInfo;
  22361. }
  22362. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22363. {
  22364. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22365. head.onCreate(_ctx, _colocalParent);
  22366. fetchInputFields.set(helper.queryFetchInputRecordSize());
  22367. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  22368. }
  22369. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22370. {
  22371. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22372. if (variableFetchFileName)
  22373. {
  22374. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22375. OwnedRoxieString fname(helper.getFileName());
  22376. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  22377. if (varFetchFileInfo)
  22378. map.setown(varFetchFileInfo->getFileMap());
  22379. }
  22380. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  22381. }
  22382. virtual void setInput(unsigned idx, IRoxieInput *in)
  22383. {
  22384. head.setInput(idx, in);
  22385. }
  22386. virtual void processRow(const void *_rhs)
  22387. {
  22388. // called from puller thread
  22389. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  22390. CJoinGroup *jg = rhs->thisGroup;
  22391. if (rhs->partNo != (unsigned short) -1)
  22392. {
  22393. unsigned partNo = map->mapOffset(rhs->fpos);
  22394. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  22395. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  22396. if (fetchInputFields.isVariableSize())
  22397. {
  22398. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  22399. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22400. ReleaseRoxieRow(rhs);
  22401. jg->notePending();
  22402. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  22403. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  22404. }
  22405. else
  22406. {
  22407. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  22408. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22409. ReleaseRoxieRow(rhs);
  22410. jg->notePending();
  22411. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  22412. }
  22413. }
  22414. else
  22415. {
  22416. unsigned candidateCount = (unsigned) rhs->fpos;
  22417. // CTXLOG("Full keyed join - all results back from index");
  22418. ReleaseRoxieRow(rhs);
  22419. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  22420. }
  22421. }
  22422. virtual void processEOG()
  22423. {
  22424. // called from front puller thread
  22425. if (preserveGroups)
  22426. endGroup();
  22427. }
  22428. void processGroup(const ConstPointerArray &)
  22429. {
  22430. throwUnexpected();
  22431. }
  22432. };
  22433. #ifdef _MSC_VER
  22434. #pragma warning ( pop )
  22435. #endif
  22436. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22437. {
  22438. IOutputMetaData *indexReadMeta;
  22439. Owned<IEngineRowAllocator> indexReadAllocator;
  22440. Owned<IKeyManager> tlk;
  22441. bool variableIndexFileName;
  22442. bool indexReadInputRecordVariable;
  22443. Owned<const IResolvedFile> varFileInfo;
  22444. Linked<TranslatorArray> translators;
  22445. Linked<IKeyArray> keySet;
  22446. Owned<IOutputMetaData> joinPrefixedMeta;
  22447. Owned<IEngineRowAllocator> joinFieldsAllocator;
  22448. public:
  22449. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  22450. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  22451. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  22452. indexReadMeta(_indexReadMeta),
  22453. tlk(createKeyManager(NULL, 0, this)),
  22454. keySet(_keySet),
  22455. translators(_translators)
  22456. {
  22457. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22458. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22459. }
  22460. virtual void serializeExtra(MemoryBuffer &out)
  22461. {
  22462. if (helper.getJoinFlags() & JFindexfromactivity)
  22463. {
  22464. assertex(rootIndex);
  22465. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22466. indexId.serialize(out);
  22467. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22468. MemoryBuffer tmp;
  22469. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22470. if (rootIndex->queryActivity()->queryVarFileInfo())
  22471. {
  22472. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22473. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22474. }
  22475. unsigned ctxlen = tmp.length();
  22476. out.append(ctxlen).append(tmp);
  22477. }
  22478. }
  22479. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22480. {
  22481. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22482. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  22483. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  22484. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  22485. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  22486. }
  22487. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22488. {
  22489. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22490. if (rootIndex)
  22491. {
  22492. varFileInfo.setown(rootIndex->getVarFileInfo());
  22493. translators.setown(rootIndex->getTranslators());
  22494. keySet.setown(rootIndex->getKeySet());
  22495. }
  22496. else if (variableIndexFileName)
  22497. {
  22498. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22499. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22500. if (varFileInfo)
  22501. {
  22502. translators.setown(new TranslatorArray);
  22503. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  22504. }
  22505. }
  22506. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  22507. }
  22508. virtual const IResolvedFile *queryVarFileInfo() const
  22509. {
  22510. return varFileInfo;
  22511. }
  22512. virtual void reset()
  22513. {
  22514. CRoxieServerKeyedJoinBase::reset();
  22515. if (varFileInfo)
  22516. {
  22517. keySet.clear();
  22518. varFileInfo.clear();
  22519. }
  22520. }
  22521. virtual void processRow(const void *row)
  22522. {
  22523. // called from front puller thread
  22524. // buffer up an IndexRead request
  22525. if (helper.leftCanMatch(row) && keySet)
  22526. {
  22527. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  22528. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  22529. OwnedConstRoxieRow extracted;
  22530. if (indexReadRecordSize)
  22531. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  22532. CJoinGroup *jg = createJoinGroup(row);
  22533. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22534. {
  22535. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22536. if (thisBase)
  22537. {
  22538. unsigned fileNo = 0;
  22539. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22540. tlk->setKey(thisKey);
  22541. tlk->setLayoutTranslator(translators->item(fileNo));
  22542. helper.createSegmentMonitors(tlk, extracted);
  22543. if (rootIndex)
  22544. rootIndex->mergeSegmentMonitors(tlk);
  22545. tlk->finishSegmentMonitors();
  22546. try
  22547. {
  22548. tlk->reset();
  22549. loop
  22550. {
  22551. typedef const void * cvp;
  22552. if (thisKey && thisKey->isTopLevelKey())
  22553. {
  22554. bool locallySorted = (!thisKey->isFullySorted());
  22555. while (locallySorted || tlk->lookup(false))
  22556. {
  22557. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22558. if (locallySorted || slavePart)
  22559. {
  22560. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22561. *outputBuffer++ = jg;
  22562. if (indexReadInputRecordVariable)
  22563. {
  22564. *(unsigned *) outputBuffer = indexReadRecordSize;
  22565. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  22566. }
  22567. jg->notePending();
  22568. memcpy(outputBuffer, extracted, indexReadRecordSize);
  22569. if (locallySorted)
  22570. {
  22571. for (unsigned i = 1; i < numChannels; i++)
  22572. jg->notePending();
  22573. break;
  22574. }
  22575. }
  22576. }
  22577. }
  22578. else
  22579. {
  22580. unsigned accepted = 0;
  22581. unsigned rejected = 0;
  22582. Owned<CRowArrayMessageResult> result;
  22583. if (!isSimple)
  22584. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22585. // MORE - This code seems to be duplicated in keyedJoinHead
  22586. jg->notePending();
  22587. unsigned candidateCount = 0;
  22588. while (tlk->lookup(true))
  22589. {
  22590. candidateCount++;
  22591. atomic_inc(&indexRecordsRead);
  22592. KLBlobProviderAdapter adapter(tlk);
  22593. offset_t recptr;
  22594. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22595. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22596. {
  22597. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22598. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22599. accepted++;
  22600. KLBlobProviderAdapter adapter(tlk);
  22601. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22602. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22603. rec->fpos = recptr;
  22604. rec->thisGroup = jg;
  22605. rec->partNo = partNo;
  22606. if (isSimple)
  22607. remote.injected.enqueue(rec);
  22608. else
  22609. result->append(rec);
  22610. }
  22611. else
  22612. {
  22613. rejected++;
  22614. atomic_inc(&postFiltered);
  22615. }
  22616. }
  22617. // output an end marker for the matches to this group
  22618. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22619. rec->fpos = (offset_t) candidateCount;
  22620. rec->thisGroup = jg;
  22621. rec->partNo = (unsigned short) -1;
  22622. if (isSimple)
  22623. remote.injected.enqueue(rec);
  22624. else
  22625. {
  22626. result->append(rec);
  22627. remote.injectResult(result.getClear());
  22628. }
  22629. if (accepted)
  22630. noteStatistic(StNumIndexAccepted, accepted);
  22631. if (rejected)
  22632. noteStatistic(StNumIndexRejected, rejected);
  22633. }
  22634. if (++fileNo < thisBase->numParts())
  22635. {
  22636. thisKey = thisBase->queryPart(fileNo);
  22637. tlk->setKey(thisKey);
  22638. tlk->setLayoutTranslator(translators->item(fileNo));
  22639. tlk->reset();
  22640. }
  22641. else
  22642. break;
  22643. }
  22644. tlk->releaseSegmentMonitors();
  22645. tlk->setKey(NULL);
  22646. }
  22647. catch (...)
  22648. {
  22649. tlk->releaseSegmentMonitors();
  22650. tlk->setKey(NULL);
  22651. throw;
  22652. }
  22653. }
  22654. }
  22655. noteEndReceived(jg, 0);
  22656. }
  22657. else
  22658. {
  22659. noteEndReceived(createJoinGroup(row), 0);
  22660. }
  22661. }
  22662. virtual void processEOG()
  22663. {
  22664. // called from front puller thread
  22665. if (preserveGroups)
  22666. endGroup();
  22667. }
  22668. void processGroup(const ConstPointerArray &)
  22669. {
  22670. throwUnexpected();
  22671. }
  22672. };
  22673. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22674. {
  22675. Owned<const IResolvedFile> indexfile;
  22676. Owned<const IResolvedFile> datafile;
  22677. Owned<IKeyArray> keySet;
  22678. Owned<TranslatorArray> translatorArray;
  22679. Owned<IDefRecordMeta> activityMeta;
  22680. RemoteActivityId headId;
  22681. RemoteActivityId tailId;
  22682. IOutputMetaData *indexReadMeta;
  22683. Owned<IFilePartMap> map;
  22684. Owned<IFileIOArray> files;
  22685. unsigned joinFlags;
  22686. bool isHalfKeyed;
  22687. bool isLocal;
  22688. bool enableFieldTranslation;
  22689. bool variableFetchFileName;
  22690. bool variableIndexFileName;
  22691. bool isSimple;
  22692. public:
  22693. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22694. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22695. {
  22696. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22697. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22698. isSimple = isLocal;
  22699. rtlDataAttr indexLayoutMeta;
  22700. size32_t indexLayoutSize;
  22701. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22702. assertex(indexLayoutSize== 0);
  22703. MemoryBuffer m;
  22704. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22705. activityMeta.setown(deserializeRecordMeta(m, true));
  22706. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  22707. translatorArray.setown(new TranslatorArray);
  22708. joinFlags = helper->getJoinFlags();
  22709. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22710. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22711. if (!variableIndexFileName)
  22712. {
  22713. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22714. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22715. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  22716. if (indexfile)
  22717. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22718. }
  22719. if (keySet && keySet->length()==1 && !isSimple)
  22720. {
  22721. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22722. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  22723. isSimple = true;
  22724. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22725. }
  22726. if (!simpleLocalKeyedJoins)
  22727. isSimple = false;
  22728. isHalfKeyed = !helper->diskAccessRequired();
  22729. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22730. if (!isHalfKeyed && !variableFetchFileName)
  22731. {
  22732. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22733. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit()));
  22734. if (datafile)
  22735. {
  22736. if (isLocal)
  22737. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22738. else
  22739. map.setown(datafile->getFileMap());
  22740. }
  22741. }
  22742. }
  22743. virtual bool getEnableFieldTranslation() const
  22744. {
  22745. return enableFieldTranslation;
  22746. }
  22747. virtual IDefRecordMeta *queryActivityMeta() const
  22748. {
  22749. return activityMeta;
  22750. }
  22751. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22752. {
  22753. if (isHalfKeyed)
  22754. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22755. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22756. else
  22757. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22758. headId, keySet, translatorArray, indexReadMeta,
  22759. tailId, map, joinFlags, isLocal);
  22760. }
  22761. virtual const StatisticsMapping &queryStatsMapping() const
  22762. {
  22763. return keyedJoinStatistics;
  22764. }
  22765. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22766. {
  22767. if (datafile)
  22768. addXrefFileInfo(reply, datafile);
  22769. if (indexfile)
  22770. addXrefFileInfo(reply, indexfile);
  22771. }
  22772. };
  22773. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22774. {
  22775. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22776. }
  22777. //=================================================================================
  22778. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22779. {
  22780. protected:
  22781. Owned<ISoapCallHelper> soaphelper;
  22782. IHThorSoapActionArg & helper;
  22783. StringBuffer authToken;
  22784. bool eof;
  22785. CriticalSection crit;
  22786. ClientCertificate *pClientCert;
  22787. public:
  22788. IMPLEMENT_IINTERFACE;
  22789. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22790. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22791. {
  22792. eof = false;
  22793. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22794. pClientCert = &clientCert;
  22795. else
  22796. pClientCert = NULL;
  22797. }
  22798. // ISoapCallRowProvider
  22799. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22800. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22801. virtual const void * getNextRow() { return NULL; };
  22802. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22803. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22804. {
  22805. eof = false;
  22806. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22807. authToken.append(ctx->queryAuthToken());
  22808. }
  22809. virtual void reset()
  22810. {
  22811. // MORE - Shouldn't we make sure thread is stopped etc???
  22812. soaphelper.clear();
  22813. CRoxieServerActivity::reset();
  22814. }
  22815. // IRoxieAbortMonitor
  22816. virtual void checkForAbort() { checkAbort(); }
  22817. };
  22818. //---------------------------------------------------------------------------
  22819. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22820. {
  22821. IHThorSoapCallArg & callHelper;
  22822. public:
  22823. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22824. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22825. {
  22826. }
  22827. virtual IHThorSoapCallArg * queryCallHelper()
  22828. {
  22829. return &callHelper;
  22830. }
  22831. virtual bool needsAllocator() const { return true; }
  22832. virtual const void *nextInGroup()
  22833. {
  22834. ActivityTimer t(totalCycles, timeActivities);
  22835. if(eof) return NULL;
  22836. if (soaphelper == NULL)
  22837. {
  22838. if (factory->getKind()==TAKhttp_rowdataset)
  22839. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22840. else
  22841. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22842. soaphelper->start();
  22843. }
  22844. OwnedConstRoxieRow ret = soaphelper->getRow();
  22845. if (!ret)
  22846. {
  22847. eof = true;
  22848. return NULL;
  22849. }
  22850. ++processed;
  22851. return ret.getClear();
  22852. }
  22853. };
  22854. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22855. {
  22856. public:
  22857. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22858. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22859. {
  22860. }
  22861. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22862. {
  22863. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22864. }
  22865. virtual const StatisticsMapping &queryStatsMapping() const
  22866. {
  22867. return soapStatistics;
  22868. }
  22869. };
  22870. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22871. {
  22872. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22873. }
  22874. //---------------------------------------------------------------------------
  22875. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22876. {
  22877. public:
  22878. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22879. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22880. {}
  22881. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22882. {
  22883. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22884. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  22885. soaphelper->start();
  22886. soaphelper->waitUntilDone();
  22887. IException *e = soaphelper->getError();
  22888. soaphelper.clear();
  22889. if (e)
  22890. throw e;
  22891. }
  22892. virtual IRoxieInput *queryOutput(unsigned idx)
  22893. {
  22894. return NULL;
  22895. }
  22896. virtual const void *nextInGroup()
  22897. {
  22898. throwUnexpected(); // I am nobody's input
  22899. }
  22900. };
  22901. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22902. {
  22903. bool isRoot;
  22904. public:
  22905. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22906. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22907. {
  22908. }
  22909. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22910. {
  22911. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22912. }
  22913. virtual bool isSink() const
  22914. {
  22915. return isRoot;
  22916. }
  22917. virtual const StatisticsMapping &queryStatsMapping() const
  22918. {
  22919. return soapStatistics;
  22920. }
  22921. };
  22922. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22923. {
  22924. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22925. }
  22926. //---------------------------------------------------------------------------
  22927. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22928. {
  22929. IHThorSoapCallArg & callHelper;
  22930. public:
  22931. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22932. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22933. {
  22934. }
  22935. virtual IHThorSoapCallArg * queryCallHelper()
  22936. {
  22937. return &callHelper;
  22938. }
  22939. virtual const void *getNextRow()
  22940. {
  22941. CriticalBlock b(crit);
  22942. const void *nextrec = input->nextInGroup();
  22943. if (!nextrec)
  22944. {
  22945. nextrec = input->nextInGroup();
  22946. }
  22947. return nextrec;
  22948. }
  22949. virtual bool needsAllocator() const { return true; }
  22950. virtual const void *nextInGroup()
  22951. {
  22952. ActivityTimer t(totalCycles, timeActivities);
  22953. if(eof) return NULL;
  22954. if (soaphelper == NULL)
  22955. {
  22956. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  22957. soaphelper->start();
  22958. }
  22959. OwnedConstRoxieRow ret = soaphelper->getRow();
  22960. if (!ret)
  22961. {
  22962. eof = true;
  22963. return NULL;
  22964. }
  22965. ++processed;
  22966. return ret.getClear();
  22967. }
  22968. };
  22969. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22970. {
  22971. public:
  22972. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22973. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22974. {
  22975. }
  22976. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22977. {
  22978. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22979. }
  22980. virtual const StatisticsMapping &queryStatsMapping() const
  22981. {
  22982. return soapStatistics;
  22983. }
  22984. };
  22985. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22986. {
  22987. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22988. }
  22989. //---------------------------------------------------------------------------
  22990. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22991. {
  22992. public:
  22993. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22994. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22995. {}
  22996. virtual const void *getNextRow()
  22997. {
  22998. CriticalBlock b(crit);
  22999. const void *nextrec = input->nextInGroup();
  23000. if (!nextrec)
  23001. {
  23002. nextrec = input->nextInGroup();
  23003. }
  23004. if (nextrec)
  23005. processed++;
  23006. return nextrec;
  23007. }
  23008. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  23009. {
  23010. try
  23011. {
  23012. start(parentExtractSize, parentExtract, false);
  23013. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  23014. soaphelper->start();
  23015. soaphelper->waitUntilDone();
  23016. IException *e = soaphelper->getError();
  23017. soaphelper.clear();
  23018. if (e)
  23019. throw e;
  23020. stop(false);
  23021. }
  23022. catch (IException *E)
  23023. {
  23024. ctx->notifyAbort(E);
  23025. stop(true);
  23026. throw;
  23027. }
  23028. catch(...)
  23029. {
  23030. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  23031. ctx->notifyAbort(E);
  23032. stop(true);
  23033. throw;
  23034. }
  23035. }
  23036. virtual IRoxieInput *queryOutput(unsigned idx)
  23037. {
  23038. return NULL;
  23039. }
  23040. virtual const void *nextInGroup()
  23041. {
  23042. throwUnexpected(); // I am nobody's input
  23043. }
  23044. };
  23045. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23046. {
  23047. bool isRoot;
  23048. public:
  23049. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23050. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  23051. {
  23052. }
  23053. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  23054. {
  23055. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  23056. }
  23057. virtual bool isSink() const
  23058. {
  23059. return isRoot;
  23060. }
  23061. virtual const StatisticsMapping &queryStatsMapping() const
  23062. {
  23063. return soapStatistics;
  23064. }
  23065. };
  23066. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23067. {
  23068. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  23069. }
  23070. //=====================================================================================================
  23071. class CGraphResults : public CInterface, implements IRoxieGraphResults
  23072. {
  23073. IArrayOf<IGraphResult> results;
  23074. CriticalSection cs;
  23075. IGraphResult & select(unsigned idx)
  23076. {
  23077. CriticalBlock procedure(cs);
  23078. if (idx >= results.ordinality())
  23079. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23080. return results.item(idx);
  23081. }
  23082. public:
  23083. IMPLEMENT_IINTERFACE
  23084. void clear()
  23085. {
  23086. CriticalBlock procedure(cs);
  23087. results.kill();
  23088. }
  23089. IRoxieInput * createIterator(unsigned id)
  23090. {
  23091. return select(id).createIterator();
  23092. }
  23093. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23094. {
  23095. select(id).getLinkedResult(count, ret);
  23096. }
  23097. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23098. {
  23099. select(id).getLinkedResult(count, ret);
  23100. }
  23101. virtual const void * getLinkedRowResult(unsigned id)
  23102. {
  23103. return select(id).getLinkedRowResult();
  23104. }
  23105. void setResult(unsigned id, IGraphResult * result)
  23106. {
  23107. CriticalBlock procedure(cs);
  23108. if (results.ordinality() <= id)
  23109. {
  23110. while (results.ordinality() < id)
  23111. results.append(*new CGraphResult);
  23112. results.append(*LINK(result));
  23113. }
  23114. else
  23115. results.replace(*LINK(result), id);
  23116. }
  23117. void appendResult(IGraphResult * result)
  23118. {
  23119. CriticalBlock procedure(cs);
  23120. results.append(*LINK(result));
  23121. }
  23122. };
  23123. //===================================================================================================================
  23124. class CPseudoArg : public CInterface, implements IHThorArg
  23125. {
  23126. public:
  23127. IMPLEMENT_IINTERFACE
  23128. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  23129. };
  23130. class CPseudoActivity : public CRoxieServerActivity
  23131. {
  23132. public:
  23133. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  23134. virtual const void *nextInGroup()
  23135. {
  23136. throwUnexpected(); // I am nobody's input
  23137. }
  23138. };
  23139. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  23140. {
  23141. protected:
  23142. class ActivityGraphSlaveContext : public IndirectSlaveContext
  23143. {
  23144. SpinLock abortLock;
  23145. bool aborted;
  23146. Owned<IException> exception;
  23147. public:
  23148. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  23149. {
  23150. aborted = false;
  23151. }
  23152. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  23153. virtual void notifyAbort(IException *E)
  23154. {
  23155. SpinBlock b(abortLock);
  23156. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  23157. {
  23158. aborted = true;
  23159. exception.set(E);
  23160. }
  23161. }
  23162. virtual void checkAbort()
  23163. {
  23164. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  23165. {
  23166. SpinBlock b(abortLock);
  23167. if (!exception)
  23168. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  23169. throw exception.getLink();
  23170. }
  23171. IndirectSlaveContext::checkAbort();
  23172. }
  23173. virtual ICodeContext *queryCodeContext()
  23174. {
  23175. return codeContext;
  23176. }
  23177. void setCodeContext(ICodeContext * _codeContext)
  23178. {
  23179. codeContext = _codeContext;
  23180. }
  23181. void setLoopCounter(unsigned _loopCounter)
  23182. {
  23183. loopCounter = _loopCounter;
  23184. }
  23185. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  23186. {
  23187. childGraphs.setValue(id, childGraph);
  23188. }
  23189. virtual IActivityGraph * queryChildGraph(unsigned id)
  23190. {
  23191. if (queryTraceLevel() > 10)
  23192. CTXLOG("resolveChildGraph %d", id);
  23193. IActivityGraph *childGraph = childGraphs.getValue(id);
  23194. assertex(childGraph);
  23195. return childGraph;
  23196. }
  23197. // 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
  23198. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  23199. {
  23200. logctx.getLogPrefix(ret);
  23201. if (loopCounter)
  23202. ret.appendf("{%u}", loopCounter);
  23203. return ret;
  23204. }
  23205. protected:
  23206. const IRoxieContextLogger &logctx;
  23207. unsigned loopCounter;
  23208. ICodeContext * codeContext;
  23209. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  23210. } graphSlaveContext;
  23211. class ActivityGraphCodeContext : public IndirectCodeContext
  23212. {
  23213. public:
  23214. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  23215. {
  23216. if ((unsigned) activityId == container->queryId())
  23217. return container;
  23218. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23219. if (match)
  23220. return match->queryLocalGraph();
  23221. return IndirectCodeContext::resolveLocalQuery(activityId);
  23222. }
  23223. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  23224. {
  23225. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23226. return LINK(match->queryChildGraph());
  23227. }
  23228. virtual unsigned getGraphLoopCounter() const
  23229. {
  23230. return container->queryLoopCounter(); // only called if value is valid
  23231. }
  23232. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  23233. {
  23234. slaveContext = _slaveContext;
  23235. container = _container;
  23236. }
  23237. protected:
  23238. IRoxieSlaveContext * slaveContext;
  23239. CActivityGraph * container;
  23240. } graphCodeContext;
  23241. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  23242. IArrayOf<IRoxieServerActivity> activities;
  23243. IArrayOf<IRoxieInput> probes;
  23244. IRoxieServerActivityCopyArray sinks;
  23245. StringAttr graphName;
  23246. Owned<CGraphResults> results;
  23247. CGraphResults graphLoopResults;
  23248. ActivityArray & graphDefinition;
  23249. CriticalSection evaluateCrit;
  23250. IProbeManager *probeManager;
  23251. unsigned id;
  23252. unsigned loopCounter;
  23253. public:
  23254. IMPLEMENT_IINTERFACE;
  23255. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23256. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  23257. {
  23258. id = x.getLibraryGraphId();
  23259. if (!id)
  23260. id = _id;
  23261. loopCounter = 0;
  23262. graphSlaveContext.setCodeContext(&graphCodeContext);
  23263. graphCodeContext.setContainer(&graphSlaveContext, this);
  23264. }
  23265. ~CActivityGraph()
  23266. {
  23267. if (probeManager)
  23268. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  23269. }
  23270. virtual const char *queryName() const
  23271. {
  23272. return graphName.get();
  23273. }
  23274. void createGraph()
  23275. {
  23276. ForEachItemIn(idx, graphDefinition)
  23277. {
  23278. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  23279. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  23280. activities.append(activity);
  23281. if (donor.isSink())
  23282. {
  23283. sinks.append(activity);
  23284. if (probeManager)
  23285. probeManager->noteSink(&activity);
  23286. }
  23287. }
  23288. ForEachItemIn(idx1, graphDefinition)
  23289. {
  23290. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  23291. IRoxieServerActivity &activity = activities.item(idx1);
  23292. unsigned inputidx = 0;
  23293. loop
  23294. {
  23295. unsigned outputidx;
  23296. unsigned source = donor.getInput(inputidx, outputidx);
  23297. if (source==(unsigned) -1)
  23298. break;
  23299. connectInput(idx1, inputidx, source, outputidx, 0);
  23300. inputidx++;
  23301. }
  23302. IntArray &dependencies = donor.queryDependencies();
  23303. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23304. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23305. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  23306. ForEachItemIn(idx2, dependencies)
  23307. {
  23308. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  23309. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  23310. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  23311. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  23312. if (probeManager)
  23313. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  23314. }
  23315. }
  23316. }
  23317. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  23318. {
  23319. IRoxieServerActivity &targetActivity = activities.item(target);
  23320. IRoxieServerActivity &sourceActivity = activities.item(source);
  23321. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  23322. if (probeManager)
  23323. {
  23324. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  23325. output = static_cast<IRoxieInput*>(inputBase);
  23326. probes.append(*LINK(output));
  23327. }
  23328. targetActivity.setInput(targetIdx, output);
  23329. }
  23330. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  23331. {
  23332. graphSlaveContext.set(ctx);
  23333. if (graphDefinition.isMultiInstance())
  23334. {
  23335. graphCodeContext.set(ctx->queryCodeContext());
  23336. ctx = &graphSlaveContext;
  23337. }
  23338. ForEachItemIn(idx, activities)
  23339. {
  23340. IRoxieServerActivity *activity = &activities.item(idx);
  23341. if (activity)
  23342. activity->onCreate(ctx, _colocalParent);
  23343. }
  23344. }
  23345. virtual void abort()
  23346. {
  23347. ForEachItemIn(idx, sinks)
  23348. {
  23349. IRoxieServerActivity &sink = sinks.item(idx);
  23350. sink.stop(true);
  23351. }
  23352. }
  23353. virtual void reset()
  23354. {
  23355. ForEachItemIn(idx, sinks)
  23356. {
  23357. IRoxieServerActivity &sink = sinks.item(idx);
  23358. sink.reset();
  23359. }
  23360. }
  23361. Linked<IException> exception;
  23362. CriticalSection eCrit;
  23363. virtual void noteException(IException *E)
  23364. {
  23365. CriticalBlock b(eCrit);
  23366. if (!exception)
  23367. {
  23368. if (graphSlaveContext.queryDebugContext())
  23369. {
  23370. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  23371. }
  23372. exception.set(E);
  23373. }
  23374. }
  23375. virtual void checkAbort()
  23376. {
  23377. CriticalBlock b(eCrit);
  23378. if (exception)
  23379. throw exception.getLink();
  23380. }
  23381. virtual void execute()
  23382. {
  23383. results.setown(new CGraphResults);
  23384. doExecute(0, NULL);
  23385. }
  23386. //New child query code...
  23387. virtual IThorChildGraph * queryChildGraph()
  23388. {
  23389. return this;
  23390. }
  23391. virtual IEclGraphResults * queryLocalGraph()
  23392. {
  23393. return this;
  23394. }
  23395. virtual IRoxieServerChildGraph * queryLoopGraph()
  23396. {
  23397. return this;
  23398. }
  23399. inline unsigned queryId() const
  23400. {
  23401. return id;
  23402. }
  23403. inline unsigned queryLoopCounter() const
  23404. {
  23405. return loopCounter;
  23406. }
  23407. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  23408. {
  23409. if (sinks.ordinality()==1)
  23410. sinks.item(0).execute(parentExtractSize, parentExtract);
  23411. #ifdef PARALLEL_EXECUTE
  23412. else if (!probeManager && !graphDefinition.isSequential())
  23413. {
  23414. class casyncfor: public CAsyncFor
  23415. {
  23416. public:
  23417. IActivityGraph &parent;
  23418. unsigned parentExtractSize;
  23419. const byte * parentExtract;
  23420. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  23421. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  23422. void Do(unsigned i)
  23423. {
  23424. try
  23425. {
  23426. sinks.item(i).execute(parentExtractSize, parentExtract);
  23427. }
  23428. catch (IException *E)
  23429. {
  23430. parent.noteException(E);
  23431. throw;
  23432. }
  23433. }
  23434. private:
  23435. IRoxieServerActivityCopyArray &sinks;
  23436. } afor(sinks, *this, parentExtractSize, parentExtract);
  23437. afor.For(sinks.ordinality(), sinks.ordinality());
  23438. }
  23439. #endif
  23440. else
  23441. {
  23442. ForEachItemIn(idx, sinks)
  23443. {
  23444. IRoxieServerActivity &sink = sinks.item(idx);
  23445. sink.execute(parentExtractSize, parentExtract);
  23446. }
  23447. }
  23448. }
  23449. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  23450. {
  23451. CriticalBlock block(evaluateCrit);
  23452. results.setown(new CGraphResults);
  23453. try
  23454. {
  23455. doExecute(parentExtractSize, parentExtract);
  23456. }
  23457. catch (...)
  23458. {
  23459. DBGLOG("Exception thrown in child query - cleaning up");
  23460. reset();
  23461. throw;
  23462. }
  23463. reset();
  23464. return results.getClear();
  23465. }
  23466. //interface IRoxieServerChildGraph
  23467. virtual void beforeExecute()
  23468. {
  23469. results.setown(new CGraphResults);
  23470. }
  23471. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23472. {
  23473. IRoxieInput * ret = selectOutput(id);
  23474. ret->start(parentExtractSize, parentExtract, paused);
  23475. return ret;
  23476. }
  23477. virtual IRoxieInput * selectOutput(unsigned id)
  23478. {
  23479. ForEachItemIn(i, sinks)
  23480. {
  23481. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  23482. if (ret)
  23483. return ret;
  23484. }
  23485. throwUnexpected();
  23486. return NULL;
  23487. }
  23488. virtual void setInputResult(unsigned id, IGraphResult * result)
  23489. {
  23490. results->setResult(id, result);
  23491. }
  23492. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  23493. {
  23494. ForEachItemIn(i, activities)
  23495. {
  23496. if (activities.item(i).querySetStreamInput(id, input))
  23497. return true;
  23498. }
  23499. return false;
  23500. }
  23501. virtual void stopUnusedOutputs()
  23502. {
  23503. //Hmm not sure how to do this...
  23504. }
  23505. virtual void afterExecute()
  23506. {
  23507. ForEachItemIn(i, sinks)
  23508. {
  23509. sinks.item(i).stop(false);
  23510. }
  23511. if (graphSlaveContext.queryDebugContext())
  23512. {
  23513. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  23514. }
  23515. reset();
  23516. }
  23517. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  23518. {
  23519. doExecute(parentExtractSize, parentExtract);
  23520. return LINK(results);
  23521. }
  23522. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23523. {
  23524. results->getLinkedResult(count, ret, id);
  23525. }
  23526. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23527. {
  23528. results->getLinkedResult(count, ret, id);
  23529. }
  23530. virtual const void * getLinkedRowResult(unsigned id)
  23531. {
  23532. return results->getLinkedRowResult(id);
  23533. }
  23534. virtual void setResult(unsigned id, IGraphResult * result)
  23535. {
  23536. results->setResult(id, result);
  23537. }
  23538. virtual IRoxieInput * createResultIterator(unsigned id)
  23539. {
  23540. return results->createIterator(id);
  23541. }
  23542. virtual void setGraphLoopResult(IGraphResult * result)
  23543. {
  23544. graphLoopResults.appendResult(result);
  23545. }
  23546. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  23547. {
  23548. try
  23549. {
  23550. return graphLoopResults.createIterator(id);
  23551. }
  23552. catch (IException * e)
  23553. {
  23554. e->Release();
  23555. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  23556. }
  23557. }
  23558. virtual void clearGraphLoopResults()
  23559. {
  23560. graphLoopResults.clear();
  23561. }
  23562. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  23563. {
  23564. doExecute(parentExtractSize, parentExtract);
  23565. }
  23566. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  23567. {
  23568. graphLoopResults.setResult(id, result);
  23569. }
  23570. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  23571. {
  23572. return graphLoopResults.createIterator(id);
  23573. }
  23574. virtual void getProbeResponse(IPropertyTree *query)
  23575. {
  23576. if (probeManager)
  23577. probeManager->getProbeResponse(query);
  23578. }
  23579. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23580. {
  23581. throwUnexpected();
  23582. }
  23583. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23584. {
  23585. return NULL;
  23586. }
  23587. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23588. {
  23589. throwUnexpected();
  23590. }
  23591. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23592. {
  23593. throwUnexpected();
  23594. }
  23595. };
  23596. class CIterationActivityGraph : public CActivityGraph
  23597. {
  23598. IHThorArg * colocalParent;
  23599. unsigned fixedParentExtractSize;
  23600. const byte * fixedParentExtract;
  23601. unsigned graphOutputActivityIndex;
  23602. public:
  23603. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  23604. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  23605. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  23606. {
  23607. graphOutputActivityIndex = 0;
  23608. loopCounter = _loopCounter;
  23609. colocalParent = _colocalParent;
  23610. graphSlaveContext.set(ctx);
  23611. graphSlaveContext.setLoopCounter(loopCounter);
  23612. graphCodeContext.set(ctx->queryCodeContext());
  23613. fixedParentExtractSize = parentExtractSize;
  23614. fixedParentExtract = parentExtract;
  23615. }
  23616. void createIterationGraph()
  23617. {
  23618. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23619. ForEachItemIn(idx1, graphDefinition)
  23620. activities.append(*LINK(pseudoActivity));
  23621. graphOutputActivityIndex = queryGraphOutputIndex();
  23622. recursiveCreateGraph(graphOutputActivityIndex);
  23623. }
  23624. unsigned queryGraphOutputIndex() const
  23625. {
  23626. ForEachItemIn(i, graphDefinition)
  23627. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23628. return i;
  23629. throwUnexpected();
  23630. }
  23631. void recursiveCreateGraph(unsigned whichActivity)
  23632. {
  23633. //Check to see if already created
  23634. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23635. if (prevActivity.queryId() != 0)
  23636. {
  23637. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23638. return;
  23639. }
  23640. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23641. IRoxieServerActivity * activity = NULL;
  23642. if (donor.isGraphInvariant())
  23643. {
  23644. ThorActivityKind kind = donor.getKind();
  23645. switch (kind)
  23646. {
  23647. case TAKif:
  23648. case TAKchildif:
  23649. case TAKcase:
  23650. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23651. {
  23652. Owned<IHThorArg> helper = &donor.getHelper();
  23653. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23654. helper->onStart(fixedParentExtract, NULL);
  23655. unsigned branch;
  23656. switch (kind)
  23657. {
  23658. case TAKif: case TAKchildif:
  23659. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23660. break;
  23661. case TAKcase: case TAKchildcase:
  23662. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23663. if (branch >= donor.numInputs())
  23664. branch = donor.numInputs() - 1;
  23665. break;
  23666. default:
  23667. throwUnexpected();
  23668. }
  23669. helper.clear();
  23670. unsigned outputidx;
  23671. unsigned source = donor.getInput(branch, outputidx);
  23672. if (source ==(unsigned) -1)
  23673. activity = createRoxieServerNullActivity(&donor, probeManager);
  23674. else
  23675. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23676. activities.replace(*activity, whichActivity);
  23677. activity->onCreate(&graphSlaveContext, colocalParent);
  23678. if (source ==(unsigned) -1)
  23679. return;
  23680. recursiveCreateGraph(source);
  23681. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23682. break;
  23683. }
  23684. }
  23685. }
  23686. if (!activity)
  23687. {
  23688. activity = donor.createActivity(probeManager);
  23689. activities.replace(*activity, whichActivity);
  23690. activity->onCreate(&graphSlaveContext, colocalParent);
  23691. activity->resetOutputsUsed();
  23692. unsigned inputidx = 0;
  23693. loop
  23694. {
  23695. unsigned outputidx;
  23696. unsigned source = donor.getInput(inputidx, outputidx);
  23697. if (source==(unsigned) -1)
  23698. break;
  23699. recursiveCreateGraph(source);
  23700. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23701. inputidx++;
  23702. }
  23703. }
  23704. IntArray &dependencies = donor.queryDependencies();
  23705. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23706. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23707. ForEachItemIn(idx2, dependencies)
  23708. {
  23709. unsigned input = dependencies.item(idx2);
  23710. recursiveCreateGraph(input);
  23711. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23712. }
  23713. }
  23714. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23715. {
  23716. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23717. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23718. }
  23719. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23720. {
  23721. ForEachItemIn(i, activities)
  23722. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23723. }
  23724. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23725. {
  23726. ForEachItemIn(i, activities)
  23727. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23728. }
  23729. };
  23730. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23731. {
  23732. StringAttr graphName;
  23733. ActivityArray & graphDefinition;
  23734. IProbeManager *probeManager;
  23735. unsigned id;
  23736. IRoxieSlaveContext * ctx;
  23737. IHThorArg * colocalParent;
  23738. public:
  23739. IMPLEMENT_IINTERFACE;
  23740. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23741. : probeManager(_probeManager), graphDefinition(x)
  23742. {
  23743. graphName.set(_graphName);
  23744. id = _id;
  23745. ctx = NULL;
  23746. colocalParent = NULL;
  23747. }
  23748. virtual const char *queryName() const { return graphName.get(); }
  23749. virtual void abort() { throwUnexpected(); }
  23750. virtual void reset() { }
  23751. virtual void execute() { throwUnexpected(); }
  23752. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23753. virtual void noteException(IException *E) { throwUnexpected(); }
  23754. virtual void checkAbort() { throwUnexpected(); }
  23755. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23756. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23757. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23758. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23759. {
  23760. ctx = _ctx;
  23761. colocalParent = _colocalParent;
  23762. }
  23763. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23764. {
  23765. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23766. ret->createIterationGraph();
  23767. return ret.getClear();
  23768. }
  23769. };
  23770. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23771. {
  23772. if (childFactories.isDelayed())
  23773. {
  23774. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23775. }
  23776. else
  23777. {
  23778. Owned<IProbeManager> childProbe;
  23779. if (_probeManager)
  23780. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23781. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23782. ret->createGraph();
  23783. if (_probeManager)
  23784. _probeManager->endChildGraph(childProbe, parentActivity);
  23785. return ret.getClear();
  23786. }
  23787. }
  23788. //================================================================================================================
  23789. #ifdef _USE_CPPUNIT
  23790. #include "unittests.hpp"
  23791. // 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...
  23792. #if _MSC_VER==1200
  23793. #undef protected
  23794. #endif
  23795. static const char *sortAlgorithm;
  23796. class TestMetaData : public CInterface, implements IOutputMetaData
  23797. {
  23798. public:
  23799. IMPLEMENT_IINTERFACE;
  23800. virtual size32_t getRecordSize(const void *) { return 10; }
  23801. virtual size32_t getMinRecordSize() const { return 10; }
  23802. virtual size32_t getFixedSize() const { return 10; }
  23803. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23804. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23805. virtual unsigned getMetaFlags() { return 0; }
  23806. virtual void destruct(byte * self) {}
  23807. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23808. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23809. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23810. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23811. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23812. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23813. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23814. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  23815. } testMeta;
  23816. class TestInput : public CInterface, implements IRoxieInput
  23817. {
  23818. char const * const *input;
  23819. IRoxieSlaveContext *ctx;
  23820. unsigned endSeen;
  23821. bool eof;
  23822. unsigned count;
  23823. ActivityTimeAccumulator totalCycles;
  23824. size32_t recordSize;
  23825. unsigned activityId;
  23826. public:
  23827. enum { STATEreset, STATEstarted, STATEstopped } state;
  23828. bool allRead;
  23829. unsigned repeat;
  23830. IMPLEMENT_IINTERFACE;
  23831. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23832. {
  23833. ctx = _ctx;
  23834. input = _input;
  23835. count = 0;
  23836. eof = false;
  23837. allRead = false;
  23838. endSeen = 0;
  23839. recordSize = testMeta.getFixedSize();
  23840. state = STATEreset;
  23841. activityId = 1;
  23842. repeat = 0;
  23843. }
  23844. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23845. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23846. {
  23847. ASSERT(state == STATEreset);
  23848. }
  23849. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23850. {
  23851. ASSERT(state == STATEreset);
  23852. state = STATEstarted;
  23853. }
  23854. virtual IRoxieServerActivity *queryActivity()
  23855. {
  23856. throwUnexpected();
  23857. }
  23858. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23859. {
  23860. throwUnexpected();
  23861. }
  23862. virtual void stop(bool aborting)
  23863. {
  23864. state = STATEstopped;
  23865. }
  23866. virtual void reset()
  23867. {
  23868. ASSERT(state == STATEstopped);
  23869. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  23870. }
  23871. virtual void resetEOF()
  23872. {
  23873. throwUnexpected();
  23874. }
  23875. virtual void checkAbort() {}
  23876. virtual unsigned queryId() const { return activityId; };
  23877. virtual const void *nextInGroup()
  23878. {
  23879. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  23880. ASSERT(state == STATEstarted);
  23881. ASSERT(allRead || !eof);
  23882. if (eof)
  23883. return NULL;
  23884. again:
  23885. const char *nextSource = input[count++];
  23886. if (nextSource)
  23887. {
  23888. endSeen = 0;
  23889. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23890. memset(ret, 0, recordSize);
  23891. strncpy((char *) ret, nextSource, recordSize);
  23892. return ret;
  23893. }
  23894. else if (repeat)
  23895. {
  23896. repeat--;
  23897. count = 0;
  23898. goto again;
  23899. }
  23900. else
  23901. {
  23902. endSeen++;
  23903. if (endSeen==2)
  23904. eof = true;
  23905. return NULL;
  23906. }
  23907. }
  23908. virtual bool nextGroup(ConstPointerArray & group)
  23909. {
  23910. const void * next;
  23911. while ((next = nextInGroup()) != NULL)
  23912. group.append(next);
  23913. if (group.ordinality())
  23914. return true;
  23915. return false;
  23916. }
  23917. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  23918. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  23919. virtual IRoxieInput *queryInput(unsigned idx) const
  23920. {
  23921. return NULL;
  23922. }
  23923. };
  23924. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23925. public:
  23926. struct CompareClass : public ICompare {
  23927. virtual int docompare(const void * _left, const void * _right) const {
  23928. return memcmp(_left, _right, 5);
  23929. }
  23930. } compare;
  23931. virtual ICompare * queryCompare() { return &compare; }
  23932. virtual IOutputMetaData * queryOutputMeta()
  23933. {
  23934. return &testMeta;
  23935. }
  23936. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23937. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23938. };
  23939. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23940. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23941. static bool isDedup;
  23942. public:
  23943. struct CompareClass : public ICompare {
  23944. virtual int docompare(const void * _left, const void * _right) const {
  23945. return memcmp(_left, _right, 5);
  23946. }
  23947. } compare;
  23948. virtual ICompare * queryCompare() { return &compare; }
  23949. virtual IOutputMetaData * queryOutputMeta()
  23950. {
  23951. return &testMeta;
  23952. }
  23953. virtual bool dedup() { return isDedup; }
  23954. };
  23955. bool MergeActivityTest::isDedup = false;
  23956. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23957. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  23958. public:
  23959. virtual unsigned numBranches() { return 2; }
  23960. virtual IOutputMetaData * queryOutputMeta()
  23961. {
  23962. return &testMeta;
  23963. }
  23964. };
  23965. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  23966. class CcdServerTest : public CppUnit::TestFixture
  23967. {
  23968. CPPUNIT_TEST_SUITE(CcdServerTest);
  23969. CPPUNIT_TEST(testSetup);
  23970. CPPUNIT_TEST(testHeapSort);
  23971. CPPUNIT_TEST(testInsertionSort);
  23972. CPPUNIT_TEST(testQuickSort);
  23973. CPPUNIT_TEST(testMerge);
  23974. CPPUNIT_TEST(testMergeDedup);
  23975. CPPUNIT_TEST(testMiscellaneous);
  23976. CPPUNIT_TEST(testSplitter);
  23977. CPPUNIT_TEST(testCleanup);
  23978. CPPUNIT_TEST_SUITE_END();
  23979. protected:
  23980. SlaveContextLogger logctx;
  23981. Owned<const IQueryDll> queryDll;
  23982. Owned<IRoxiePackage> package;
  23983. Owned<IPropertyTree> stateInfo;
  23984. Owned<IQueryFactory> queryFactory;
  23985. Owned<IRoxieSlaveContext> ctx;
  23986. void testSetup()
  23987. {
  23988. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  23989. }
  23990. void testCleanup()
  23991. {
  23992. roxiemem::releaseRoxieHeap();
  23993. }
  23994. void init()
  23995. {
  23996. package.setown(createRoxiePackage(NULL, NULL));
  23997. queryDll.setown(createExeQueryDll("roxie"));
  23998. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  23999. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  24000. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  24001. queryActiveTimer()->reset();
  24002. }
  24003. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  24004. {
  24005. testActivity(activity, input, NULL, output);
  24006. }
  24007. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  24008. {
  24009. TestInput in(ctx, input);
  24010. TestInput in2(ctx, input2);
  24011. activity->setInput(0, &in);
  24012. if (input2)
  24013. activity->setInput(1, &in2);
  24014. IRoxieInput *out = activity->queryOutput(outputIdx);
  24015. IOutputMetaData *meta = out->queryOutputMeta();
  24016. void *buf = alloca(meta->getFixedSize());
  24017. for (unsigned iteration = 0; iteration < 8; iteration++)
  24018. {
  24019. // 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)
  24020. // This should be true whether we read all, some, or none of the data.
  24021. // Should not matter if an activity is not started
  24022. if (iteration % 4 == 0)
  24023. activity->onCreate(ctx, NULL);
  24024. unsigned count = 0;
  24025. if (iteration % 4 != 3)
  24026. {
  24027. activity->start(0, NULL, false);
  24028. ASSERT(in.state == TestInput::STATEstarted);
  24029. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  24030. loop
  24031. {
  24032. const void *next = out->nextInGroup();
  24033. if (!next)
  24034. {
  24035. ASSERT(output[count++] == NULL);
  24036. next = out->nextInGroup();
  24037. if (!next)
  24038. {
  24039. ASSERT(output[count++] == NULL);
  24040. break;
  24041. }
  24042. }
  24043. ASSERT(output[count] != NULL);
  24044. unsigned outsize = meta->getRecordSize(next);
  24045. memset(buf, 0, outsize);
  24046. strncpy((char *) buf, output[count++], outsize);
  24047. ASSERT(memcmp(next, buf, outsize) == 0);
  24048. ReleaseRoxieRow(next);
  24049. if (iteration % 4 == 2)
  24050. break;
  24051. }
  24052. if (iteration % 4 != 2)
  24053. {
  24054. // Check that reading after end is harmless
  24055. in.allRead = true;
  24056. const void *next = out->nextInGroup();
  24057. ASSERT(next == NULL);
  24058. }
  24059. }
  24060. activity->stop(false);
  24061. ASSERT(in.state == TestInput::STATEstopped);
  24062. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  24063. activity->reset();
  24064. ASSERT(in.state == TestInput::STATEreset);
  24065. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  24066. ctx->queryRowManager().reportLeaks();
  24067. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24068. }
  24069. }
  24070. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  24071. {
  24072. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24073. TestInput in(ctx, input);
  24074. in.repeat = repeat;
  24075. activity->setInput(0, &in);
  24076. ArrayOf<IRoxieInput *> out;
  24077. for (unsigned i = 0; i < numOutputs; i++)
  24078. {
  24079. out.append(activity->queryOutput(i));
  24080. }
  24081. activity->onCreate(ctx, NULL);
  24082. class casyncfor: public CAsyncFor
  24083. {
  24084. public:
  24085. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  24086. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  24087. {}
  24088. void Do(unsigned i)
  24089. {
  24090. IRoxieInput *out = outputs.item(i);
  24091. out->start(0, NULL, false);
  24092. IOutputMetaData *meta = out->queryOutputMeta();
  24093. void *buf = alloca(meta->getFixedSize());
  24094. unsigned count = 0;
  24095. unsigned repeats = repeat;
  24096. loop
  24097. {
  24098. const void *next = out->nextInGroup();
  24099. if (!next)
  24100. {
  24101. ASSERT(repeats==0);
  24102. ASSERT(output[count++] == NULL);
  24103. next = out->nextInGroup();
  24104. if (!next)
  24105. {
  24106. ASSERT(output[count++] == NULL);
  24107. break;
  24108. }
  24109. }
  24110. if (output[count] == NULL && repeats)
  24111. {
  24112. repeats--;
  24113. count = 0;
  24114. }
  24115. ASSERT(output[count] != NULL);
  24116. unsigned outsize = meta->getRecordSize(next);
  24117. memset(buf, 0, outsize);
  24118. strncpy((char *) buf, output[count++], outsize);
  24119. ASSERT(memcmp(next, buf, outsize) == 0);
  24120. ReleaseRoxieRow(next);
  24121. }
  24122. out->stop(false);
  24123. }
  24124. private:
  24125. IRoxieServerActivity *activity;
  24126. ArrayOf<IRoxieInput *> &outputs;
  24127. char const * const *input;
  24128. char const * const *output;
  24129. unsigned repeat;
  24130. CcdServerTest *parent;
  24131. } afor(this, activity, out, input, output, repeat);
  24132. afor.For(numOutputs, numOutputs);
  24133. ASSERT(in.state == TestInput::STATEstopped);
  24134. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  24135. {
  24136. out.item(i2)->reset();
  24137. }
  24138. ASSERT(in.state == TestInput::STATEreset);
  24139. ctx->queryRowManager().reportLeaks();
  24140. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24141. }
  24142. static int compareFunc(const void *l, const void *r)
  24143. {
  24144. return strcmp(*(char **) l, *(char **) r);
  24145. }
  24146. void testSort(unsigned type)
  24147. {
  24148. init();
  24149. sortAlgorithm = NULL;
  24150. if (type==2)
  24151. sortAlgorithm = "heapSort";
  24152. else if (type == 1)
  24153. sortAlgorithm = "insertionSort";
  24154. else
  24155. sortAlgorithm = "quickSort";
  24156. DBGLOG("Testing %s activity", sortAlgorithm);
  24157. Owned<IPropertyTree> dummyNode = createPTree("node");
  24158. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  24159. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24160. const char * test[] = { NULL, NULL };
  24161. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24162. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  24163. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24164. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24165. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24166. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24167. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24168. testActivity(activity, test, test);
  24169. testActivity(activity, test12345, test12345);
  24170. testActivity(activity, test54321, test12345);
  24171. testActivity(activity, test11111, test11111);
  24172. testActivity(activity, test11111_12345, test11111_12345);
  24173. testActivity(activity, test11111_54321, test11111_12345);
  24174. testActivity(activity, test54321_54321, test12345_12345);
  24175. // A few larger tests
  24176. char *input[2002];
  24177. char *output[2002];
  24178. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  24179. unsigned i;
  24180. // identical
  24181. for (i=0; i<2000; i++)
  24182. {
  24183. input[i] = new char[11];
  24184. output[i] = new char[11];
  24185. sprintf(input[i], "1");
  24186. sprintf(output[i], "1");
  24187. }
  24188. testActivity(activity, input, output);
  24189. // Ascending
  24190. for (i=0; i<2000; i++)
  24191. {
  24192. sprintf(input[i], "%04d", i);
  24193. sprintf(output[i], "%04d", i);
  24194. }
  24195. testActivity(activity, input, output);
  24196. // Almost sorted
  24197. for (i=0; i<20; i++)
  24198. {
  24199. unsigned h = i*100;
  24200. sprintf(input[h], "%04d", 1900-h);
  24201. }
  24202. testActivity(activity, input, output);
  24203. // Descending
  24204. for (i=0; i<2000; i++)
  24205. {
  24206. sprintf(input[i], "%04d", 1999-i);
  24207. sprintf(output[i], "%04d", i);
  24208. }
  24209. testActivity(activity, input, output);
  24210. // Random
  24211. for (i=0; i<2000; i++)
  24212. {
  24213. unsigned r = rand() % 1500;
  24214. sprintf(input[i], "%04d", r);
  24215. sprintf(output[i], "%04d", r);
  24216. }
  24217. qsort(output, 2000, sizeof(output[0]), compareFunc);
  24218. testActivity(activity, input, output);
  24219. #if 0
  24220. // Random
  24221. #define BIGSORTSIZE 1000000
  24222. char **linput = new char*[BIGSORTSIZE +2];
  24223. char **loutput = new char *[BIGSORTSIZE+2];
  24224. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  24225. for (i=0; i<BIGSORTSIZE; i++)
  24226. {
  24227. unsigned r = rand() % 15000;
  24228. linput[i] = loutput[i] = new char[11];
  24229. sprintf(linput[i], "%04d", r);
  24230. }
  24231. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  24232. testActivity(activity, linput, loutput);
  24233. for (i=0; i<BIGSORTSIZE; i++)
  24234. {
  24235. delete [] linput[i];
  24236. }
  24237. delete [] linput;
  24238. delete [] loutput;
  24239. #endif
  24240. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  24241. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  24242. factory->resetNodeProgressInfo();
  24243. if (type)
  24244. {
  24245. // Other than quicksort, it's supposed to be stable. Let's check that it is
  24246. // All sort identical
  24247. for (i=0; i<2000; i++)
  24248. {
  24249. sprintf(input[i], "1 %d", i);
  24250. sprintf(output[i], "1 %d", i);
  24251. }
  24252. testActivity(activity, input, output);
  24253. // Already sorted
  24254. for (i=0; i<2000; i++)
  24255. {
  24256. sprintf(input[i], "%04d %d", i / 10, i);
  24257. sprintf(output[i], "%04d %d", i / 10, i);
  24258. }
  24259. testActivity(activity, input, output);
  24260. // Reverse order
  24261. for (i=0; i<2000; i++)
  24262. {
  24263. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  24264. sprintf(output[i], "%04d %d", i / 10, i%10);
  24265. }
  24266. testActivity(activity, input, output);
  24267. }
  24268. for (i=0; i<2000; i++)
  24269. {
  24270. delete [] input[i];
  24271. delete [] output[i];
  24272. }
  24273. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  24274. }
  24275. void testQuickSort()
  24276. {
  24277. testSort(0);
  24278. }
  24279. void testInsertionSort()
  24280. {
  24281. testSort(1);
  24282. }
  24283. void testHeapSort()
  24284. {
  24285. testSort(2);
  24286. }
  24287. void testMerge()
  24288. {
  24289. DBGLOG("testMerge");
  24290. init();
  24291. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24292. factory->setInput(0,0,0);
  24293. factory->setInput(1,0,0);
  24294. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24295. const char * test[] = { NULL, NULL };
  24296. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24297. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  24298. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24299. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  24300. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24301. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24302. 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 };
  24303. testActivity(activity, test, test, test);
  24304. testActivity(activity, test12345, test, test12345);
  24305. testActivity(activity, test, test12345, test12345);
  24306. testActivity(activity, test12345, test12345, test1122334455);
  24307. testActivity(activity, test11111, test, test11111);
  24308. testActivity(activity, test, test11111, test11111);
  24309. testActivity(activity, test11111, test11111, test1111111111);
  24310. testActivity(activity, test11111_12345, test, test1111112345);
  24311. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  24312. // Should really test WHICH side gets kept...
  24313. // Should test with more than 2 inputs...
  24314. DBGLOG("testMerge done");
  24315. }
  24316. void testMergeDedup()
  24317. {
  24318. DBGLOG("testMergeDedup");
  24319. init();
  24320. MergeActivityTest::isDedup = true;
  24321. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24322. factory->setInput(0,0,0);
  24323. factory->setInput(1,0,0);
  24324. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24325. const char * test[] = { NULL, NULL };
  24326. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24327. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24328. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24329. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24330. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  24331. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  24332. testActivity(activity, test, test11111, test11111);
  24333. testActivity(activity, test, test, test);
  24334. testActivity(activity, test12345, test, test12345);
  24335. testActivity(activity, test, test12345, test12345);
  24336. testActivity(activity, test12345, test12345, test12345);
  24337. testActivity(activity, test11111_12345, test, test1111112345);
  24338. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  24339. // Should really test WHICH side gets kept...
  24340. // Should test with more than 2 inputs...
  24341. DBGLOG("testMergeDedup done");
  24342. }
  24343. void doTestSplitter(unsigned numOutputs)
  24344. {
  24345. DBGLOG("testSplit %d", numOutputs);
  24346. init();
  24347. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs);
  24348. factory->setInput(0,0,0);
  24349. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24350. const char * test[] = { NULL, NULL };
  24351. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24352. unsigned start = msTick();
  24353. testSplitActivity(factory, test, test, numOutputs, 0);
  24354. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  24355. testSplitActivity(factory, test12345, test12345, numOutputs, 1000000);
  24356. unsigned elapsed = msTick() - start;
  24357. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  24358. }
  24359. void testSplitter()
  24360. {
  24361. doTestSplitter(1);
  24362. doTestSplitter(2);
  24363. doTestSplitter(3);
  24364. doTestSplitter(10);
  24365. }
  24366. void testMiscellaneous()
  24367. {
  24368. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  24369. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  24370. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  24371. ASSERT(sizeof(CJoinGroup) <= 120);
  24372. }
  24373. };
  24374. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  24375. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  24376. #endif