ccdserver.cpp 875 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139
  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(unsigned statCode, unsigned __int64 value, unsigned count) const
  210. {
  211. ctx->noteStatistic(statCode, value, count);
  212. }
  213. virtual void CTXLOG(const char *format, ...) const
  214. {
  215. va_list args;
  216. va_start(args, format);
  217. ctx->CTXLOGva(format, args);
  218. va_end(args);
  219. }
  220. virtual void CTXLOGva(const char *format, va_list args) const
  221. {
  222. ctx->CTXLOGva(format, args);
  223. }
  224. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  225. {
  226. ctx->CTXLOGa(category, prefix, text);
  227. }
  228. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  229. {
  230. va_list args;
  231. va_start(args, format);
  232. ctx->logOperatorExceptionVA(E, file, line, format, args);
  233. va_end(args);
  234. }
  235. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  236. {
  237. ctx->logOperatorExceptionVA(E, file, line, format, args);
  238. }
  239. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  240. {
  241. va_list args;
  242. va_start(args, format);
  243. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  244. va_end(args);
  245. }
  246. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  247. {
  248. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  249. }
  250. virtual void CTXLOGl(LogItem *log) const
  251. {
  252. ctx->CTXLOGl(log);
  253. }
  254. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  255. {
  256. return ctx->getLogPrefix(ret);
  257. }
  258. virtual unsigned queryTraceLevel() const
  259. {
  260. return ctx->queryTraceLevel();
  261. }
  262. virtual bool isIntercepted() const
  263. {
  264. return ctx->isIntercepted();
  265. }
  266. virtual bool isBlind() const
  267. {
  268. return ctx->isBlind();
  269. }
  270. virtual unsigned parallelJoinPreload()
  271. {
  272. return ctx->parallelJoinPreload();
  273. }
  274. virtual unsigned concatPreload()
  275. {
  276. return ctx->concatPreload();
  277. }
  278. virtual unsigned fetchPreload()
  279. {
  280. return ctx->fetchPreload();
  281. }
  282. virtual unsigned fullKeyedJoinPreload()
  283. {
  284. return ctx->fullKeyedJoinPreload();
  285. }
  286. virtual unsigned keyedJoinPreload()
  287. {
  288. return ctx->keyedJoinPreload();
  289. }
  290. virtual unsigned prefetchProjectPreload()
  291. {
  292. return ctx->prefetchProjectPreload();
  293. }
  294. virtual void addSlavesReplyLen(unsigned len)
  295. {
  296. ctx->addSlavesReplyLen(len);
  297. }
  298. virtual const char *queryAuthToken()
  299. {
  300. return ctx->queryAuthToken();
  301. }
  302. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  303. {
  304. return ctx->resolveLFN(filename, isOpt);
  305. }
  306. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  307. {
  308. return ctx->createLFN(filename, overwrite, extend, clusters);
  309. }
  310. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  311. {
  312. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  313. }
  314. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  315. {
  316. return ctx->getLibraryGraph(extra, parentActivity);
  317. }
  318. virtual void noteProcessed(const IRoxieContextLogger &_activityContext, const IRoxieServerActivity *_activity, unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  319. {
  320. ctx->noteProcessed(_activityContext, _activity, _idx, _processed, _totalCycles, _localCycles);
  321. }
  322. virtual IProbeManager *queryProbeManager() const
  323. {
  324. return ctx->queryProbeManager();
  325. }
  326. virtual IDebuggableContext *queryDebugContext() const
  327. {
  328. return ctx->queryDebugContext();
  329. }
  330. virtual bool queryTimeActivities() const
  331. {
  332. return ctx->queryTimeActivities();
  333. }
  334. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  335. {
  336. ctx->printResults(output, name, sequence);
  337. }
  338. virtual void setWUState(WUState state)
  339. {
  340. ctx->setWUState(state);
  341. }
  342. virtual bool checkWuAborted()
  343. {
  344. return ctx->checkWuAborted();
  345. }
  346. virtual IWorkUnit *updateWorkUnit() const
  347. {
  348. return ctx->updateWorkUnit();
  349. }
  350. virtual IConstWorkUnit *queryWorkUnit() const
  351. {
  352. return ctx->queryWorkUnit();
  353. }
  354. virtual IRoxieServerContext *queryServerContext()
  355. {
  356. return ctx->queryServerContext();
  357. }
  358. virtual IWorkUnitRowReader *getWorkunitRowReader(const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  359. {
  360. return ctx->getWorkunitRowReader(name, sequence, xmlTransformer, rowAllocator, isGrouped);
  361. }
  362. protected:
  363. IRoxieSlaveContext * ctx;
  364. };
  365. //=================================================================================
  366. #define RESULT_FLUSH_THRESHOLD 10000u
  367. #ifdef _DEBUG
  368. #define SOAP_SPLIT_THRESHOLD 100u
  369. #define SOAP_SPLIT_RESERVE 200u
  370. #else
  371. #define SOAP_SPLIT_THRESHOLD 64000u
  372. #define SOAP_SPLIT_RESERVE 65535u
  373. #endif
  374. //=================================================================================
  375. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  376. {
  377. protected:
  378. IntArray dependencies; // things I am dependent on
  379. IntArray dependencyIndexes; // things I am dependent on
  380. IntArray dependencyControlIds; // things I am dependent on
  381. StringArray dependencyEdgeIds; // How to describe them to the debugger
  382. unsigned dependentCount; // things dependent on me
  383. mutable CriticalSection statsCrit;
  384. mutable __int64 processed;
  385. mutable __int64 started;
  386. mutable __int64 totalCycles;
  387. mutable __int64 localCycles;
  388. public:
  389. IMPLEMENT_IINTERFACE;
  390. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  391. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  392. {
  393. processed = 0;
  394. started = 0;
  395. totalCycles = 0;
  396. localCycles = 0;
  397. dependentCount = 0;
  398. }
  399. ~CRoxieServerActivityFactoryBase()
  400. {
  401. }
  402. StringBuffer &toString(StringBuffer &ret) const
  403. {
  404. return ret.appendf("%p", this);
  405. }
  406. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  407. {
  408. dependencies.append(_source);
  409. dependencyIndexes.append(_sourceIdx);
  410. dependencyControlIds.append(controlId);
  411. dependencyEdgeIds.append(edgeId);
  412. }
  413. virtual void noteDependent(unsigned target)
  414. {
  415. dependentCount++;
  416. }
  417. virtual IntArray &queryDependencies() { return dependencies; }
  418. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  419. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  420. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  421. virtual unsigned queryId() const { return id; }
  422. virtual unsigned querySubgraphId() const { return subgraphId; }
  423. virtual ThorActivityKind getKind() const { return kind; }
  424. virtual IOutputMetaData * queryOutputMeta() const
  425. {
  426. return meta;
  427. }
  428. virtual bool isSink() const
  429. {
  430. return false;
  431. }
  432. virtual bool isFunction() const
  433. {
  434. return false;
  435. }
  436. virtual bool isGraphInvariant() const
  437. {
  438. return false;
  439. }
  440. virtual IHThorArg &getHelper() const
  441. {
  442. return *helperFactory();
  443. }
  444. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  445. {
  446. arg.Release();
  447. throwUnexpected();
  448. }
  449. virtual void noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  450. {
  451. if (_processed || _totalCycles || _localCycles)
  452. {
  453. CriticalBlock b(statsCrit);
  454. #ifdef _DEBUG
  455. assertex(_totalCycles >= _localCycles);
  456. #endif
  457. processed += _processed;
  458. totalCycles += _totalCycles;
  459. localCycles += _localCycles;
  460. }
  461. }
  462. virtual void noteStarted() const
  463. {
  464. CriticalBlock b(statsCrit);
  465. started ++;
  466. }
  467. virtual void noteStarted(unsigned idx) const
  468. {
  469. throwUnexpected(); // should be implemented/required by multiOutput cases only
  470. }
  471. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  472. {
  473. CriticalBlock b(statsCrit);
  474. if (output == 0)
  475. {
  476. putStatsValue(&edge, "count", "sum", processed);
  477. if (started)
  478. putStatsValue(&edge, "started", "sum", started);
  479. }
  480. else
  481. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  482. }
  483. virtual void getNodeProgressInfo(IPropertyTree &node) const
  484. {
  485. CActivityFactory::getNodeProgressInfo(node);
  486. CriticalBlock b(statsCrit);
  487. if (started)
  488. putStatsValue(&node, "_roxieStarted", "sum", started);
  489. if (totalCycles)
  490. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  491. if (localCycles)
  492. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  493. }
  494. virtual void resetNodeProgressInfo()
  495. {
  496. CActivityFactory::resetNodeProgressInfo();
  497. CriticalBlock b(statsCrit);
  498. 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 noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  562. {
  563. mystats.noteStatistic(statCode, value, count);
  564. }
  565. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  566. {
  567. // Most activities have nothing to say...
  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 noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  713. {
  714. assertex(numOutputs ? idx < numOutputs : idx==0);
  715. CriticalBlock b(statsCrit);
  716. processedArray[idx] += _processed;
  717. totalCycles += _totalCycles;
  718. localCycles += _localCycles;
  719. }
  720. virtual void noteStarted(unsigned idx) const
  721. {
  722. assertex(numOutputs ? idx < numOutputs : idx==0);
  723. CriticalBlock b(statsCrit);
  724. startedArray[idx] = true;
  725. }
  726. };
  727. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  728. {
  729. protected:
  730. bool isInternal;
  731. bool isRoot;
  732. unsigned usageCount;
  733. public:
  734. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  735. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  736. {
  737. usageCount = _usageCount;
  738. isRoot = _isRoot;
  739. isInternal = false; // filled in by derived class constructor
  740. }
  741. virtual bool isSink() const
  742. {
  743. //only a sink if a root activity
  744. 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?
  745. }
  746. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  747. {
  748. // 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
  749. // Just leave it blank is safest.
  750. }
  751. };
  752. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  753. const char *queryStateText(activityState state)
  754. {
  755. switch (state)
  756. {
  757. case STATEreset: return "reset";
  758. case STATEstarted: return "started";
  759. case STATEstopped: return "stopped";
  760. case STATEstarting: return "starting";
  761. default: return "unknown";
  762. }
  763. }
  764. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  765. class CParallelActivityExecutor : public CAsyncFor
  766. {
  767. public:
  768. unsigned parentExtractSize;
  769. const byte * parentExtract;
  770. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  771. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  772. void Do(unsigned i)
  773. {
  774. activities.item(i).execute(parentExtractSize, parentExtract);
  775. }
  776. private:
  777. IRoxieServerActivityCopyArray & activities;
  778. };
  779. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  780. {
  781. protected:
  782. IRoxieInput *input;
  783. IHThorArg &basehelper;
  784. IRoxieSlaveContext *ctx;
  785. const IRoxieServerActivityFactory *factory;
  786. IRoxieServerActivityCopyArray dependencies;
  787. IntArray dependencyControlIds;
  788. IArrayOf<IActivityGraph> childGraphs;
  789. CachedOutputMetaData meta;
  790. IHThorArg *colocalParent;
  791. IEngineRowAllocator *rowAllocator;
  792. CriticalSection statecrit;
  793. mutable StatsCollector stats;
  794. unsigned processed;
  795. unsigned __int64 totalCycles;
  796. unsigned activityId;
  797. activityState state;
  798. bool createPending;
  799. bool debugging;
  800. public:
  801. IMPLEMENT_IINTERFACE;
  802. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  803. : factory(_factory),
  804. basehelper(_factory->getHelper()),
  805. activityId(_factory->queryId())
  806. {
  807. input = NULL;
  808. ctx = NULL;
  809. meta.set(basehelper.queryOutputMeta());
  810. processed = 0;
  811. totalCycles = 0;
  812. if (factory)
  813. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  814. state=STATEreset;
  815. rowAllocator = NULL;
  816. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  817. colocalParent = NULL;
  818. createPending = true;
  819. }
  820. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper)
  821. {
  822. activityId = 0;
  823. input = NULL;
  824. ctx = NULL;
  825. meta.set(basehelper.queryOutputMeta());
  826. processed = 0;
  827. totalCycles = 0;
  828. state=STATEreset;
  829. rowAllocator = NULL;
  830. debugging = false;
  831. colocalParent = NULL;
  832. createPending = true;
  833. }
  834. inline ~CRoxieServerActivity()
  835. {
  836. CriticalBlock cb(statecrit);
  837. if (traceStartStop)
  838. DBGLOG("%p destroy state=%s", this, queryStateText(state)); // Note- CTXLOG may not be safe
  839. if (state!=STATEreset)
  840. {
  841. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  842. state = STATEreset; // bit pointless but there you go...
  843. }
  844. basehelper.Release();
  845. ::Release(rowAllocator);
  846. }
  847. virtual const IRoxieContextLogger &queryLogCtx()const
  848. {
  849. return *this;
  850. }
  851. inline void createRowAllocator()
  852. {
  853. if (!rowAllocator)
  854. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  855. }
  856. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  857. virtual void CTXLOG(const char *format, ...) const
  858. {
  859. va_list args;
  860. va_start(args, format);
  861. CTXLOGva(format, args);
  862. va_end(args);
  863. }
  864. virtual void CTXLOGva(const char *format, va_list args) const
  865. {
  866. StringBuffer text, prefix;
  867. getLogPrefix(prefix);
  868. text.valist_appendf(format, args);
  869. CTXLOGa(LOG_TRACING, prefix.str(), text.str());
  870. }
  871. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  872. {
  873. if (ctx)
  874. ctx->CTXLOGa(category, prefix, text);
  875. else
  876. DBGLOG("[%s] %s", prefix, text);
  877. }
  878. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  879. {
  880. va_list args;
  881. va_start(args, format);
  882. StringBuffer prefix;
  883. getLogPrefix(prefix);
  884. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  885. va_end(args);
  886. }
  887. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  888. {
  889. StringBuffer prefix;
  890. getLogPrefix(prefix);
  891. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  892. }
  893. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  894. {
  895. va_list args;
  896. va_start(args, format);
  897. CTXLOGaeva(E, file, line, prefix, format, args);
  898. va_end(args);
  899. }
  900. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  901. {
  902. if (ctx)
  903. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  904. else
  905. {
  906. StringBuffer ss;
  907. ss.appendf("[%s] ERROR", prefix);
  908. if (E)
  909. ss.append(": ").append(E->errorCode());
  910. if (file)
  911. ss.appendf(": %s(%d) ", file, line);
  912. if (E)
  913. E->errorMessage(ss.append(": "));
  914. if (format)
  915. {
  916. ss.append(": ").valist_appendf(format, args);
  917. }
  918. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  919. }
  920. }
  921. virtual void CTXLOGl(LogItem *log) const
  922. {
  923. if (ctx)
  924. ctx->CTXLOGl(log);
  925. else
  926. {
  927. assert(ctx);
  928. log->Release(); // Should never happen
  929. }
  930. }
  931. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  932. {
  933. if (factory)
  934. factory->noteStatistic(statCode, value, count);
  935. if (ctx)
  936. ctx->noteStatistic(statCode, value, count);
  937. stats.noteStatistic(statCode, value, count);
  938. }
  939. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  940. {
  941. if (ctx)
  942. ctx->getLogPrefix(ret);
  943. return ret.append('@').append(activityId);
  944. }
  945. virtual bool isIntercepted() const
  946. {
  947. return ctx ? ctx->isIntercepted() : false;
  948. }
  949. virtual bool isBlind() const
  950. {
  951. return ctx ? ctx->isBlind() : blindLogging;
  952. }
  953. virtual unsigned queryTraceLevel() const
  954. {
  955. if (ctx)
  956. return ctx->queryTraceLevel();
  957. else
  958. return traceLevel;
  959. }
  960. virtual bool isPassThrough()
  961. {
  962. return false;
  963. }
  964. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  965. {
  966. return ctx->resolveLFN(filename, isOpt);
  967. }
  968. virtual const IResolvedFile *queryVarFileInfo() const
  969. {
  970. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  971. return NULL;
  972. }
  973. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  974. {
  975. throwUnexpected(); // should be implemented in more derived class wherever needed
  976. }
  977. virtual IRoxieSlaveContext *queryContext()
  978. {
  979. return ctx;
  980. }
  981. virtual IRoxieServerActivity *queryActivity() { return this; }
  982. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  983. virtual bool needsAllocator() const { return false; }
  984. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  985. {
  986. ctx = _ctx;
  987. colocalParent = _colocalParent;
  988. createPending = true;
  989. if (needsAllocator())
  990. createRowAllocator();
  991. processed = 0;
  992. totalCycles = 0;
  993. if (factory)
  994. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  995. }
  996. virtual void serializeCreateStartContext(MemoryBuffer &out)
  997. {
  998. //This should only be called after onStart has been called on the helper
  999. assertex(!createPending);
  1000. assertex(state==STATEstarted);
  1001. unsigned startlen = out.length();
  1002. basehelper.serializeCreateContext(out);
  1003. basehelper.serializeStartContext(out);
  1004. if (queryTraceLevel() > 10)
  1005. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1006. }
  1007. virtual void serializeExtra(MemoryBuffer &out) {}
  1008. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1009. {
  1010. CriticalBlock cb(statecrit);
  1011. if (state != STATEreset && state != STATEstarting)
  1012. {
  1013. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1014. }
  1015. state=STATEstarted;
  1016. #ifdef TRACE_STARTSTOP
  1017. if (traceStartStop)
  1018. {
  1019. CTXLOG("start %d", activityId);
  1020. if (watchActivityId && watchActivityId==activityId)
  1021. {
  1022. CTXLOG("WATCH: start %d", activityId);
  1023. }
  1024. }
  1025. #endif
  1026. executeDependencies(parentExtractSize, parentExtract, 0);
  1027. if (input)
  1028. input->start(parentExtractSize, parentExtract, paused);
  1029. ensureCreated();
  1030. basehelper.onStart(parentExtract, NULL);
  1031. if (factory)
  1032. factory->noteStarted();
  1033. }
  1034. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1035. {
  1036. //MORE: Create a filtered list and then use asyncfor
  1037. ForEachItemIn(idx, dependencies)
  1038. {
  1039. if (dependencyControlIds.item(idx) == controlId)
  1040. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1041. }
  1042. }
  1043. virtual unsigned __int64 queryTotalCycles() const
  1044. {
  1045. return totalCycles;
  1046. }
  1047. virtual unsigned __int64 queryLocalCycles() const
  1048. {
  1049. __int64 ret = totalCycles;
  1050. if (input) ret -= input->queryTotalCycles();
  1051. if (ret < 0)
  1052. ret = 0;
  1053. return ret;
  1054. }
  1055. virtual IRoxieInput *queryInput(unsigned idx) const
  1056. {
  1057. if (idx==0)
  1058. return input;
  1059. else
  1060. return NULL;
  1061. }
  1062. void noteProcessed(unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  1063. {
  1064. if (factory)
  1065. {
  1066. if (!debugging)
  1067. factory->noteProcessed(_idx, _processed, _totalCycles, _localCycles);
  1068. if (ctx)
  1069. ctx->noteProcessed(*this, this, _idx, _processed, _totalCycles, _localCycles);
  1070. }
  1071. }
  1072. inline void ensureCreated()
  1073. {
  1074. if (createPending)
  1075. {
  1076. createPending = false;
  1077. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1078. }
  1079. }
  1080. inline void stop(bool aborting)
  1081. {
  1082. if (state != STATEstopped)
  1083. {
  1084. CriticalBlock cb(statecrit);
  1085. if (state != STATEstopped)
  1086. {
  1087. state=STATEstopped;
  1088. #ifdef TRACE_STARTSTOP
  1089. if (traceStartStop)
  1090. {
  1091. CTXLOG("stop %d", activityId);
  1092. if (watchActivityId && watchActivityId==activityId)
  1093. {
  1094. CTXLOG("WATCH: stop %d", activityId);
  1095. }
  1096. }
  1097. #endif
  1098. if (input)
  1099. input->stop(aborting);
  1100. }
  1101. }
  1102. }
  1103. inline void reset()
  1104. {
  1105. if (state != STATEreset)
  1106. {
  1107. CriticalBlock cb(statecrit);
  1108. if (state != STATEreset)
  1109. {
  1110. if (state==STATEstarted || state==STATEstarting)
  1111. {
  1112. CTXLOG("STATE: activity %d reset without stop", activityId);
  1113. stop(false);
  1114. }
  1115. if (ctx->queryTimeActivities())
  1116. {
  1117. stats.dumpStats(*this);
  1118. StringBuffer prefix, text;
  1119. getLogPrefix(prefix);
  1120. text.appendf("records processed - %d", processed);
  1121. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1122. text.clear().appendf("total time - %d us", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  1123. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1124. text.clear().appendf("local time - %d us", (unsigned) (cycle_to_nanosec(queryLocalCycles())/1000));
  1125. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1126. }
  1127. state = STATEreset;
  1128. #ifdef TRACE_STARTSTOP
  1129. if (traceStartStop)
  1130. {
  1131. CTXLOG("reset %d", activityId);
  1132. if (watchActivityId && watchActivityId==activityId)
  1133. {
  1134. CTXLOG("WATCH: reset %d", activityId);
  1135. }
  1136. }
  1137. #endif
  1138. ForEachItemIn(idx, dependencies)
  1139. dependencies.item(idx).reset();
  1140. noteProcessed(0, processed, totalCycles, queryLocalCycles());
  1141. if (input)
  1142. input->reset();
  1143. processed = 0;
  1144. totalCycles = 0;
  1145. }
  1146. }
  1147. }
  1148. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1149. {
  1150. dependencies.append(source);
  1151. dependencyControlIds.append(controlId);
  1152. }
  1153. virtual void resetEOF()
  1154. {
  1155. //would make more sense if the default implementation (and eof member) were in the base class
  1156. }
  1157. // Sink activities should override this....
  1158. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1159. {
  1160. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1161. }
  1162. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1163. {
  1164. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1165. }
  1166. virtual __int64 evaluate()
  1167. {
  1168. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1169. }
  1170. virtual IRoxieInput * querySelectOutput(unsigned id)
  1171. {
  1172. return NULL;
  1173. }
  1174. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1175. {
  1176. return false;
  1177. }
  1178. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1179. {
  1180. assertex(!idx);
  1181. input = _in;
  1182. }
  1183. virtual IRoxieInput *queryOutput(unsigned idx)
  1184. {
  1185. if (idx == (unsigned) -1)
  1186. idx = 0;
  1187. return idx ? NULL : this;
  1188. }
  1189. virtual IOutputMetaData *queryOutputMeta() const
  1190. {
  1191. return meta.queryOriginal();
  1192. }
  1193. virtual unsigned queryId() const
  1194. {
  1195. return activityId;
  1196. }
  1197. virtual unsigned querySubgraphId() const
  1198. {
  1199. return factory->querySubgraphId();
  1200. }
  1201. virtual void checkAbort()
  1202. {
  1203. ctx->checkAbort();
  1204. }
  1205. IException *makeWrappedException(IException *e)
  1206. {
  1207. StringBuffer msg;
  1208. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1209. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1210. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1211. return e;
  1212. else
  1213. return new CWrappedException(e, activityKind, activityId);
  1214. }
  1215. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1216. {
  1217. }
  1218. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1219. {
  1220. }
  1221. virtual void resetOutputsUsed()
  1222. {
  1223. }
  1224. virtual void noteOutputUsed()
  1225. {
  1226. }
  1227. virtual IRoxieServerSideCache *queryServerSideCache() const
  1228. {
  1229. return factory->queryServerSideCache();
  1230. }
  1231. virtual const IRoxieServerActivityFactory *queryFactory() const
  1232. {
  1233. return factory;
  1234. }
  1235. inline ThorActivityKind getKind() const
  1236. {
  1237. return factory->getKind();
  1238. }
  1239. inline bool isSink() const
  1240. {
  1241. return (factory != NULL) && factory->isSink();
  1242. }
  1243. };
  1244. //=====================================================================================================
  1245. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1246. {
  1247. protected:
  1248. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1249. bool prefiltered;
  1250. bool eof;
  1251. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1252. {
  1253. prefiltered = !any;
  1254. eof = prefiltered;
  1255. if (!prefiltered)
  1256. input->start(parentExtractSize, parentExtract, false);
  1257. else
  1258. {
  1259. if (traceStartStop)
  1260. CTXLOG("lateStart activity stopping input early as prefiltered");
  1261. input->stop(false);
  1262. }
  1263. }
  1264. public:
  1265. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1266. : CRoxieServerActivity(_factory, _probeManager)
  1267. {
  1268. input = NULL;
  1269. prefiltered = false;
  1270. eof = false;
  1271. }
  1272. virtual void stop(bool aborting)
  1273. {
  1274. if (!prefiltered)
  1275. {
  1276. input->stop(aborting);
  1277. }
  1278. else if (traceStartStop)
  1279. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1280. CRoxieServerActivity::stop(aborting);
  1281. }
  1282. virtual unsigned __int64 queryLocalCycles() const
  1283. {
  1284. __int64 localCycles = totalCycles - input->queryTotalCycles();
  1285. if (localCycles < 0)
  1286. localCycles = 0;
  1287. return localCycles;
  1288. }
  1289. virtual IRoxieInput *queryInput(unsigned idx) const
  1290. {
  1291. if (idx==0)
  1292. return input;
  1293. else
  1294. return NULL;
  1295. }
  1296. virtual void reset()
  1297. {
  1298. CRoxieServerActivity::reset();
  1299. input->reset();
  1300. prefiltered = false;
  1301. }
  1302. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1303. {
  1304. assertex(!idx);
  1305. input = _in;
  1306. }
  1307. };
  1308. //=====================================================================================================
  1309. atomic_t nextInstanceId;
  1310. extern unsigned getNextInstanceId()
  1311. {
  1312. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1313. }
  1314. atomic_t nextRuid;
  1315. ruid_t getNextRuid()
  1316. {
  1317. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1318. while (ret < RUID_FIRST)
  1319. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1320. return ret;
  1321. }
  1322. void setStartRuid(unsigned restarts)
  1323. {
  1324. atomic_set(&nextRuid, restarts * 0x10000);
  1325. atomic_set(&nextInstanceId, restarts * 10000);
  1326. }
  1327. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1328. class LimitSkipException : public CInterface, public IException
  1329. {
  1330. int code;
  1331. public:
  1332. LimitSkipException(int _code) { code = _code; }
  1333. IMPLEMENT_IINTERFACE;
  1334. virtual int errorCode() const { return code; }
  1335. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1336. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1337. };
  1338. IException *makeLimitSkipException(bool isKeyed)
  1339. {
  1340. // We need to make sure what we throw is IException not something derived from it....
  1341. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1342. }
  1343. //=================================================================================
  1344. interface IRecordPullerCallback : extends IExceptionHandler
  1345. {
  1346. virtual void processRow(const void *row) = 0;
  1347. virtual void processEOG() = 0;
  1348. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1349. virtual void processDone() = 0;
  1350. };
  1351. class RecordPullerThread : public RestartableThread
  1352. {
  1353. protected:
  1354. IRoxieInput *input;
  1355. IRecordPullerCallback *helper;
  1356. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1357. bool groupAtOnce, eof, eog;
  1358. CriticalSection crit;
  1359. public:
  1360. RecordPullerThread(bool _groupAtOnce)
  1361. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1362. {
  1363. input = NULL;
  1364. helper = NULL;
  1365. eof = eog = FALSE;
  1366. }
  1367. inline unsigned __int64 queryTotalCycles() const
  1368. {
  1369. return input->queryTotalCycles();
  1370. }
  1371. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1372. {
  1373. helper = _helper;
  1374. input = _input;
  1375. }
  1376. IRoxieInput *queryInput() const
  1377. {
  1378. return input;
  1379. }
  1380. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1381. {
  1382. eof = false;
  1383. eog = false;
  1384. input->start(parentExtractSize, parentExtract, paused);
  1385. try
  1386. {
  1387. if (preload && !paused)
  1388. {
  1389. if (traceLevel > 4)
  1390. DBGLOG("Preload fetching first %d records", preload);
  1391. if (groupAtOnce)
  1392. pullGroups(preload);
  1393. else
  1394. pullRecords(preload);
  1395. }
  1396. if (eof)
  1397. {
  1398. if (traceLevel > 4)
  1399. DBGLOG("No need to start puller after preload");
  1400. helper->processDone();
  1401. }
  1402. else
  1403. {
  1404. if (!noThread)
  1405. {
  1406. StringBuffer logPrefix("[");
  1407. if (ctx) ctx->getLogPrefix(logPrefix);
  1408. logPrefix.append("] ");
  1409. RestartableThread::start(logPrefix);
  1410. started.wait();
  1411. }
  1412. }
  1413. }
  1414. catch (IException *e)
  1415. {
  1416. helper->fireException(e);
  1417. }
  1418. catch (...)
  1419. {
  1420. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1421. }
  1422. }
  1423. void stop(bool aborting)
  1424. {
  1425. if (traceStartStop)
  1426. DBGLOG("RecordPullerThread::stop");
  1427. {
  1428. 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.
  1429. input->stop(aborting);
  1430. }
  1431. RestartableThread::join();
  1432. }
  1433. void reset()
  1434. {
  1435. input->reset();
  1436. }
  1437. virtual int run()
  1438. {
  1439. started.signal();
  1440. try
  1441. {
  1442. if (groupAtOnce)
  1443. pullGroups((unsigned) -1);
  1444. else
  1445. pullRecords((unsigned) -1);
  1446. helper->processDone();
  1447. }
  1448. catch (IException *e)
  1449. {
  1450. helper->fireException(e);
  1451. }
  1452. catch (...)
  1453. {
  1454. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1455. }
  1456. return 0;
  1457. }
  1458. void done()
  1459. {
  1460. helper->processDone();
  1461. }
  1462. bool pullRecords(unsigned preload)
  1463. {
  1464. if (eof)
  1465. return false;
  1466. while (preload)
  1467. {
  1468. const void * row;
  1469. {
  1470. CriticalBlock c(crit); // See comments in stop for why this is needed
  1471. row = input->nextInGroup();
  1472. }
  1473. if (row)
  1474. {
  1475. eog = false;
  1476. helper->processRow(row);
  1477. }
  1478. else if (!eog)
  1479. {
  1480. helper->processEOG();
  1481. eog = true;
  1482. }
  1483. else
  1484. {
  1485. eof = true;
  1486. return false;
  1487. }
  1488. if (preload != (unsigned) -1)
  1489. preload--;
  1490. }
  1491. return true;
  1492. }
  1493. void pullGroups(unsigned preload)
  1494. {
  1495. ConstPointerArray thisGroup;
  1496. unsigned rowsDone = 0;
  1497. while (preload && !eof)
  1498. {
  1499. const void *row;
  1500. {
  1501. CriticalBlock c(crit);
  1502. row = input->nextInGroup();
  1503. }
  1504. if (row)
  1505. {
  1506. thisGroup.append(row);
  1507. rowsDone++;
  1508. }
  1509. else if (thisGroup.length())
  1510. {
  1511. helper->processGroup(thisGroup);
  1512. thisGroup.kill();
  1513. if (preload != (unsigned) -1)
  1514. {
  1515. if (preload > rowsDone)
  1516. preload -= rowsDone;
  1517. else
  1518. break;
  1519. }
  1520. rowsDone = 0;
  1521. }
  1522. else
  1523. {
  1524. eof = true;
  1525. break;
  1526. }
  1527. }
  1528. }
  1529. };
  1530. //=================================================================================
  1531. #define READAHEAD_SIZE 1000
  1532. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1533. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1534. {
  1535. QueueOf<const void, true> buffer;
  1536. InterruptableSemaphore ready;
  1537. InterruptableSemaphore space;
  1538. CriticalSection crit;
  1539. bool eof;
  1540. bool disabled;
  1541. RecordPullerThread puller;
  1542. unsigned preload;
  1543. unsigned __int64 totalCycles;
  1544. IRoxieSlaveContext *ctx;
  1545. public:
  1546. IMPLEMENT_IINTERFACE;
  1547. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1548. {
  1549. eof = false;
  1550. disabled = false;
  1551. totalCycles = 0;
  1552. ctx = NULL;
  1553. }
  1554. void onCreate(IRoxieSlaveContext *_ctx)
  1555. {
  1556. ctx = _ctx;
  1557. disabled = (ctx->queryDebugContext() != NULL);
  1558. }
  1559. virtual IRoxieServerActivity *queryActivity()
  1560. {
  1561. return puller.queryInput()->queryActivity();
  1562. }
  1563. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1564. {
  1565. return puller.queryInput()->queryIndexReadActivity();
  1566. }
  1567. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1568. {
  1569. eof = false;
  1570. totalCycles = 0;
  1571. if (disabled)
  1572. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1573. else
  1574. {
  1575. space.reinit(READAHEAD_SIZE);
  1576. ready.reinit();
  1577. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1578. }
  1579. }
  1580. virtual void stop(bool aborting)
  1581. {
  1582. if (disabled)
  1583. puller.queryInput()->stop(aborting);
  1584. else
  1585. {
  1586. space.interrupt();
  1587. ready.interrupt();
  1588. puller.stop(aborting);
  1589. }
  1590. }
  1591. virtual void reset()
  1592. {
  1593. if (disabled)
  1594. puller.queryInput()->reset();
  1595. else
  1596. {
  1597. puller.reset();
  1598. ForEachItemIn(idx1, buffer)
  1599. ReleaseRoxieRow(buffer.item(idx1));
  1600. buffer.clear();
  1601. }
  1602. }
  1603. virtual void resetEOF()
  1604. {
  1605. throwUnexpected();
  1606. }
  1607. virtual IOutputMetaData * queryOutputMeta() const
  1608. {
  1609. return puller.queryInput()->queryOutputMeta();
  1610. }
  1611. virtual void checkAbort()
  1612. {
  1613. puller.queryInput()->checkAbort();
  1614. }
  1615. void setInput(unsigned idx, IRoxieInput *_in)
  1616. {
  1617. assertex(!idx);
  1618. puller.setInput(this, _in);
  1619. }
  1620. virtual unsigned __int64 queryTotalCycles() const
  1621. {
  1622. return totalCycles;
  1623. }
  1624. virtual unsigned __int64 queryLocalCycles() const
  1625. {
  1626. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1627. if (ret < 0) ret = 0;
  1628. return ret;
  1629. }
  1630. virtual IRoxieInput *queryInput(unsigned idx) const
  1631. {
  1632. return puller.queryInput()->queryInput(idx);
  1633. }
  1634. virtual const void * nextInGroup()
  1635. {
  1636. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  1637. if (disabled)
  1638. return puller.queryInput()->nextInGroup();
  1639. else
  1640. {
  1641. loop
  1642. {
  1643. {
  1644. CriticalBlock b(crit);
  1645. if (eof && !buffer.ordinality())
  1646. return NULL; // eof
  1647. }
  1648. ready.wait();
  1649. const void *ret;
  1650. {
  1651. CriticalBlock b(crit);
  1652. ret = buffer.dequeue();
  1653. }
  1654. space.signal();
  1655. return ret;
  1656. }
  1657. }
  1658. }
  1659. virtual unsigned queryId() const { throwUnexpected(); }
  1660. virtual bool fireException(IException *e)
  1661. {
  1662. // called from puller thread on failure
  1663. ready.interrupt(LINK(e));
  1664. space.interrupt(e);
  1665. return true;
  1666. }
  1667. virtual void processRow(const void *row)
  1668. {
  1669. {
  1670. CriticalBlock b(crit);
  1671. buffer.enqueue(row);
  1672. }
  1673. ready.signal();
  1674. space.wait();
  1675. }
  1676. virtual void processGroup(const ConstPointerArray &rows)
  1677. {
  1678. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1679. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1680. // if group was larger than max(space)
  1681. {
  1682. CriticalBlock b(crit);
  1683. ForEachItemIn(idx, rows)
  1684. buffer.enqueue(rows.item(idx));
  1685. buffer.enqueue(NULL);
  1686. }
  1687. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1688. {
  1689. ready.signal();
  1690. space.wait();
  1691. }
  1692. }
  1693. virtual void processEOG()
  1694. {
  1695. // Used when output is not grouped - just ignore
  1696. }
  1697. virtual void processDone()
  1698. {
  1699. CriticalBlock b(crit);
  1700. eof = true;
  1701. ready.signal();
  1702. }
  1703. };
  1704. //=================================================================================
  1705. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1706. {
  1707. protected:
  1708. IRoxieInput *input1;
  1709. Owned<CRoxieServerReadAheadInput> puller;
  1710. public:
  1711. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1712. : CRoxieServerActivity(_factory, _probeManager)
  1713. {
  1714. input1 = NULL;
  1715. }
  1716. ~CRoxieServerTwoInputActivity()
  1717. {
  1718. }
  1719. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1720. {
  1721. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1722. input1->start(parentExtractSize, parentExtract, paused);
  1723. }
  1724. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1725. {
  1726. if (puller)
  1727. puller->onCreate(_ctx);
  1728. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1729. }
  1730. virtual void stop(bool aborting)
  1731. {
  1732. input1->stop(aborting);
  1733. CRoxieServerActivity::stop(aborting);
  1734. }
  1735. virtual unsigned __int64 queryLocalCycles() const
  1736. {
  1737. __int64 ret;
  1738. __int64 inputCycles = input->queryTotalCycles();
  1739. __int64 input1Cycles = input1->queryTotalCycles();
  1740. if (puller)
  1741. ret = totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1742. else
  1743. ret = totalCycles - (inputCycles + input1Cycles);
  1744. if (ret < 0)
  1745. ret = 0;
  1746. return ret;
  1747. }
  1748. virtual IRoxieInput *queryInput(unsigned idx) const
  1749. {
  1750. switch (idx)
  1751. {
  1752. case 0:
  1753. return input;
  1754. case 1:
  1755. return input1;
  1756. default:
  1757. return NULL;
  1758. }
  1759. }
  1760. virtual void reset()
  1761. {
  1762. CRoxieServerActivity::reset();
  1763. if (input1)
  1764. input1->reset();
  1765. }
  1766. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1767. {
  1768. switch(idx)
  1769. {
  1770. case 0:
  1771. input = _in;
  1772. break;
  1773. case 1:
  1774. input1 = _in;
  1775. break;
  1776. default:
  1777. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1778. }
  1779. }
  1780. };
  1781. //=================================================================================
  1782. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1783. {
  1784. protected:
  1785. unsigned numInputs;
  1786. IRoxieInput **inputArray;
  1787. public:
  1788. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1789. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1790. {
  1791. inputArray = new IRoxieInput*[numInputs];
  1792. for (unsigned i = 0; i < numInputs; i++)
  1793. inputArray[i] = NULL;
  1794. }
  1795. ~CRoxieServerMultiInputBaseActivity()
  1796. {
  1797. delete [] inputArray;
  1798. }
  1799. virtual unsigned __int64 queryLocalCycles() const
  1800. {
  1801. __int64 localCycles = totalCycles;
  1802. for (unsigned i = 0; i < numInputs; i++)
  1803. localCycles -= inputArray[i]->queryTotalCycles();
  1804. if (localCycles < 0)
  1805. localCycles = 0;
  1806. return localCycles;
  1807. }
  1808. virtual IRoxieInput *queryInput(unsigned idx) const
  1809. {
  1810. if (idx < numInputs)
  1811. return inputArray[idx];
  1812. else
  1813. return NULL;
  1814. }
  1815. virtual void reset()
  1816. {
  1817. for (unsigned i = 0; i < numInputs; i++)
  1818. inputArray[i]->reset();
  1819. CRoxieServerActivity::reset();
  1820. }
  1821. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1822. {
  1823. inputArray[idx] = _in;
  1824. }
  1825. };
  1826. //=================================================================================
  1827. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1828. {
  1829. public:
  1830. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1831. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1832. {
  1833. }
  1834. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1835. {
  1836. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1837. for (unsigned i = 0; i < numInputs; i++)
  1838. {
  1839. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1840. }
  1841. }
  1842. virtual void stop(bool aborting)
  1843. {
  1844. for (unsigned i = 0; i < numInputs; i++)
  1845. {
  1846. inputArray[i]->stop(aborting);
  1847. }
  1848. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1849. }
  1850. };
  1851. //=====================================================================================================
  1852. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1853. {
  1854. protected:
  1855. bool executed;
  1856. CriticalSection ecrit;
  1857. Owned<IException> exception;
  1858. public:
  1859. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1860. : CRoxieServerActivity(_factory, _probeManager)
  1861. {
  1862. executed = false;
  1863. }
  1864. virtual void reset()
  1865. {
  1866. executed = false;
  1867. exception.clear();
  1868. CRoxieServerActivity::reset();
  1869. }
  1870. virtual IRoxieInput *queryOutput(unsigned idx)
  1871. {
  1872. return NULL;
  1873. }
  1874. virtual const void *nextInGroup()
  1875. {
  1876. throwUnexpected(); // I am nobody's input
  1877. }
  1878. virtual void onExecute() = 0;
  1879. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1880. {
  1881. CriticalBlock b(ecrit);
  1882. if (exception)
  1883. throw exception.getLink();
  1884. if (!executed)
  1885. {
  1886. try
  1887. {
  1888. start(parentExtractSize, parentExtract, false);
  1889. {
  1890. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // unfortunately this is not really best place for seeing in debugger.
  1891. onExecute();
  1892. }
  1893. stop(false);
  1894. executed = true;
  1895. }
  1896. catch (IException *E)
  1897. {
  1898. exception.set(E); // (or maybe makeWrappedException?)
  1899. stop(true);
  1900. throw;
  1901. }
  1902. catch (...)
  1903. {
  1904. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1905. stop(true);
  1906. throw;
  1907. }
  1908. }
  1909. }
  1910. };
  1911. //=================================================================================
  1912. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1913. {
  1914. protected:
  1915. Owned<IMessageResult> result;
  1916. Owned<IRoxieQueryPacket> packet;
  1917. Linked<IRoxieServerQueryPacket> continuation;
  1918. unsigned hash;
  1919. unsigned seq;
  1920. unsigned lastDebugSequence;
  1921. Owned<IRoxieQueryPacket> lastDebugResponse;
  1922. ILRUChain *prev;
  1923. ILRUChain *next;
  1924. bool delayed;
  1925. public:
  1926. IMPLEMENT_IINTERFACE;
  1927. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1928. {
  1929. hash = 0;
  1930. seq = 0;
  1931. prev = NULL;
  1932. next = NULL;
  1933. delayed = false;
  1934. lastDebugSequence = 0;
  1935. }
  1936. virtual IRoxieQueryPacket *queryPacket() const
  1937. {
  1938. return packet;
  1939. }
  1940. virtual bool isContinuation() const
  1941. {
  1942. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1943. }
  1944. virtual bool isDelayed() const
  1945. {
  1946. return delayed;
  1947. }
  1948. virtual bool isEnd() const
  1949. {
  1950. return false;
  1951. }
  1952. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1953. {
  1954. return false;
  1955. }
  1956. virtual bool hasResult() const
  1957. {
  1958. return result != NULL;
  1959. }
  1960. virtual bool hasContinuation() const
  1961. {
  1962. return continuation != NULL;
  1963. }
  1964. virtual void setDelayed(bool _delayed)
  1965. {
  1966. delayed = _delayed;
  1967. }
  1968. virtual void setPacket(IRoxieQueryPacket *_packet)
  1969. {
  1970. packet.setown(_packet);
  1971. }
  1972. virtual void setSequence(unsigned _seq)
  1973. {
  1974. assertex(!IsShared());
  1975. seq = _seq;
  1976. }
  1977. virtual unsigned getSequence() const
  1978. {
  1979. return seq;
  1980. }
  1981. IMessageResult *getResult()
  1982. {
  1983. return result.getLink();
  1984. }
  1985. IMessageResult *queryResult()
  1986. {
  1987. return result;
  1988. }
  1989. void setResult(IMessageResult *r)
  1990. {
  1991. result.setown(r);
  1992. }
  1993. IRoxieServerQueryPacket *queryContinuation()
  1994. {
  1995. return continuation;
  1996. }
  1997. void setContinuation(IRoxieServerQueryPacket *c)
  1998. {
  1999. continuation.setown(c);
  2000. }
  2001. virtual unsigned queryHash() const
  2002. {
  2003. return hash;
  2004. }
  2005. virtual void setHash(unsigned _hash)
  2006. {
  2007. hash = _hash;
  2008. }
  2009. virtual ILRUChain *queryPrev() const { return prev; }
  2010. virtual ILRUChain *queryNext() const { return next; }
  2011. virtual void setPrev(ILRUChain *p) { prev = p; }
  2012. virtual void setNext(ILRUChain *n) { next = n; }
  2013. virtual void unchain()
  2014. {
  2015. if (prev && next)
  2016. {
  2017. prev->setNext(next);
  2018. next->setPrev(prev);
  2019. }
  2020. next = NULL;
  2021. prev = NULL;
  2022. }
  2023. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2024. {
  2025. if (sequence == lastDebugSequence)
  2026. return lastDebugResponse.getLink();
  2027. else if (sequence > lastDebugSequence)
  2028. {
  2029. lastDebugResponse.clear();
  2030. return NULL;
  2031. }
  2032. else
  2033. throwUnexpected();
  2034. }
  2035. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2036. {
  2037. lastDebugSequence = sequence;
  2038. lastDebugResponse.set(response);
  2039. }
  2040. };
  2041. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2042. {
  2043. public:
  2044. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2045. {
  2046. }
  2047. virtual bool isEnd() const
  2048. {
  2049. return true;
  2050. }
  2051. };
  2052. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2053. {
  2054. unsigned __int64 rowLimit;
  2055. unsigned __int64 keyedLimit;
  2056. unsigned __int64 stopAfter;
  2057. public:
  2058. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2059. {
  2060. rowLimit = _rowLimit;
  2061. keyedLimit = _keyedLimit;
  2062. stopAfter = _stopAfter;
  2063. }
  2064. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2065. {
  2066. _rowLimit = rowLimit;
  2067. _keyedLimit = keyedLimit;
  2068. _stopAfter = stopAfter;
  2069. return true;
  2070. }
  2071. };
  2072. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2073. {
  2074. protected:
  2075. unsigned cacheTableSize;
  2076. unsigned cacheTableSpace;
  2077. IRoxieServerQueryPacket **cacheTable;
  2078. mutable ILRUChain *prev;
  2079. mutable ILRUChain *next;
  2080. mutable CriticalSection crit;
  2081. virtual ILRUChain *queryPrev() const { return prev; }
  2082. virtual ILRUChain *queryNext() const { return next; }
  2083. virtual void setPrev(ILRUChain *p) { prev = p; }
  2084. virtual void setNext(ILRUChain *n) { next = n; }
  2085. virtual void unchain()
  2086. {
  2087. prev->setNext(next);
  2088. next->setPrev(prev);
  2089. next = NULL;
  2090. prev = NULL;
  2091. }
  2092. void moveToHead(IRoxieServerQueryPacket *mru)
  2093. {
  2094. mru->unchain();
  2095. mru->setNext(next);
  2096. next->setPrev(mru);
  2097. mru->setPrev(this);
  2098. next = mru;
  2099. }
  2100. IRoxieServerQueryPacket *removeLRU()
  2101. {
  2102. if (next==this)
  2103. assertex(next != this);
  2104. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2105. goer->unchain(); // NOTE - this will modify the value of next
  2106. return goer;
  2107. }
  2108. void removeEntry(IRoxieServerQueryPacket *goer)
  2109. {
  2110. unsigned v = goer->queryHash() % cacheTableSize;
  2111. loop
  2112. {
  2113. IRoxieServerQueryPacket *found = cacheTable[v];
  2114. assertex(found);
  2115. if (found == goer)
  2116. {
  2117. cacheTable[v] = NULL;
  2118. unsigned vn = v;
  2119. loop
  2120. {
  2121. vn++;
  2122. if (vn==cacheTableSize) vn = 0;
  2123. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2124. if (!found2)
  2125. break;
  2126. unsigned vm = found2->queryHash() % cacheTableSize;
  2127. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2128. {
  2129. cacheTable[v] = found2;
  2130. v = vn;
  2131. cacheTable[v] = NULL;
  2132. }
  2133. }
  2134. cacheTableSpace++;
  2135. break;
  2136. }
  2137. v++;
  2138. if (v==cacheTableSize)
  2139. v = 0;
  2140. }
  2141. goer->Release();
  2142. }
  2143. public:
  2144. CRoxieServerSideCache(unsigned _cacheSize)
  2145. {
  2146. cacheTableSize = (_cacheSize*4)/3;
  2147. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2148. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2149. cacheTableSpace = _cacheSize;
  2150. prev = this;
  2151. next = this;
  2152. }
  2153. ~CRoxieServerSideCache()
  2154. {
  2155. for (unsigned i = 0; i < cacheTableSize; i++)
  2156. {
  2157. ::Release(cacheTable[i]);
  2158. }
  2159. delete [] cacheTable;
  2160. }
  2161. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2162. {
  2163. unsigned hash = p->hash();
  2164. unsigned et = hash % cacheTableSize;
  2165. if (traceServerSideCache)
  2166. {
  2167. StringBuffer s;
  2168. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2169. }
  2170. CriticalBlock b(crit);
  2171. loop
  2172. {
  2173. IRoxieServerQueryPacket *found = cacheTable[et];
  2174. if (!found)
  2175. return NULL;
  2176. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2177. {
  2178. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2179. if (traceServerSideCache)
  2180. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2181. logctx.noteStatistic(STATS_SERVERCACHEHIT, 1, 1);
  2182. return NULL;
  2183. // Because IMessageResult cannot be replayed, this echeme is flawed. I'm leaving the code here just as a stats gatherer to see how useful it would have been....
  2184. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2185. //ret->setResult(found->getResult());
  2186. //return ret;
  2187. }
  2188. et++;
  2189. if (et == cacheTableSize)
  2190. et = 0;
  2191. }
  2192. }
  2193. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2194. {
  2195. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2196. {
  2197. unsigned hash = out->queryPacket()->hash();
  2198. out->setHash(hash);
  2199. unsigned et = hash % cacheTableSize;
  2200. if (traceServerSideCache)
  2201. {
  2202. StringBuffer s;
  2203. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2204. }
  2205. CriticalBlock b(crit);
  2206. loop
  2207. {
  2208. IRoxieServerQueryPacket *found = cacheTable[et];
  2209. if (!found)
  2210. {
  2211. if (cacheTableSpace)
  2212. {
  2213. out->setResult(LINK(in));
  2214. cacheTable[et] = LINK(out);
  2215. cacheTableSpace--;
  2216. moveToHead(out);
  2217. break;
  2218. }
  2219. else
  2220. {
  2221. IRoxieServerQueryPacket *goer = removeLRU();
  2222. removeEntry(goer);
  2223. et = hash % cacheTableSize;
  2224. continue;
  2225. }
  2226. }
  2227. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2228. {
  2229. moveToHead(found);
  2230. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2231. // multiple copies of a slave query are in-flight at once.
  2232. }
  2233. et++;
  2234. if (et == cacheTableSize)
  2235. et = 0;
  2236. }
  2237. }
  2238. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2239. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2240. }
  2241. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2242. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2243. // more than make up for it
  2244. };
  2245. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2246. {
  2247. ConstPointerArray &data;
  2248. Linked<IMessageResult> result;
  2249. public:
  2250. IMPLEMENT_IINTERFACE;
  2251. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2252. : data(_data), result(_result)
  2253. {
  2254. }
  2255. virtual bool atEOF() const
  2256. {
  2257. return data.length()==0;
  2258. }
  2259. virtual bool isSerialized() const
  2260. {
  2261. return false;
  2262. }
  2263. virtual const void * getNext(int length)
  2264. {
  2265. if (!data.length())
  2266. return NULL;
  2267. const void *ret = data.item(0);
  2268. data.remove(0);
  2269. return ret;
  2270. }
  2271. };
  2272. // MORE - should possibly move more over to the lazy version used in indexread?
  2273. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2274. {
  2275. ConstPointerArray data;
  2276. IRowManager &rowManager;
  2277. bool variableSize;
  2278. public:
  2279. IMPLEMENT_IINTERFACE;
  2280. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2281. {
  2282. }
  2283. ~CRowArrayMessageResult()
  2284. {
  2285. ReleaseRoxieRowSet(data);
  2286. }
  2287. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2288. {
  2289. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2290. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2291. }
  2292. virtual const void *getMessageHeader(unsigned &length) const
  2293. {
  2294. throwUnexpected(); // should never get called - I don't have a header available
  2295. length = 0;
  2296. return NULL;
  2297. }
  2298. virtual const void *getMessageMetadata(unsigned &length) const
  2299. {
  2300. length = 0;
  2301. return NULL;
  2302. }
  2303. virtual void discard() const
  2304. {
  2305. throwUnexpected();
  2306. }
  2307. void append(const void *row)
  2308. {
  2309. data.append(row);
  2310. }
  2311. };
  2312. void throwRemoteException(IMessageUnpackCursor *extra)
  2313. {
  2314. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2315. if (rowlen)
  2316. {
  2317. char *xml = (char *) extra->getNext(*rowlen);
  2318. ReleaseRoxieRow(rowlen);
  2319. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2320. ReleaseRoxieRow(xml);
  2321. unsigned code = p->getPropInt("Code", 0);
  2322. const char *msg = p->queryProp("Message");
  2323. if (!msg)
  2324. msg = xml;
  2325. throw MakeStringException(code, "%s", msg);
  2326. }
  2327. throwUnexpected();
  2328. }
  2329. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2330. {
  2331. friend class CRemoteResultMerger;
  2332. class CRemoteResultMerger
  2333. {
  2334. class HeapEntry : public CInterface
  2335. {
  2336. private:
  2337. CRemoteResultAdaptor &adaptor;
  2338. IMessageUnpackCursor *cursor;
  2339. public:
  2340. const void *current;
  2341. bool isLast;
  2342. bool lastIsComplete;
  2343. IRoxieServerQueryPacket *packet;
  2344. unsigned seq;
  2345. public:
  2346. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2347. {
  2348. cursor = _cursor;
  2349. lastIsComplete = _lastIsComplete;
  2350. return next();
  2351. }
  2352. public:
  2353. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2354. {
  2355. cursor = NULL;
  2356. current = NULL;
  2357. isLast = false;
  2358. lastIsComplete = true;
  2359. }
  2360. ~HeapEntry()
  2361. {
  2362. ::Release(packet);
  2363. ::Release(cursor);
  2364. ReleaseRoxieRow(current);
  2365. }
  2366. bool isCompleteMatch() const
  2367. {
  2368. if (!isLast || lastIsComplete)
  2369. return true;
  2370. else
  2371. return false;
  2372. }
  2373. const void *next()
  2374. {
  2375. if (cursor)
  2376. {
  2377. ReleaseClearRoxieRow(current);
  2378. current = adaptor.getRow(cursor);
  2379. isLast = cursor->atEOF();
  2380. if (!current)
  2381. {
  2382. cursor->Release();
  2383. cursor = NULL;
  2384. }
  2385. }
  2386. return current;
  2387. }
  2388. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2389. {
  2390. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2391. unsigned skipped = 0;
  2392. loop
  2393. {
  2394. int c = compare->docompare(current, seek, numFields);
  2395. //If larger than the seek values, then we may be allowed to return an inexact match,
  2396. //if equal then it is required to be an exact match,
  2397. if (c > 0)
  2398. {
  2399. if (!requireExactMatch || isCompleteMatch())
  2400. break;
  2401. }
  2402. else if ((c == 0) && isCompleteMatch())
  2403. break;
  2404. skipped++;
  2405. if (!next())
  2406. break;
  2407. }
  2408. return skipped;
  2409. }
  2410. };
  2411. CRemoteResultAdaptor &adaptor;
  2412. CIArrayOf<HeapEntry> heapEntries;
  2413. UnsignedArray heap;
  2414. IRowManager *rowManager;
  2415. unsigned numPending;
  2416. unsigned numFields;
  2417. bool endSeen;
  2418. bool remakePending;
  2419. IRangeCompare *compare;
  2420. bool deferredContinuation;
  2421. inline int doCompare(unsigned l, unsigned r)
  2422. {
  2423. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2424. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2425. return ret;
  2426. }
  2427. void makeHeap()
  2428. {
  2429. /* Permute blocks to establish the heap property
  2430. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2431. The children of p must both be greater than or equal to p
  2432. The parent of a child c is given by p = (c-1)/2
  2433. */
  2434. unsigned i;
  2435. unsigned n = heap.length();
  2436. unsigned *s = heap.getArray();
  2437. for (i=1; i<n; i++)
  2438. {
  2439. unsigned r = s[i];
  2440. int c = i; /* child */
  2441. while (c > 0)
  2442. {
  2443. int p = (c-1)/2; /* parent */
  2444. if ( doCompare( s[c], s[p] ) >= 0 )
  2445. break;
  2446. s[c] = s[p];
  2447. s[p] = r;
  2448. c = p;
  2449. }
  2450. }
  2451. remakePending = false;
  2452. }
  2453. void remakeHeap()
  2454. {
  2455. /* The row associated with block[0] will have changed
  2456. This code restores the heap property
  2457. */
  2458. unsigned p = 0; /* parent */
  2459. unsigned n = heap.length();
  2460. unsigned *s = heap.getArray();
  2461. while (1)
  2462. {
  2463. unsigned c = p*2 + 1; /* child */
  2464. if ( c >= n )
  2465. break;
  2466. /* Select smaller child */
  2467. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2468. /* If child is greater or equal than parent then we are done */
  2469. if ( doCompare( s[c], s[p] ) >= 0 )
  2470. break;
  2471. /* Swap parent and child */
  2472. unsigned r = s[c];
  2473. s[c] = s[p];
  2474. s[p] = r;
  2475. /* child becomes parent */
  2476. p = c;
  2477. }
  2478. remakePending = false;
  2479. }
  2480. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2481. {
  2482. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2483. IMessageResult *result = p->queryResult();
  2484. assertex(result);
  2485. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2486. {
  2487. heapEntries.append(h);
  2488. heap.append(heap.ordinality());
  2489. }
  2490. else
  2491. h.Release();
  2492. }
  2493. void removeHeap(unsigned idx)
  2494. {
  2495. heapEntries.remove(idx);
  2496. ForEachItemIn(i, heap)
  2497. {
  2498. unsigned v = heap.item(i);
  2499. assertex(v != idx);
  2500. if (v > idx)
  2501. heap.replace(v-1, i);
  2502. }
  2503. }
  2504. bool isCompleteMatchFlag(IMessageResult *result)
  2505. {
  2506. unsigned metaLen;
  2507. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2508. if (metaLen)
  2509. {
  2510. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2511. if (continuationLen >= sizeof(bool))
  2512. {
  2513. metaInfo += sizeof(unsigned short);
  2514. return *(bool *) metaInfo;
  2515. }
  2516. }
  2517. return true; // if no continuation info, last row was complete.
  2518. }
  2519. public:
  2520. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2521. {
  2522. init(NULL, NULL);
  2523. }
  2524. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2525. {
  2526. if (meta)
  2527. {
  2528. numFields = meta->getNumFields();
  2529. compare = meta->queryCompare();
  2530. }
  2531. else
  2532. {
  2533. numFields = 0;
  2534. compare = NULL;
  2535. }
  2536. rowManager = _rowManager;
  2537. numPending = 0;
  2538. endSeen = false;
  2539. remakePending = false;
  2540. deferredContinuation = false;
  2541. }
  2542. void reset()
  2543. {
  2544. heapEntries.kill();
  2545. heap.kill();
  2546. numPending = 0;
  2547. endSeen = false;
  2548. remakePending = false;
  2549. deferredContinuation = false;
  2550. }
  2551. inline bool noteEndSeen()
  2552. {
  2553. bool hadSeen = endSeen;
  2554. if (!endSeen)
  2555. makeHeap();
  2556. endSeen = true;
  2557. return !hadSeen;
  2558. }
  2559. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2560. {
  2561. if (!p->isContinuation())
  2562. append(p, seq);
  2563. else
  2564. {
  2565. ForEachItemIn(idx, heapEntries)
  2566. {
  2567. HeapEntry &h = heapEntries.item(idx);
  2568. if (h.packet == p)
  2569. {
  2570. IMessageResult *result = p->queryResult();
  2571. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2572. {
  2573. heap.zap(idx);
  2574. removeHeap(idx);
  2575. }
  2576. numPending--;
  2577. if (!numPending)
  2578. makeHeap();
  2579. return;
  2580. }
  2581. }
  2582. }
  2583. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2584. return;
  2585. }
  2586. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2587. {
  2588. HeapEntry &entry = heapEntries.item(idx);
  2589. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2590. if (!entry.current)
  2591. {
  2592. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2593. if (continuation)
  2594. {
  2595. continuation->Link();
  2596. entry.packet->Release();
  2597. entry.packet = continuation;
  2598. if (continuation->hasResult())
  2599. {
  2600. IMessageResult *result = continuation->queryResult();
  2601. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2602. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2603. }
  2604. else
  2605. {
  2606. if (continuation->isDelayed())
  2607. {
  2608. continuation->setDelayed(false);
  2609. MemoryBuffer serializedSkip;
  2610. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2611. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2612. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2613. adaptor.sentsome.signal();
  2614. }
  2615. numPending++;
  2616. }
  2617. }
  2618. else
  2619. {
  2620. heap.zap(idx);
  2621. removeHeap(idx);
  2622. idx--;
  2623. }
  2624. }
  2625. return skipped;
  2626. }
  2627. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2628. {
  2629. // We discard all rows < seekval from all entries in heap
  2630. // If this results in additional slave requests, we return NULL so that we can wait for them
  2631. // If not, we rebuild the heap (if any were skipped) and return the first row
  2632. deferredContinuation = false;
  2633. if (heap.length())
  2634. {
  2635. unsigned skipped = 0;
  2636. unsigned idx = 0;
  2637. while(heapEntries.isItem(idx))
  2638. {
  2639. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2640. idx++;
  2641. }
  2642. if (numPending)
  2643. return NULL; // can't answer yet, need more results from slaves
  2644. else
  2645. {
  2646. if (skipped)
  2647. makeHeap();
  2648. return next(wasCompleteMatch, stepExtra);
  2649. }
  2650. }
  2651. else
  2652. return NULL;
  2653. }
  2654. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2655. {
  2656. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2657. if (continuation)
  2658. {
  2659. if (continuation->isDelayed() && canDefer)
  2660. {
  2661. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2662. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2663. deferredContinuation = true;
  2664. }
  2665. else
  2666. {
  2667. deferredContinuation = false;
  2668. continuation->Link();
  2669. topEntry.packet->Release();
  2670. topEntry.packet = continuation;
  2671. if (continuation->hasResult())
  2672. {
  2673. IMessageResult *result = continuation->queryResult();
  2674. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2675. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2676. }
  2677. else
  2678. {
  2679. if (continuation->isDelayed()) // has the continuation been requested yet?
  2680. {
  2681. continuation->Link();
  2682. topEntry.packet->Release();
  2683. topEntry.packet = continuation;
  2684. continuation->setDelayed(false);
  2685. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2686. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2687. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2688. adaptor.sentsome.signal();
  2689. }
  2690. numPending++; // we are waiting for one that is already in flight
  2691. }
  2692. }
  2693. return true; // next not known yet
  2694. }
  2695. else
  2696. return false;
  2697. }
  2698. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2699. {
  2700. OwnedConstRoxieRow ret;
  2701. if (heap.length())
  2702. {
  2703. if (deferredContinuation)
  2704. {
  2705. unsigned top = heap.item(0);
  2706. HeapEntry &topEntry = heapEntries.item(top);
  2707. doContinuation(topEntry, false);
  2708. return NULL;
  2709. }
  2710. if (remakePending)
  2711. remakeHeap();
  2712. unsigned top = heap.item(0);
  2713. HeapEntry &topEntry = heapEntries.item(top);
  2714. ret.set(topEntry.current);
  2715. wasCompleteMatch = topEntry.isCompleteMatch();
  2716. const void *next = topEntry.next();
  2717. if (!next)
  2718. {
  2719. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2720. {
  2721. unsigned last = heap.pop();
  2722. if (heap.length())
  2723. heap.replace(last, 0);
  2724. removeHeap(top);
  2725. }
  2726. }
  2727. remakePending = true;
  2728. }
  2729. return ret.getClear();
  2730. }
  2731. bool ready()
  2732. {
  2733. return endSeen && numPending == 0;
  2734. }
  2735. };
  2736. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2737. {
  2738. if (serverSideCache && !debugContext)
  2739. {
  2740. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2741. if (ret)
  2742. {
  2743. p->Release();
  2744. cached = true;
  2745. return ret;
  2746. }
  2747. }
  2748. cached = false;
  2749. return new CRoxieServerQueryPacket(p);
  2750. }
  2751. #ifdef _DEBUG
  2752. void dumpPending()
  2753. {
  2754. CriticalBlock b(pendingCrit);
  2755. ForEachItemIn(idx, pending)
  2756. {
  2757. IRoxieServerQueryPacket &p = pending.item(idx);
  2758. StringBuffer s;
  2759. unsigned __int64 dummy;
  2760. if (p.isEnd())
  2761. s.append("END");
  2762. else if (p.isLimit(dummy, dummy, dummy))
  2763. s.append("LIMIT");
  2764. else
  2765. {
  2766. IRoxieQueryPacket *i = p.queryPacket();
  2767. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2768. if (i)
  2769. {
  2770. RoxiePacketHeader &header = i->queryHeader();
  2771. header.toString(s);
  2772. }
  2773. }
  2774. DBGLOG("Pending %d %s", idx, s.str());
  2775. }
  2776. }
  2777. #endif
  2778. void abortPending()
  2779. {
  2780. CriticalBlock b(pendingCrit);
  2781. ForEachItemIn(idx, pending)
  2782. {
  2783. IRoxieServerQueryPacket &p = pending.item(idx);
  2784. if (!p.hasResult())
  2785. {
  2786. IRoxieQueryPacket *i = p.queryPacket();
  2787. if (i)
  2788. {
  2789. RoxiePacketHeader &header = i->queryHeader();
  2790. ROQ->sendAbort(header, activity.queryLogCtx());
  2791. }
  2792. }
  2793. }
  2794. pending.kill();
  2795. }
  2796. void checkDelayed()
  2797. {
  2798. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2799. {
  2800. bool allDelayed = true;
  2801. CriticalBlock b(pendingCrit);
  2802. unsigned sendIdx = (unsigned) -1;
  2803. ForEachItemIn(idx, pending)
  2804. {
  2805. IRoxieServerQueryPacket &p = pending.item(idx);
  2806. if (p.queryPacket())
  2807. {
  2808. if (p.isDelayed())
  2809. {
  2810. if (sendIdx == (unsigned) -1)
  2811. sendIdx = idx;
  2812. }
  2813. else if (!p.hasResult())
  2814. {
  2815. allDelayed = false;
  2816. break;
  2817. }
  2818. }
  2819. }
  2820. if (allDelayed && sendIdx != (unsigned) -1)
  2821. {
  2822. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2823. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2824. pending.item(sendIdx).setDelayed(false);
  2825. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2826. sentsome.signal();
  2827. }
  2828. }
  2829. else if (deferredStart)
  2830. {
  2831. CriticalBlock b(pendingCrit);
  2832. ForEachItemIn(idx, pending)
  2833. {
  2834. IRoxieServerQueryPacket &p = pending.item(idx);
  2835. if (p.isDelayed())
  2836. {
  2837. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2838. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2839. p.setDelayed(false);
  2840. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2841. sentsome.signal();
  2842. }
  2843. }
  2844. deferredStart = false;
  2845. }
  2846. }
  2847. void retryPending()
  2848. {
  2849. CriticalBlock b(pendingCrit);
  2850. checkDelayed();
  2851. ForEachItemIn(idx, pending)
  2852. {
  2853. IRoxieServerQueryPacket &p = pending.item(idx);
  2854. if (!p.hasResult() && !p.isDelayed())
  2855. {
  2856. IRoxieQueryPacket *i = p.queryPacket();
  2857. if (i)
  2858. {
  2859. if (!i->queryHeader().retry())
  2860. {
  2861. StringBuffer s;
  2862. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2863. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2864. throw E;
  2865. }
  2866. if (!localSlave)
  2867. {
  2868. ROQ->sendPacket(i, activity.queryLogCtx());
  2869. atomic_inc(&retriesSent);
  2870. }
  2871. }
  2872. }
  2873. }
  2874. }
  2875. class ChannelBuffer
  2876. {
  2877. protected:
  2878. unsigned bufferLeft;
  2879. MemoryBuffer buffer;
  2880. char *nextBuf;
  2881. unsigned overflowSequence;
  2882. unsigned channel; // == bonded channel
  2883. bool needsFlush;
  2884. InterruptableSemaphore flowController;
  2885. const CRemoteResultAdaptor &owner;
  2886. CriticalSection crit;
  2887. public:
  2888. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2889. {
  2890. overflowSequence = 0;
  2891. needsFlush = false;
  2892. bufferLeft = 0;
  2893. nextBuf = NULL;
  2894. }
  2895. void init(unsigned minSize)
  2896. {
  2897. assertex(!buffer.length());
  2898. if (minSize < MIN_PAYLOAD_SIZE)
  2899. minSize = MIN_PAYLOAD_SIZE;
  2900. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2901. unsigned bufferSize = headerSize+minSize;
  2902. if (bufferSize < mtu_size)
  2903. bufferSize = mtu_size;
  2904. buffer.reserveTruncate(bufferSize);
  2905. bufferLeft = bufferSize - headerSize;
  2906. assertex(buffer.toByteArray());
  2907. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2908. needsFlush = false;
  2909. }
  2910. inline IRoxieQueryPacket *flush()
  2911. {
  2912. CriticalBlock cb(crit);
  2913. Owned<IRoxieQueryPacket> ret;
  2914. if (needsFlush)
  2915. {
  2916. buffer.setLength(nextBuf - buffer.toByteArray());
  2917. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2918. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2919. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2920. byte * tgt = (byte*)(h+1);
  2921. owner.copyHeader(tgt, channel);
  2922. ret.setown(createRoxiePacket(buffer));
  2923. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2924. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2925. else
  2926. overflowSequence++;
  2927. needsFlush = false;
  2928. bufferLeft = 0;
  2929. if (owner.flowControlled)
  2930. {
  2931. CriticalUnblock cub(crit);
  2932. while (!flowController.wait(1000))
  2933. {
  2934. StringBuffer s;
  2935. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2936. }
  2937. }
  2938. }
  2939. return ret.getClear();
  2940. }
  2941. inline void signal()
  2942. {
  2943. if (owner.flowControlled)
  2944. flowController.signal();
  2945. }
  2946. inline void interrupt(IException *e)
  2947. {
  2948. flowController.interrupt(e);
  2949. }
  2950. inline void *getBuffer(unsigned size)
  2951. {
  2952. CriticalBlock cb(crit);
  2953. if (bufferLeft >= size)
  2954. {
  2955. needsFlush = true;
  2956. void * ret = nextBuf;
  2957. nextBuf += size;
  2958. bufferLeft -= size;
  2959. return ret;
  2960. }
  2961. else if (!needsFlush)
  2962. {
  2963. init(size);
  2964. return getBuffer(size);
  2965. }
  2966. else if (owner.mergeOrder)
  2967. {
  2968. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2969. }
  2970. else
  2971. return NULL; // will force it to flush and start a new packet
  2972. }
  2973. };
  2974. private:
  2975. friend class CRemoteResultMerger;
  2976. bool allread;
  2977. bool contextCached;
  2978. bool preserveOrder;
  2979. InterruptableSemaphore sentsome;
  2980. Owned <IMessageCollator> mc;
  2981. Owned<IMessageUnpackCursor> mu;
  2982. Owned<IMessageResult> mr;
  2983. ChannelBuffer **buffers;
  2984. IHThorArg &helper;
  2985. unsigned __int64 stopAfter;
  2986. unsigned resendSequence;
  2987. IHThorArg *colocalArg;
  2988. IArrayOf<IRoxieServerQueryPacket> pending;
  2989. CriticalSection pendingCrit;
  2990. IRoxieServerSideCache *serverSideCache;
  2991. unsigned sentSequence;
  2992. Owned<IOutputRowDeserializer> deserializer;
  2993. Owned<IEngineRowAllocator> rowAllocator;
  2994. CRemoteResultMerger merger;
  2995. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  2996. MemoryBuffer tempRowBuffer;
  2997. Owned<ISerialStream> bufferStream;
  2998. CThorStreamDeserializerSource rowSource;
  2999. protected:
  3000. IRowManager *rowManager;
  3001. IRoxieInput *owner;
  3002. unsigned __int64 rowLimit;
  3003. unsigned __int64 keyedLimit;
  3004. IRoxieServerErrorHandler *errorHandler;
  3005. CachedOutputMetaData meta;
  3006. public:
  3007. ISteppingMeta *mergeOrder;
  3008. IRoxieSlaveContext *ctx;
  3009. IDebuggableContext *debugContext;
  3010. IRoxieServerActivity &activity;
  3011. unsigned parentExtractSize;
  3012. const byte * parentExtract;
  3013. bool flowControlled;
  3014. bool deferredStart;
  3015. MemoryBuffer logInfo;
  3016. MemoryBuffer cachedContext;
  3017. const RemoteActivityId &remoteId;
  3018. ruid_t ruid;
  3019. mutable CriticalSection buffersCrit;
  3020. unsigned processed;
  3021. unsigned __int64 totalCycles;
  3022. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3023. const void *getRow(IMessageUnpackCursor *mu)
  3024. {
  3025. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3026. return mu->getNext(meta.getFixedSize());
  3027. else
  3028. {
  3029. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3030. if (rowlen)
  3031. {
  3032. RecordLengthType len = *rowlen;
  3033. ReleaseRoxieRow(rowlen);
  3034. const void *slaveRec = mu->getNext(len);
  3035. if (deserializer && mu->isSerialized())
  3036. {
  3037. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3038. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3039. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3040. ReleaseRoxieRow(slaveRec);
  3041. return rowBuilder.finalizeRowClear(outsize);
  3042. }
  3043. else
  3044. return slaveRec;
  3045. }
  3046. else
  3047. return NULL;
  3048. }
  3049. }
  3050. private:
  3051. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3052. {
  3053. CriticalBlock cb(buffersCrit);
  3054. ChannelBuffer *b = buffers[channel];
  3055. if (!b && force)
  3056. {
  3057. if (!contextCached)
  3058. {
  3059. logInfo.clear();
  3060. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3061. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3062. if (activity.queryLogCtx().isIntercepted())
  3063. loggingFlags |= LOGGING_INTERCEPTED;
  3064. if (ctx->queryTimeActivities())
  3065. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3066. if (activity.queryLogCtx().isBlind())
  3067. loggingFlags |= LOGGING_BLIND;
  3068. if (debugContext)
  3069. {
  3070. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3071. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3072. MemoryBuffer bpInfo;
  3073. debugContext->serialize(bpInfo);
  3074. bpInfo.append((__uint64)(memsize_t) &activity);
  3075. logInfo.append((unsigned short) bpInfo.length());
  3076. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3077. }
  3078. else
  3079. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3080. StringBuffer logPrefix;
  3081. activity.queryLogCtx().getLogPrefix(logPrefix);
  3082. logInfo.append(logPrefix);
  3083. activity.serializeCreateStartContext(cachedContext.clear());
  3084. activity.serializeExtra(cachedContext);
  3085. if (activity.queryVarFileInfo())
  3086. {
  3087. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3088. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3089. }
  3090. contextCached = true;
  3091. }
  3092. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3093. }
  3094. return b;
  3095. }
  3096. void processRow(const void *got)
  3097. {
  3098. processed++;
  3099. if (processed > rowLimit)
  3100. {
  3101. ReleaseRoxieRow(got);
  3102. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3103. throwUnexpected();
  3104. }
  3105. else if (processed > keyedLimit)
  3106. {
  3107. ReleaseRoxieRow(got);
  3108. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3109. throwUnexpected();
  3110. }
  3111. }
  3112. public:
  3113. IMPLEMENT_IINTERFACE;
  3114. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3115. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3116. {
  3117. rowLimit = (unsigned __int64) -1;
  3118. keyedLimit = (unsigned __int64) -1;
  3119. contextCached = false;
  3120. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3121. buffers = new ChannelBuffer*[numChannels+1];
  3122. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3123. parentExtractSize = 0;
  3124. parentExtract = NULL;
  3125. owner = NULL;
  3126. mergeOrder = NULL;
  3127. deferredStart = false;
  3128. processed = 0;
  3129. totalCycles = 0;
  3130. sentSequence = 0;
  3131. serverSideCache = activity.queryServerSideCache();
  3132. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3133. rowSource.setStream(bufferStream);
  3134. }
  3135. ~CRemoteResultAdaptor()
  3136. {
  3137. if (mc)
  3138. {
  3139. ROQ->queryReceiveManager()->detachCollator(mc);
  3140. mc.clear();
  3141. }
  3142. for (unsigned channel = 0; channel <= numChannels; channel++)
  3143. {
  3144. delete(buffers[channel]);
  3145. }
  3146. delete [] buffers;
  3147. }
  3148. void setMeta(IOutputMetaData *newmeta)
  3149. {
  3150. meta.set(newmeta);
  3151. }
  3152. virtual IRoxieServerActivity *queryActivity()
  3153. {
  3154. return &activity;
  3155. }
  3156. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3157. {
  3158. return NULL;
  3159. }
  3160. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3161. {
  3162. mergeOrder = _mergeOrder;
  3163. deferredStart = true;
  3164. }
  3165. void send(IRoxieQueryPacket *p)
  3166. {
  3167. if (p)
  3168. {
  3169. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3170. assertex(p->queryHeader().uid==ruid);
  3171. // MORE: Maybe we should base the fastlane flag on some other
  3172. // criteria !! (i.e A Roxie server prediction based on the
  3173. // activity type/activity behaviour/expected reply size .. etc).
  3174. //
  3175. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3176. // But this could still cause too many reply packets on the fatlane
  3177. // (higher priority output Q), which may cause the activities on the
  3178. // low priority output Q to not get service on time.
  3179. if ((colocalArg == 0) && // not a child query activity??
  3180. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3181. (p->queryHeader().overflowSequence == 0) &&
  3182. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3183. p->queryHeader().retries |= ROXIE_FASTLANE;
  3184. if (p->queryHeader().channel)
  3185. {
  3186. bool cached = false;
  3187. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3188. if (deferredStart)
  3189. rsqp->setDelayed(true);
  3190. rsqp->setSequence(sentSequence++);
  3191. {
  3192. CriticalBlock b(pendingCrit);
  3193. pending.append(*rsqp);
  3194. }
  3195. if (!deferredStart)
  3196. {
  3197. if (!cached)
  3198. ROQ->sendPacket(p, activity.queryLogCtx());
  3199. sentsome.signal();
  3200. }
  3201. }
  3202. else
  3203. {
  3204. // 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
  3205. // Need to add first, then send
  3206. unsigned i;
  3207. bool allCached = true;
  3208. for (i = 1; i <= numActiveChannels; i++)
  3209. {
  3210. IRoxieQueryPacket *q = p->clonePacket(i);
  3211. bool thisChannelCached;
  3212. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3213. if (!thisChannelCached)
  3214. allCached = false;
  3215. rsqp->setSequence(sentSequence++);
  3216. if (deferredStart)
  3217. {
  3218. rsqp->setDelayed(true);
  3219. }
  3220. {
  3221. CriticalBlock b(pendingCrit);
  3222. pending.append(*rsqp);
  3223. }
  3224. if (!deferredStart)
  3225. sentsome.signal();
  3226. }
  3227. if (!allCached && !deferredStart)
  3228. ROQ->sendPacket(p, activity.queryLogCtx());
  3229. buffers[0]->signal(); // since replies won't come back on that channel...
  3230. p->Release();
  3231. }
  3232. }
  3233. }
  3234. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3235. {
  3236. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3237. size += sizeof(PartNoType);
  3238. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3239. char *buffer = (char *) b->getBuffer(size);
  3240. if (!buffer)
  3241. {
  3242. send(b->flush());
  3243. buffer = (char *) b->getBuffer(size);
  3244. }
  3245. PartNoType sp;
  3246. sp.partNo = partNo;
  3247. sp.fileNo = fileNo;
  3248. memcpy(buffer, &sp, sizeof(sp));
  3249. buffer += sizeof(sp);
  3250. return buffer;
  3251. }
  3252. void injectResult(IMessageResult *result)
  3253. {
  3254. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3255. f->setSequence(sentSequence++);
  3256. f->setResult(result);
  3257. CriticalBlock b(pendingCrit);
  3258. pending.append(*f);
  3259. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3260. }
  3261. void flush()
  3262. {
  3263. for (unsigned channel = 0; channel <= numChannels; channel++)
  3264. {
  3265. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3266. if (b)
  3267. send(b->flush());
  3268. }
  3269. }
  3270. void interruptBuffers(IException *e)
  3271. {
  3272. for (unsigned channel = 0; channel <= numChannels; channel++)
  3273. {
  3274. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3275. if (b)
  3276. b->interrupt(LINK(e));
  3277. }
  3278. }
  3279. void senddone()
  3280. {
  3281. CriticalBlock b(pendingCrit);
  3282. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3283. sentsome.signal();
  3284. }
  3285. bool fireException(IException *e)
  3286. {
  3287. {
  3288. CriticalBlock b(pendingCrit);
  3289. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3290. }
  3291. interruptBuffers(e);
  3292. if (mc)
  3293. mc->interrupt(LINK(e));
  3294. sentsome.interrupt(e);
  3295. return true;
  3296. }
  3297. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3298. {
  3299. owner = _owner;
  3300. errorHandler = _errorHandler;
  3301. ctx = _ctx;
  3302. debugContext = ctx->queryDebugContext();
  3303. colocalArg = _colocalArg;
  3304. if (meta.needsSerializeDisk())
  3305. {
  3306. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3307. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3308. }
  3309. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3310. deferredStart = true;
  3311. }
  3312. virtual unsigned queryId() const
  3313. {
  3314. return owner->queryId();
  3315. }
  3316. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3317. {
  3318. #ifdef TRACE_STARTSTOP
  3319. if (traceStartStop)
  3320. activity.queryLogCtx().CTXLOG("RRAonstart");
  3321. #endif
  3322. sentsome.reinit();
  3323. ruid = getNextRuid();
  3324. rowManager = &ctx->queryRowManager();
  3325. if (mergeOrder)
  3326. merger.init(mergeOrder, rowManager);
  3327. if (mc)
  3328. {
  3329. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3330. }
  3331. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3332. allread = false;
  3333. mu.clear();
  3334. contextCached = false;
  3335. processed = 0;
  3336. totalCycles = 0;
  3337. resendSequence = 0;
  3338. sentSequence = 0;
  3339. for (unsigned channel = 0; channel <= numChannels; channel++)
  3340. {
  3341. delete(buffers[channel]);
  3342. buffers[channel] = NULL;
  3343. }
  3344. flush();
  3345. parentExtractSize = _parentExtractSize;
  3346. parentExtract = _parentExtract;
  3347. }
  3348. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3349. {
  3350. #ifdef TRACE_STARTSTOP
  3351. if (traceStartStop)
  3352. activity.queryLogCtx().CTXLOG("RRAstart");
  3353. #endif
  3354. owner->start(parentExtractSize, parentExtract, paused);
  3355. totalCycles = 0;
  3356. }
  3357. void checkAbort()
  3358. {
  3359. owner->checkAbort();
  3360. }
  3361. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3362. {
  3363. if (ctx->queryProbeManager())
  3364. {
  3365. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3366. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3367. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3368. }
  3369. {
  3370. CriticalBlock b(pendingCrit);
  3371. if (pending.length())
  3372. {
  3373. #ifdef _DEBUG
  3374. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3375. #endif
  3376. assertex(pending.length()==0);
  3377. }
  3378. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3379. }
  3380. sentsome.signal();
  3381. rowLimit = _rowLimit;
  3382. keyedLimit = _keyedLimit;
  3383. stopAfter = _stopAfter;
  3384. }
  3385. virtual void stop(bool aborting)
  3386. {
  3387. #ifdef TRACE_STARTSTOP
  3388. if (traceStartStop)
  3389. activity.queryLogCtx().CTXLOG("RRAstop");
  3390. #endif
  3391. onStop(aborting);
  3392. owner->stop(aborting);
  3393. }
  3394. void onStop(bool aborting)
  3395. {
  3396. #ifdef TRACE_STARTSTOP
  3397. if (traceStartStop)
  3398. activity.queryLogCtx().CTXLOG("RRAonstop");
  3399. #endif
  3400. abortPending();
  3401. interruptBuffers(NULL);
  3402. sentsome.interrupt();
  3403. if (mc) // May not be set if start() chain threw exception
  3404. mc->interrupt();
  3405. }
  3406. virtual void reset()
  3407. {
  3408. #ifdef TRACE_STARTSTOP
  3409. if (traceStartStop)
  3410. activity.queryLogCtx().CTXLOG("RRAreset");
  3411. #endif
  3412. owner->reset();
  3413. onReset();
  3414. }
  3415. virtual void resetEOF()
  3416. {
  3417. throwUnexpected();
  3418. }
  3419. virtual void onReset()
  3420. {
  3421. #ifdef TRACE_STARTSTOP
  3422. if (traceStartStop)
  3423. activity.queryLogCtx().CTXLOG("RRAonreset");
  3424. #endif
  3425. if (mc)
  3426. ROQ->queryReceiveManager()->detachCollator(mc);
  3427. merger.reset();
  3428. pending.kill();
  3429. if (mc && ctx)
  3430. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3431. mc.clear(); // Or we won't free memory for graphs that get recreated
  3432. mu.clear(); //ditto
  3433. mergeOrder = NULL; // MORE - is that needed?
  3434. deferredStart = false;
  3435. }
  3436. virtual IOutputMetaData * queryOutputMeta() const
  3437. {
  3438. return helper.queryOutputMeta();
  3439. }
  3440. virtual unsigned __int64 queryTotalCycles() const
  3441. {
  3442. return totalCycles;
  3443. }
  3444. virtual unsigned __int64 queryLocalCycles() const
  3445. {
  3446. return owner->queryLocalCycles();
  3447. }
  3448. virtual IRoxieInput *queryInput(unsigned idx) const
  3449. {
  3450. return owner->queryInput(idx);
  3451. }
  3452. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3453. {
  3454. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3455. {
  3456. StringBuffer recstr;
  3457. unsigned i;
  3458. for (i = 0; i < seekLen; i++)
  3459. {
  3460. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3461. }
  3462. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3463. }
  3464. assertex(mergeOrder);
  3465. if (deferredStart)
  3466. {
  3467. CriticalBlock b(pendingCrit);
  3468. ForEachItemIn(idx, pending)
  3469. {
  3470. IRoxieServerQueryPacket &p = pending.item(idx);
  3471. if (p.isDelayed())
  3472. {
  3473. p.setDelayed(false);
  3474. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3475. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3476. MemoryBuffer serializedSkip;
  3477. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3478. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3479. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3480. sentsome.signal();
  3481. }
  3482. }
  3483. deferredStart = false;
  3484. }
  3485. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3486. if (processed==stopAfter)
  3487. return NULL;
  3488. if (allread)
  3489. return NULL;
  3490. loop
  3491. {
  3492. if (merger.ready())
  3493. {
  3494. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3495. if (got)
  3496. {
  3497. processRow(got);
  3498. return got;
  3499. }
  3500. }
  3501. if (!reload()) // MORE - should pass the seek info here...
  3502. return NULL;
  3503. }
  3504. }
  3505. virtual const void *nextInGroup()
  3506. {
  3507. // If we are merging then we need to do a heapsort on all
  3508. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3509. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3510. {
  3511. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3512. }
  3513. loop
  3514. {
  3515. checkDelayed();
  3516. if (processed==stopAfter)
  3517. return NULL;
  3518. if (allread)
  3519. return NULL;
  3520. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3521. const void *got = NULL;
  3522. if (mergeOrder && merger.ready())
  3523. {
  3524. bool matched = true;
  3525. got = merger.next(matched, dummySmartStepExtra);
  3526. }
  3527. else if (mu)
  3528. got = getRow(mu);
  3529. if (got)
  3530. {
  3531. processRow(got);
  3532. return got;
  3533. }
  3534. if (!reload())
  3535. return NULL;
  3536. }
  3537. }
  3538. bool reload()
  3539. {
  3540. // Wait for something to be returned from a slave....
  3541. mu.clear();
  3542. sentsome.wait();
  3543. // must be at least an endMarker on the queue since sentsome was signalled
  3544. {
  3545. CriticalBlock b(pendingCrit);
  3546. IRoxieServerQueryPacket &top = pending.item(0);
  3547. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3548. {
  3549. pending.remove(0);
  3550. return true;
  3551. }
  3552. else if (top.isEnd())
  3553. {
  3554. pending.remove(0);
  3555. allread = true;
  3556. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3557. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3558. return false;
  3559. }
  3560. else if (mergeOrder)
  3561. {
  3562. unsigned idx = 0;
  3563. bool added = false;
  3564. while (pending.isItem(idx))
  3565. {
  3566. IRoxieServerQueryPacket &item = pending.item(idx);
  3567. if (item.isEnd())
  3568. {
  3569. if (merger.noteEndSeen())
  3570. {
  3571. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3572. added = true;
  3573. }
  3574. break;
  3575. }
  3576. else if (item.hasResult())
  3577. {
  3578. merger.noteResult(&item, item.getSequence());
  3579. pending.remove(idx);
  3580. added = true;
  3581. }
  3582. else if (item.isContinuation())
  3583. idx++;
  3584. else
  3585. break;
  3586. }
  3587. if (added)
  3588. return true;
  3589. }
  3590. else if (top.hasResult())
  3591. {
  3592. mr.setown(pending.item(0).getResult());
  3593. mu.setown(mr->getCursor(rowManager));
  3594. pending.remove(0);
  3595. return true;
  3596. }
  3597. }
  3598. getNextUnpacker();
  3599. return true;
  3600. }
  3601. void getNextUnpacker()
  3602. {
  3603. mu.clear();
  3604. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3605. loop
  3606. {
  3607. checkDelayed();
  3608. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3609. owner->checkAbort();
  3610. bool anyActivity;
  3611. if (ctxTraceLevel > 5)
  3612. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3613. mr.setown(mc->getNextResult(timeout, anyActivity));
  3614. if (ctxTraceLevel > 6)
  3615. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3616. owner->checkAbort();
  3617. if (mr)
  3618. {
  3619. unsigned roxieHeaderLen;
  3620. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3621. #ifdef _DEBUG
  3622. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3623. #endif
  3624. if (ctxTraceLevel > 5)
  3625. {
  3626. StringBuffer s;
  3627. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3628. }
  3629. CriticalBlock b(pendingCrit);
  3630. unsigned idx = 0;
  3631. IRoxieServerQueryPacket *original = NULL;
  3632. IRoxieQueryPacket *op;
  3633. while (pending.isItem(idx))
  3634. {
  3635. original = &pending.item(idx);
  3636. op = original->queryPacket();
  3637. if (op && header.matchPacket(op->queryHeader()))
  3638. break;
  3639. original = NULL;
  3640. idx++;
  3641. }
  3642. if (!original || original->hasResult())
  3643. {
  3644. switch (header.activityId)
  3645. {
  3646. case ROXIE_FILECALLBACK:
  3647. {
  3648. // tell slave to abort
  3649. //if (ctxTraceLevel > 5)
  3650. {
  3651. StringBuffer s;
  3652. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3653. }
  3654. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3655. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3656. if (len)
  3657. {
  3658. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3659. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3660. const char *rowdata = (const char *) row.get();
  3661. // bool isOpt = * (bool *) rowdata;
  3662. // bool isLocal = * (bool *) (rowdata+1);
  3663. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3664. }
  3665. else
  3666. throwUnexpected();
  3667. break;
  3668. }
  3669. // MORE - ROXIE_ALIVE perhaps should go here too
  3670. case ROXIE_TRACEINFO:
  3671. {
  3672. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3673. loop
  3674. {
  3675. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3676. if (rowlen)
  3677. {
  3678. char *logInfo = (char *) extra->getNext(*rowlen);
  3679. MemoryBuffer buf;
  3680. buf.setBuffer(*rowlen, logInfo, false);
  3681. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3682. ReleaseRoxieRow(rowlen);
  3683. ReleaseRoxieRow(logInfo);
  3684. }
  3685. else
  3686. break;
  3687. }
  3688. break;
  3689. }
  3690. default:
  3691. if (ctxTraceLevel > 3)
  3692. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3693. mr->discard();
  3694. break;
  3695. }
  3696. mr.clear();
  3697. }
  3698. else
  3699. {
  3700. atomic_inc(&resultsReceived);
  3701. switch (header.activityId)
  3702. {
  3703. case ROXIE_DEBUGCALLBACK:
  3704. {
  3705. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3706. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3707. if (len)
  3708. {
  3709. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3710. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3711. char *rowdata = (char *) row.get();
  3712. if (ctxTraceLevel > 5)
  3713. {
  3714. StringBuffer s;
  3715. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3716. }
  3717. MemoryBuffer slaveInfo;
  3718. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3719. unsigned debugSequence;
  3720. slaveInfo.read(debugSequence);
  3721. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3722. if (!reply)
  3723. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3724. if (reply)
  3725. {
  3726. original->setDebugResponse(debugSequence, reply);
  3727. ROQ->sendPacket(reply, activity.queryLogCtx());
  3728. }
  3729. }
  3730. else
  3731. throwUnexpected();
  3732. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3733. // Leave original message on pending queue in original location - this is not a reply to it.
  3734. break;
  3735. }
  3736. case ROXIE_FILECALLBACK:
  3737. {
  3738. // we need to send back to the slave a message containing the file info requested.
  3739. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3740. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3741. if (len)
  3742. {
  3743. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3744. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3745. const char *rowdata = (const char *) row.get();
  3746. bool isOpt = * (bool *) rowdata;
  3747. bool isLocal = * (bool *) (rowdata+1);
  3748. const char *lfn = rowdata+2;
  3749. if (ctxTraceLevel > 5)
  3750. {
  3751. StringBuffer s;
  3752. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3753. }
  3754. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3755. }
  3756. else
  3757. throwUnexpected();
  3758. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3759. // Leave original message on pending queue in original location - this is not a reply to it.
  3760. break;
  3761. }
  3762. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3763. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3764. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3765. throwUnexpected();
  3766. case ROXIE_LIMIT_EXCEEDED:
  3767. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3768. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3769. throwUnexpected();
  3770. case ROXIE_TRACEINFO:
  3771. {
  3772. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3773. loop
  3774. {
  3775. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3776. if (rowlen)
  3777. {
  3778. char *logInfo = (char *) extra->getNext(*rowlen);
  3779. MemoryBuffer buf;
  3780. buf.setBuffer(*rowlen, logInfo, false);
  3781. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3782. ReleaseRoxieRow(rowlen);
  3783. ReleaseRoxieRow(logInfo);
  3784. }
  3785. else
  3786. break;
  3787. }
  3788. break;
  3789. }
  3790. case ROXIE_EXCEPTION:
  3791. if (ctxTraceLevel > 1)
  3792. {
  3793. StringBuffer s;
  3794. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3795. }
  3796. op->queryHeader().noteException(header.retries);
  3797. if (op->queryHeader().allChannelsFailed())
  3798. {
  3799. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3800. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3801. throwRemoteException(exceptionData);
  3802. }
  3803. // Leave it on pending queue in original location
  3804. break;
  3805. case ROXIE_ALIVE:
  3806. if (ctxTraceLevel > 4)
  3807. {
  3808. StringBuffer s;
  3809. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3810. }
  3811. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3812. // Leave it on pending queue in original location
  3813. break;
  3814. default:
  3815. if (header.retries & ROXIE_RETRIES_MASK)
  3816. atomic_inc(&retriesNeeded);
  3817. unsigned metaLen;
  3818. const void *metaData = mr->getMessageMetadata(metaLen);
  3819. if (metaLen)
  3820. {
  3821. // We got back first chunk but there is more.
  3822. // resend the packet, with the cursor info provided.
  3823. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3824. if (ctxTraceLevel > 1)
  3825. {
  3826. StringBuffer s;
  3827. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3828. }
  3829. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3830. {
  3831. StringBuffer s;
  3832. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3833. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3834. throwUnexpected();
  3835. }
  3836. MemoryBuffer nextQuery;
  3837. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3838. nextQuery.append(metaLen, metaData);
  3839. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3840. nextQuery.append(op->getContextLength(), op->queryContextData());
  3841. if (resendSequence == CONTINUESEQUENCE_MAX)
  3842. {
  3843. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3844. resendSequence = 1;
  3845. }
  3846. else
  3847. resendSequence++;
  3848. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3849. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3850. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3851. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3852. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3853. fqp->setSequence(original->getSequence());
  3854. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3855. original->setContinuation(LINK(fqp));
  3856. if (mergeOrder)
  3857. fqp->setDelayed(true);
  3858. else
  3859. {
  3860. ROQ->sendPacket(resend, activity.queryLogCtx());
  3861. sentsome.signal();
  3862. }
  3863. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3864. }
  3865. else
  3866. {
  3867. if (serverSideCache)
  3868. serverSideCache->noteCachedResult(original, mr);
  3869. }
  3870. unsigned channel = header.channel;
  3871. {
  3872. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3873. if (b)
  3874. b->signal();
  3875. }
  3876. original->setResult(mr.getClear());
  3877. sentsome.signal();
  3878. return;
  3879. }
  3880. }
  3881. }
  3882. else
  3883. {
  3884. if (!anyActivity)
  3885. {
  3886. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3887. retryPending();
  3888. }
  3889. }
  3890. }
  3891. }
  3892. inline unsigned headerLength() const
  3893. {
  3894. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3895. }
  3896. void copyHeader(byte *tgt, unsigned channel) const
  3897. {
  3898. unsigned len = logInfo.length();
  3899. memcpy(tgt, logInfo.toByteArray(), len);
  3900. tgt += len;
  3901. *(unsigned *) tgt = parentExtractSize;
  3902. tgt += sizeof(unsigned);
  3903. memcpy(tgt, parentExtract, parentExtractSize);
  3904. tgt += parentExtractSize;
  3905. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3906. tgt += cachedContext.length();
  3907. }
  3908. };
  3909. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3910. {
  3911. Owned <IException> exception;
  3912. bool skipping;
  3913. ConstPointerArray buff;
  3914. unsigned index;
  3915. bool pulled;
  3916. void pullInput()
  3917. {
  3918. try
  3919. {
  3920. if (exception)
  3921. throw exception.getClear();
  3922. unsigned __int64 count = 0;
  3923. loop
  3924. {
  3925. const void * next = CRemoteResultAdaptor::nextInGroup();
  3926. if (next == NULL)
  3927. {
  3928. next = CRemoteResultAdaptor::nextInGroup();
  3929. if(next == NULL)
  3930. break;
  3931. buff.append(NULL);
  3932. }
  3933. count++;
  3934. if (count > rowLimit)
  3935. {
  3936. ReleaseRoxieRow(next);
  3937. ReleaseRoxieRowSet(buff);
  3938. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3939. throwUnexpected();
  3940. }
  3941. else if (count > keyedLimit)
  3942. {
  3943. ReleaseRoxieRow(next);
  3944. ReleaseRoxieRowSet(buff);
  3945. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3946. throwUnexpected();
  3947. }
  3948. buff.append(next);
  3949. }
  3950. }
  3951. catch (IException *E)
  3952. {
  3953. if (QUERYINTERFACE(E, LimitSkipException))
  3954. {
  3955. Owned<IException> cleanup = E;
  3956. ReleaseRoxieRowSet(buff);
  3957. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  3958. if (onfail)
  3959. buff.append(onfail);
  3960. }
  3961. else
  3962. throw;
  3963. }
  3964. pulled = true;
  3965. }
  3966. public:
  3967. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  3968. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  3969. {
  3970. skipping = _skipping;
  3971. index = 0;
  3972. pulled = false;
  3973. }
  3974. void setException(IException *E)
  3975. {
  3976. exception.setown(E);
  3977. }
  3978. virtual void onReset()
  3979. {
  3980. while (buff.isItem(index))
  3981. ReleaseRoxieRow(buff.item(index++));
  3982. buff.kill();
  3983. pulled = false;
  3984. exception.clear();
  3985. CRemoteResultAdaptor::onReset();
  3986. }
  3987. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3988. {
  3989. index = 0;
  3990. pulled = false;
  3991. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  3992. }
  3993. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3994. {
  3995. // 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
  3996. if (exception)
  3997. throw exception.getClear();
  3998. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  3999. }
  4000. virtual const void *nextInGroup()
  4001. {
  4002. if (skipping)
  4003. {
  4004. if(!pulled)
  4005. pullInput();
  4006. if(buff.isItem(index))
  4007. {
  4008. const void * next = buff.item(index++);
  4009. if(next)
  4010. processed++;
  4011. return next;
  4012. }
  4013. return NULL;
  4014. }
  4015. else
  4016. {
  4017. if (exception)
  4018. throw exception.getClear();
  4019. return CRemoteResultAdaptor::nextInGroup();
  4020. }
  4021. }
  4022. };
  4023. //=================================================================================
  4024. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4025. {
  4026. IHThorApplyArg &helper;
  4027. public:
  4028. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4029. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorApplyArg &) basehelper)
  4030. {
  4031. }
  4032. virtual void onExecute()
  4033. {
  4034. helper.start();
  4035. loop
  4036. {
  4037. const void * next = input->nextInGroup();
  4038. if (!next)
  4039. {
  4040. next = input->nextInGroup();
  4041. if (!next)
  4042. break;
  4043. }
  4044. helper.apply(next);
  4045. ReleaseRoxieRow(next);
  4046. }
  4047. helper.end();
  4048. }
  4049. };
  4050. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4051. {
  4052. bool isRoot;
  4053. public:
  4054. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4055. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4056. {
  4057. }
  4058. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4059. {
  4060. return new CRoxieServerApplyActivity(this, _probeManager);
  4061. }
  4062. virtual bool isSink() const
  4063. {
  4064. return isRoot;
  4065. }
  4066. };
  4067. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4068. {
  4069. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4070. }
  4071. //=================================================================================
  4072. class CRoxieServerNullActivity : public CRoxieServerActivity
  4073. {
  4074. public:
  4075. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4076. : CRoxieServerActivity(_factory, _probeManager)
  4077. {
  4078. }
  4079. virtual const void *nextInGroup()
  4080. {
  4081. return NULL;
  4082. }
  4083. };
  4084. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4085. {
  4086. return new CRoxieServerNullActivity(_factory, _probeManager);
  4087. }
  4088. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4089. {
  4090. public:
  4091. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4092. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4093. {
  4094. }
  4095. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4096. {
  4097. return new CRoxieServerNullActivity(this, _probeManager);
  4098. }
  4099. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4100. {
  4101. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4102. }
  4103. };
  4104. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4105. {
  4106. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4107. }
  4108. //=================================================================================
  4109. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4110. {
  4111. public:
  4112. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4113. : CRoxieServerActivity(_factory, _probeManager)
  4114. {
  4115. }
  4116. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4117. {
  4118. return input->gatherConjunctions(collector);
  4119. }
  4120. virtual void resetEOF()
  4121. {
  4122. input->resetEOF();
  4123. }
  4124. virtual const void *nextInGroup()
  4125. {
  4126. const void * next = input->nextInGroup();
  4127. if (next)
  4128. processed++;
  4129. return next;
  4130. }
  4131. virtual bool isPassThrough()
  4132. {
  4133. return true;
  4134. }
  4135. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4136. {
  4137. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4138. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4139. if (next)
  4140. processed++;
  4141. return next;
  4142. }
  4143. IInputSteppingMeta * querySteppingMeta()
  4144. {
  4145. return input->querySteppingMeta();
  4146. }
  4147. };
  4148. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4149. {
  4150. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4151. }
  4152. //=================================================================================
  4153. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4154. {
  4155. protected:
  4156. bool eof;
  4157. bool first;
  4158. public:
  4159. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4160. : CRoxieServerActivity(_factory, _probeManager)
  4161. {
  4162. eof = false;
  4163. first = true;
  4164. }
  4165. ~CRoxieServerChildBaseActivity()
  4166. {
  4167. }
  4168. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4169. {
  4170. eof = false;
  4171. first = true;
  4172. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4173. }
  4174. };
  4175. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4176. {
  4177. public:
  4178. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4179. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4180. {
  4181. }
  4182. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4183. {
  4184. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4185. }
  4186. };
  4187. //=================================================================================
  4188. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4189. {
  4190. IHThorChildIteratorArg &helper;
  4191. public:
  4192. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4193. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4194. {
  4195. }
  4196. virtual bool needsAllocator() const { return true; }
  4197. virtual const void *nextInGroup()
  4198. {
  4199. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4200. if (eof)
  4201. return NULL;
  4202. bool ok;
  4203. if (first)
  4204. {
  4205. ok = helper.first();
  4206. first = false;
  4207. }
  4208. else
  4209. ok = helper.next();
  4210. try
  4211. {
  4212. while (ok)
  4213. {
  4214. processed++;
  4215. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4216. unsigned outSize = helper.transform(rowBuilder);
  4217. if (outSize)
  4218. return rowBuilder.finalizeRowClear(outSize);
  4219. ok = helper.next();
  4220. }
  4221. }
  4222. catch (IException *E)
  4223. {
  4224. throw makeWrappedException(E);
  4225. }
  4226. eof = true;
  4227. return NULL;
  4228. }
  4229. };
  4230. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4231. {
  4232. public:
  4233. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4234. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4235. {
  4236. }
  4237. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4238. {
  4239. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4240. }
  4241. };
  4242. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4243. {
  4244. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4245. }
  4246. //=================================================================================
  4247. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4248. {
  4249. IHThorChildNormalizeArg &helper;
  4250. public:
  4251. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4252. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4253. {
  4254. }
  4255. virtual bool needsAllocator() const { return true; }
  4256. virtual const void *nextInGroup()
  4257. {
  4258. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4259. if (eof)
  4260. return NULL;
  4261. bool ok;
  4262. if (first)
  4263. {
  4264. ok = helper.first();
  4265. first = false;
  4266. }
  4267. else
  4268. ok = helper.next();
  4269. if (ok)
  4270. {
  4271. try
  4272. {
  4273. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4274. do {
  4275. unsigned outSize = helper.transform(rowBuilder);
  4276. if (outSize)
  4277. {
  4278. processed++;
  4279. return rowBuilder.finalizeRowClear(outSize);
  4280. }
  4281. ok = helper.next();
  4282. }
  4283. while (ok);
  4284. }
  4285. catch (IException *E)
  4286. {
  4287. throw makeWrappedException(E);
  4288. }
  4289. }
  4290. eof = true;
  4291. return NULL;
  4292. }
  4293. };
  4294. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4295. {
  4296. public:
  4297. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4298. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4299. {
  4300. }
  4301. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4302. {
  4303. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4304. }
  4305. };
  4306. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4307. {
  4308. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4309. }
  4310. //=================================================================================
  4311. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4312. {
  4313. IHThorChildAggregateArg &helper;
  4314. public:
  4315. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4316. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4317. {
  4318. }
  4319. virtual bool needsAllocator() const { return true; }
  4320. virtual const void *nextInGroup()
  4321. {
  4322. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4323. if (eof)
  4324. return NULL;
  4325. eof = true;
  4326. processed++;
  4327. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4328. helper.clearAggregate(rowBuilder);
  4329. helper.processRows(rowBuilder);
  4330. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4331. return rowBuilder.finalizeRowClear(finalSize);
  4332. }
  4333. };
  4334. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4335. {
  4336. public:
  4337. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4338. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4339. {
  4340. }
  4341. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4342. {
  4343. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4344. }
  4345. };
  4346. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4347. {
  4348. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4349. }
  4350. //=================================================================================
  4351. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4352. {
  4353. IHThorChildGroupAggregateArg &helper;
  4354. RowAggregator aggregated;
  4355. public:
  4356. IMPLEMENT_IINTERFACE
  4357. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4358. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4359. aggregated(helper, helper)
  4360. {
  4361. }
  4362. void processRow(const void * next)
  4363. {
  4364. aggregated.addRow(next);
  4365. }
  4366. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4367. {
  4368. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4369. aggregated.start(rowAllocator);
  4370. }
  4371. virtual void reset()
  4372. {
  4373. aggregated.reset();
  4374. CRoxieServerChildBaseActivity::reset();
  4375. }
  4376. virtual bool needsAllocator() const { return true; }
  4377. virtual const void *nextInGroup()
  4378. {
  4379. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4380. if (eof)
  4381. return NULL;
  4382. if (first)
  4383. {
  4384. helper.processRows(this);
  4385. first = false;
  4386. }
  4387. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4388. if (next)
  4389. {
  4390. processed++;
  4391. return next->finalizeRowClear();
  4392. }
  4393. eof = true;
  4394. return NULL;
  4395. }
  4396. };
  4397. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4398. {
  4399. public:
  4400. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4401. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4402. {
  4403. }
  4404. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4405. {
  4406. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4407. }
  4408. };
  4409. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4410. {
  4411. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4412. }
  4413. //=================================================================================
  4414. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4415. {
  4416. IHThorChildThroughNormalizeArg &helper;
  4417. const void * lastInput;
  4418. unsigned numProcessedLastGroup;
  4419. bool ok;
  4420. public:
  4421. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4422. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4423. {
  4424. lastInput = NULL;
  4425. numProcessedLastGroup = 0;
  4426. ok = false;
  4427. }
  4428. virtual void stop(bool aborting)
  4429. {
  4430. CRoxieServerChildBaseActivity::stop(aborting);
  4431. ReleaseRoxieRow(lastInput);
  4432. lastInput = NULL;
  4433. }
  4434. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4435. {
  4436. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4437. numProcessedLastGroup = processed;
  4438. ok = false;
  4439. }
  4440. virtual bool needsAllocator() const { return true; }
  4441. virtual const void *nextInGroup()
  4442. {
  4443. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4444. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4445. loop
  4446. {
  4447. if (ok)
  4448. ok = helper.next();
  4449. while (!ok)
  4450. {
  4451. ReleaseRoxieRow(lastInput);
  4452. lastInput = input->nextInGroup();
  4453. if (!lastInput)
  4454. {
  4455. if (numProcessedLastGroup != processed)
  4456. {
  4457. numProcessedLastGroup = processed;
  4458. return NULL;
  4459. }
  4460. lastInput = input->nextInGroup();
  4461. if (!lastInput)
  4462. return NULL;
  4463. }
  4464. ok = helper.first(lastInput);
  4465. }
  4466. try
  4467. {
  4468. do
  4469. {
  4470. unsigned outSize = helper.transform(rowBuilder);
  4471. if (outSize)
  4472. {
  4473. processed++;
  4474. return rowBuilder.finalizeRowClear(outSize);
  4475. }
  4476. ok = helper.next();
  4477. } while (ok);
  4478. }
  4479. catch (IException *E)
  4480. {
  4481. throw makeWrappedException(E);
  4482. }
  4483. }
  4484. }
  4485. };
  4486. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4487. {
  4488. public:
  4489. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4490. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4491. {
  4492. }
  4493. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4494. {
  4495. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4496. }
  4497. };
  4498. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4499. {
  4500. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4501. }
  4502. //=================================================================================
  4503. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4504. {
  4505. IHThorLinkedRawIteratorArg &helper;
  4506. public:
  4507. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4508. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4509. {
  4510. }
  4511. virtual const void *nextInGroup()
  4512. {
  4513. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4514. const void *ret =helper.next();
  4515. if (ret)
  4516. {
  4517. LinkRoxieRow(ret);
  4518. processed++;
  4519. }
  4520. return ret;
  4521. }
  4522. };
  4523. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4524. {
  4525. public:
  4526. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4527. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4528. {
  4529. }
  4530. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4531. {
  4532. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4533. }
  4534. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4535. {
  4536. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4537. }
  4538. };
  4539. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4540. {
  4541. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4542. }
  4543. //=================================================================================
  4544. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4545. {
  4546. public:
  4547. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4548. : CRoxieServerActivity(_factory, _probeManager)
  4549. {
  4550. }
  4551. virtual const void *nextInGroup()
  4552. {
  4553. throwUnexpected();
  4554. }
  4555. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4556. {
  4557. try
  4558. {
  4559. start(parentExtractSize, parentExtract, false);
  4560. {
  4561. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4562. MemoryBuffer result;
  4563. IRecordSize * inputMeta = input->queryOutputMeta();
  4564. loop
  4565. {
  4566. const void *nextrec = input->nextInGroup();
  4567. if (!nextrec)
  4568. {
  4569. nextrec = input->nextInGroup();
  4570. if (!nextrec)
  4571. break;
  4572. }
  4573. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4574. ReleaseRoxieRow(nextrec);
  4575. }
  4576. retSize = result.length();
  4577. ret = result.detach();
  4578. }
  4579. stop(false);
  4580. reset();
  4581. }
  4582. catch(IException *E)
  4583. {
  4584. ctx->notifyAbort(E);
  4585. stop(true);
  4586. reset();
  4587. throw;
  4588. }
  4589. catch(...)
  4590. {
  4591. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4592. ctx->notifyAbort(E);
  4593. stop(true);
  4594. reset();
  4595. throw;
  4596. }
  4597. }
  4598. };
  4599. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4600. {
  4601. bool isRoot;
  4602. public:
  4603. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4604. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4605. {
  4606. }
  4607. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4608. {
  4609. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4610. }
  4611. virtual bool isSink() const
  4612. {
  4613. return isRoot;
  4614. }
  4615. };
  4616. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4617. {
  4618. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4619. }
  4620. //=================================================================================
  4621. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4622. {
  4623. IHThorInlineTableArg &helper;
  4624. __uint64 curRow;
  4625. __uint64 numRows;
  4626. public:
  4627. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4628. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4629. {
  4630. }
  4631. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4632. {
  4633. curRow = 0;
  4634. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4635. numRows = helper.numRows();
  4636. }
  4637. virtual bool needsAllocator() const { return true; }
  4638. virtual const void *nextInGroup()
  4639. {
  4640. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4641. // Filtering empty rows, returns the next valid row
  4642. while (curRow < numRows)
  4643. {
  4644. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4645. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4646. if (outSize)
  4647. {
  4648. processed++;
  4649. return rowBuilder.finalizeRowClear(outSize);
  4650. }
  4651. }
  4652. return NULL;
  4653. }
  4654. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4655. {
  4656. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4657. }
  4658. };
  4659. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4660. {
  4661. public:
  4662. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4663. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4664. {
  4665. }
  4666. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4667. {
  4668. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4669. }
  4670. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4671. {
  4672. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4673. }
  4674. };
  4675. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4676. {
  4677. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4678. }
  4679. //=================================================================================
  4680. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4681. {
  4682. IHThorWorkunitReadArg &helper;
  4683. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4684. public:
  4685. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4686. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4687. {
  4688. }
  4689. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4690. {
  4691. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4692. if (!ctx->queryServerContext())
  4693. {
  4694. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4695. }
  4696. }
  4697. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4698. {
  4699. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4700. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4701. OwnedRoxieString fromWuid(helper.getWUID());
  4702. if (fromWuid)
  4703. UNIMPLEMENTED;
  4704. wuReader.setown(ctx->getWorkunitRowReader(helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4705. // MORE _ should that be in onCreate?
  4706. }
  4707. virtual void reset()
  4708. {
  4709. wuReader.clear();
  4710. CRoxieServerActivity::reset();
  4711. };
  4712. virtual bool needsAllocator() const { return true; }
  4713. virtual const void *nextInGroup()
  4714. {
  4715. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4716. const void *ret = wuReader->nextInGroup();
  4717. if (ret)
  4718. processed++;
  4719. return ret;
  4720. }
  4721. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4722. {
  4723. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4724. }
  4725. };
  4726. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4727. {
  4728. public:
  4729. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4730. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4731. {
  4732. }
  4733. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4734. {
  4735. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4736. }
  4737. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4738. {
  4739. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4740. }
  4741. };
  4742. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4743. {
  4744. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4745. }
  4746. //=================================================================================
  4747. interface ILocalGraphEx : public IEclGraphResults
  4748. {
  4749. public:
  4750. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4751. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4752. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4753. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4754. };
  4755. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4756. {
  4757. public:
  4758. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4759. IMPLEMENT_IINTERFACE
  4760. virtual IOutputMetaData * queryOutputMeta() const
  4761. {
  4762. return input->queryOutputMeta();
  4763. }
  4764. virtual unsigned queryId() const
  4765. {
  4766. return input->queryId();
  4767. }
  4768. virtual unsigned __int64 queryTotalCycles() const
  4769. {
  4770. return input->queryTotalCycles();
  4771. }
  4772. virtual unsigned __int64 queryLocalCycles() const
  4773. {
  4774. return input->queryLocalCycles();
  4775. }
  4776. virtual IRoxieInput *queryInput(unsigned idx) const
  4777. {
  4778. return input->queryInput(idx);
  4779. }
  4780. virtual IRoxieServerActivity *queryActivity()
  4781. {
  4782. return input->queryActivity();
  4783. }
  4784. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4785. {
  4786. return input->queryIndexReadActivity();
  4787. }
  4788. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4789. {
  4790. CriticalBlock procedure(cs);
  4791. input->start(parentExtractSize, parentExtract, paused);
  4792. }
  4793. virtual void stop(bool aborting)
  4794. {
  4795. CriticalBlock procedure(cs);
  4796. input->stop(aborting);
  4797. }
  4798. virtual void reset()
  4799. {
  4800. CriticalBlock procedure(cs);
  4801. input->reset();
  4802. }
  4803. virtual void resetEOF()
  4804. {
  4805. CriticalBlock procedure(cs);
  4806. input->resetEOF();
  4807. }
  4808. virtual void checkAbort()
  4809. {
  4810. CriticalBlock procedure(cs);
  4811. input->checkAbort();
  4812. }
  4813. virtual const void *nextInGroup()
  4814. {
  4815. CriticalBlock procedure(cs);
  4816. return input->nextInGroup();
  4817. }
  4818. virtual bool nextGroup(ConstPointerArray & group)
  4819. {
  4820. CriticalBlock procedure(cs);
  4821. return input->nextGroup(group);
  4822. }
  4823. private:
  4824. CriticalSection cs;
  4825. Linked<IRoxieInput> input;
  4826. };
  4827. //=================================================================================
  4828. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4829. {
  4830. protected:
  4831. unsigned __int64 totalCycles;
  4832. public:
  4833. IMPLEMENT_IINTERFACE;
  4834. CPseudoRoxieInput()
  4835. {
  4836. totalCycles = 0;
  4837. }
  4838. virtual unsigned __int64 queryTotalCycles() const
  4839. {
  4840. return totalCycles;
  4841. }
  4842. virtual unsigned __int64 queryLocalCycles() const
  4843. {
  4844. return totalCycles;
  4845. }
  4846. virtual IRoxieInput *queryInput(unsigned idx) const
  4847. {
  4848. return NULL;
  4849. }
  4850. virtual IRoxieServerActivity *queryActivity()
  4851. {
  4852. throwUnexpected();
  4853. }
  4854. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4855. {
  4856. throwUnexpected();
  4857. }
  4858. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4859. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4860. virtual void stop(bool aborting) { }
  4861. virtual void reset() { totalCycles = 0; }
  4862. virtual void checkAbort() { }
  4863. virtual unsigned queryId() const { throwUnexpected(); }
  4864. virtual void resetEOF() { }
  4865. };
  4866. class CIndirectRoxieInput : public CPseudoRoxieInput
  4867. {
  4868. public:
  4869. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4870. {
  4871. }
  4872. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4873. {
  4874. input->start(parentExtractSize, parentExtract, paused);
  4875. }
  4876. virtual void stop(bool aborting)
  4877. {
  4878. input->stop(aborting);
  4879. }
  4880. virtual void reset()
  4881. {
  4882. input->reset();
  4883. totalCycles = 0;
  4884. }
  4885. virtual void checkAbort()
  4886. {
  4887. input->checkAbort();
  4888. }
  4889. virtual const void * nextInGroup()
  4890. {
  4891. return input->nextInGroup();
  4892. }
  4893. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4894. {
  4895. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4896. }
  4897. virtual unsigned __int64 queryLocalCycles() const
  4898. {
  4899. __int64 ret = totalCycles - input->queryTotalCycles();
  4900. if (ret < 0)
  4901. ret = 0;
  4902. return ret;
  4903. }
  4904. virtual IRoxieInput *queryInput(unsigned idx) const
  4905. {
  4906. return input->queryInput(idx);
  4907. }
  4908. virtual unsigned queryId() const
  4909. {
  4910. return input->queryId();
  4911. }
  4912. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4913. {
  4914. return input->gatherConjunctions(collector);
  4915. }
  4916. virtual void resetEOF()
  4917. {
  4918. input->resetEOF();
  4919. }
  4920. virtual unsigned numConcreteOutputs() const
  4921. {
  4922. return input->numConcreteOutputs();
  4923. }
  4924. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  4925. {
  4926. return input->queryConcreteInput(idx);
  4927. }
  4928. virtual IOutputMetaData * queryOutputMeta() const
  4929. {
  4930. return input->queryOutputMeta();
  4931. }
  4932. virtual IRoxieServerActivity *queryActivity()
  4933. {
  4934. return input->queryActivity();
  4935. }
  4936. void setInput(IRoxieInput * _input)
  4937. {
  4938. input = _input;
  4939. }
  4940. protected:
  4941. IRoxieInput * input;
  4942. };
  4943. class CExtractMapperInput : public CIndirectRoxieInput
  4944. {
  4945. unsigned savedParentExtractSize;
  4946. const byte * savedParentExtract;
  4947. public:
  4948. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  4949. {
  4950. savedParentExtractSize = 0;
  4951. savedParentExtract = NULL;
  4952. }
  4953. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4954. {
  4955. input->start(savedParentExtractSize, savedParentExtract, paused);
  4956. }
  4957. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  4958. {
  4959. savedParentExtractSize = _savedParentExtractSize;
  4960. savedParentExtract = _savedParentExtract;
  4961. }
  4962. };
  4963. class CGraphResult : public CInterface, implements IGraphResult
  4964. {
  4965. CriticalSection cs;
  4966. byte **rowset;
  4967. size32_t count;
  4968. bool complete;
  4969. void clear()
  4970. {
  4971. CriticalBlock func(cs);
  4972. rtlReleaseRowset(count, rowset);
  4973. rowset = NULL;
  4974. count = 0;
  4975. complete = false;
  4976. }
  4977. public:
  4978. IMPLEMENT_IINTERFACE
  4979. CGraphResult()
  4980. {
  4981. complete = false; // dummy result is not supposed to be used...
  4982. rowset = NULL;
  4983. count = 0;
  4984. }
  4985. CGraphResult(size32_t _count, byte **_rowset)
  4986. : count(_count), rowset(_rowset)
  4987. {
  4988. complete = true;
  4989. }
  4990. ~CGraphResult()
  4991. {
  4992. clear();
  4993. }
  4994. // interface IGraphResult
  4995. virtual IRoxieInput * createIterator()
  4996. {
  4997. if (!complete)
  4998. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  4999. return new CGraphResultIterator(this);
  5000. }
  5001. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5002. {
  5003. if (!complete)
  5004. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5005. result = rtlLinkRowset(rowset);
  5006. countResult = count;
  5007. }
  5008. //other
  5009. const void * getRow(unsigned i)
  5010. {
  5011. CriticalBlock func(cs);
  5012. if (i >= count)
  5013. return NULL;
  5014. const void * ret = rowset[i];
  5015. if (ret) LinkRoxieRow(ret);
  5016. return ret;
  5017. }
  5018. protected:
  5019. class CGraphResultIterator : public CPseudoRoxieInput
  5020. {
  5021. unsigned i;
  5022. Linked<CGraphResult> result;
  5023. public:
  5024. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5025. IMPLEMENT_IINTERFACE
  5026. public:
  5027. virtual const void * nextInGroup()
  5028. {
  5029. return result->getRow(i++);
  5030. }
  5031. };
  5032. };
  5033. //=================================================================================
  5034. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5035. {
  5036. IHThorLocalResultReadArg &helper;
  5037. Owned<IRoxieInput> iter;
  5038. ILocalGraphEx * graph;
  5039. unsigned graphId;
  5040. unsigned sequence;
  5041. public:
  5042. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5043. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5044. {
  5045. graph = NULL;
  5046. sequence = 0;
  5047. }
  5048. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5049. {
  5050. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5051. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5052. sequence = helper.querySequence();
  5053. }
  5054. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5055. {
  5056. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5057. iter.setown(graph->createResultIterator(sequence));
  5058. }
  5059. virtual void reset()
  5060. {
  5061. iter.clear();
  5062. CRoxieServerActivity::reset();
  5063. };
  5064. virtual const void *nextInGroup()
  5065. {
  5066. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5067. const void * next = iter->nextInGroup();
  5068. if (next)
  5069. {
  5070. processed++;
  5071. atomic_inc(&rowsIn);
  5072. }
  5073. return next;
  5074. }
  5075. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5076. {
  5077. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5078. }
  5079. };
  5080. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5081. {
  5082. unsigned graphId;
  5083. public:
  5084. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5085. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5086. {
  5087. }
  5088. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5089. {
  5090. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5091. }
  5092. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5093. {
  5094. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5095. }
  5096. };
  5097. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5098. {
  5099. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5100. }
  5101. //=================================================================================
  5102. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5103. {
  5104. IHThorLocalResultReadArg &helper;
  5105. Owned<IRoxieInput> streamInput;
  5106. unsigned sequence;
  5107. public:
  5108. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5109. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5110. {
  5111. sequence = 0;
  5112. }
  5113. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5114. {
  5115. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5116. sequence = helper.querySequence();
  5117. }
  5118. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5119. {
  5120. assertex(streamInput != NULL);
  5121. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5122. streamInput->start(parentExtractSize, parentExtract, paused);
  5123. }
  5124. virtual void stop(bool aborting)
  5125. {
  5126. CRoxieServerActivity::stop(aborting);
  5127. streamInput->stop(aborting);
  5128. }
  5129. virtual void reset()
  5130. {
  5131. streamInput->reset();
  5132. CRoxieServerActivity::reset();
  5133. };
  5134. virtual const void *nextInGroup()
  5135. {
  5136. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5137. const void * next = streamInput->nextInGroup();
  5138. if (next)
  5139. {
  5140. processed++;
  5141. atomic_inc(&rowsIn);
  5142. }
  5143. return next;
  5144. }
  5145. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5146. {
  5147. if (id == sequence)
  5148. {
  5149. streamInput.set(_input);
  5150. return true;
  5151. }
  5152. return false;
  5153. }
  5154. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5155. {
  5156. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5157. }
  5158. };
  5159. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5160. {
  5161. public:
  5162. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5163. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5164. {
  5165. }
  5166. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5167. {
  5168. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5169. }
  5170. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5171. {
  5172. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5173. }
  5174. };
  5175. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5176. {
  5177. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5178. }
  5179. //=====================================================================================================
  5180. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5181. {
  5182. IHThorLocalResultWriteArg &helper;
  5183. ILocalGraphEx * graph;
  5184. unsigned graphId;
  5185. public:
  5186. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5187. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5188. {
  5189. graph = NULL;
  5190. }
  5191. virtual bool needsAllocator() const { return true; }
  5192. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5193. {
  5194. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5195. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5196. }
  5197. virtual void onExecute()
  5198. {
  5199. RtlLinkedDatasetBuilder builder(rowAllocator);
  5200. input->readAll(builder);
  5201. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5202. graph->setResult(helper.querySequence(), result);
  5203. }
  5204. IRoxieInput * querySelectOutput(unsigned id)
  5205. {
  5206. if (id == helper.querySequence())
  5207. {
  5208. executed = true;
  5209. return LINK(input);
  5210. }
  5211. return NULL;
  5212. }
  5213. };
  5214. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5215. {
  5216. unsigned graphId;
  5217. public:
  5218. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5219. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5220. {
  5221. isInternal = true;
  5222. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5223. }
  5224. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5225. {
  5226. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId);
  5227. }
  5228. };
  5229. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5230. {
  5231. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5232. }
  5233. //=====================================================================================================
  5234. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5235. {
  5236. IHThorDictionaryResultWriteArg &helper;
  5237. ILocalGraphEx * graph;
  5238. unsigned graphId;
  5239. public:
  5240. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5241. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5242. {
  5243. graph = NULL;
  5244. }
  5245. virtual bool needsAllocator() const { return true; }
  5246. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5247. {
  5248. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5249. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5250. }
  5251. virtual void onExecute()
  5252. {
  5253. unsigned sequence = helper.querySequence();
  5254. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5255. loop
  5256. {
  5257. const void *row = input->nextInGroup();
  5258. if (!row)
  5259. {
  5260. row = input->nextInGroup();
  5261. if (!row)
  5262. break;
  5263. }
  5264. builder.appendOwn(row);
  5265. processed++;
  5266. }
  5267. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5268. graph->setResult(helper.querySequence(), result);
  5269. }
  5270. IRoxieInput * querySelectOutput(unsigned id)
  5271. {
  5272. if (id == helper.querySequence())
  5273. {
  5274. executed = true;
  5275. return LINK(input);
  5276. }
  5277. return NULL;
  5278. }
  5279. };
  5280. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5281. {
  5282. unsigned graphId;
  5283. public:
  5284. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5285. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5286. {
  5287. isInternal = true;
  5288. }
  5289. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5290. {
  5291. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, graphId);
  5292. }
  5293. };
  5294. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5295. {
  5296. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5297. }
  5298. //=================================================================================
  5299. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5300. {
  5301. protected:
  5302. IHThorGraphLoopResultReadArg &helper;
  5303. Owned<IRoxieInput> iter;
  5304. ILocalGraphEx * graph;
  5305. unsigned graphId;
  5306. unsigned sequence;
  5307. public:
  5308. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5309. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5310. {
  5311. graph = NULL;
  5312. sequence = 0;
  5313. }
  5314. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5315. {
  5316. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5317. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5318. }
  5319. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5320. {
  5321. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5322. if (iter)
  5323. iter->start(parentExtractSize, parentExtract, paused);
  5324. else
  5325. {
  5326. sequence = helper.querySequence();
  5327. if ((int)sequence >= 0)
  5328. {
  5329. try
  5330. {
  5331. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5332. }
  5333. catch (IException * E)
  5334. {
  5335. throw makeWrappedException(E);
  5336. }
  5337. }
  5338. }
  5339. }
  5340. virtual void stop(bool aborting)
  5341. {
  5342. if (iter)
  5343. iter->stop(aborting);
  5344. CRoxieServerActivity::stop(aborting);
  5345. }
  5346. virtual void reset()
  5347. {
  5348. if (iter)
  5349. iter->reset();
  5350. iter.clear();
  5351. CRoxieServerActivity::reset();
  5352. };
  5353. virtual const void *nextInGroup()
  5354. {
  5355. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5356. const void * next = iter ? iter->nextInGroup() : NULL;
  5357. if (next)
  5358. {
  5359. processed++;
  5360. atomic_inc(&rowsIn);
  5361. }
  5362. return next;
  5363. }
  5364. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5365. {
  5366. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5367. }
  5368. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5369. {
  5370. ensureCreated();
  5371. basehelper.onStart(parentExtract, NULL);
  5372. processor.noteUseIteration(helper.querySequence());
  5373. }
  5374. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5375. {
  5376. //helper already initialised from the gratherIterationUsage() call.
  5377. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5378. }
  5379. virtual IInputSteppingMeta * querySteppingMeta()
  5380. {
  5381. assertex(iter);
  5382. return iter->querySteppingMeta();
  5383. }
  5384. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5385. {
  5386. assertex(iter);
  5387. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5388. }
  5389. };
  5390. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5391. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5392. {
  5393. public:
  5394. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5395. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5396. {
  5397. sequence = _sequence;
  5398. }
  5399. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5400. {
  5401. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5402. if ((int)sequence >= 0)
  5403. {
  5404. try
  5405. {
  5406. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5407. }
  5408. catch (IException * E)
  5409. {
  5410. throw makeWrappedException(E);
  5411. }
  5412. }
  5413. }
  5414. };
  5415. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5416. {
  5417. unsigned graphId;
  5418. public:
  5419. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5420. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5421. {
  5422. }
  5423. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5424. {
  5425. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5426. }
  5427. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5428. {
  5429. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5430. }
  5431. };
  5432. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5433. {
  5434. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5435. }
  5436. //=====================================================================================================
  5437. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5438. {
  5439. IHThorGraphLoopResultWriteArg &helper;
  5440. ILocalGraphEx * graph;
  5441. unsigned graphId;
  5442. public:
  5443. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5444. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5445. {
  5446. graph = NULL;
  5447. }
  5448. virtual bool needsAllocator() const { return true; }
  5449. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5450. {
  5451. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5452. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5453. }
  5454. virtual void onExecute()
  5455. {
  5456. RtlLinkedDatasetBuilder builder(rowAllocator);
  5457. input->readAll(builder);
  5458. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5459. graph->setGraphLoopResult(result);
  5460. }
  5461. virtual IRoxieInput *queryOutput(unsigned idx)
  5462. {
  5463. if (idx==0)
  5464. return this;
  5465. else
  5466. return NULL;
  5467. }
  5468. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5469. {
  5470. return input->gatherConjunctions(collector);
  5471. }
  5472. virtual void resetEOF()
  5473. {
  5474. input->resetEOF();
  5475. }
  5476. virtual const void *nextInGroup()
  5477. {
  5478. const void * next = input->nextInGroup();
  5479. if (next)
  5480. processed++;
  5481. return next;
  5482. }
  5483. virtual bool isPassThrough()
  5484. {
  5485. return true;
  5486. }
  5487. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5488. {
  5489. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5490. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5491. if (next)
  5492. processed++;
  5493. return next;
  5494. }
  5495. IInputSteppingMeta * querySteppingMeta()
  5496. {
  5497. return input->querySteppingMeta();
  5498. }
  5499. virtual IOutputMetaData * queryOutputMeta() const
  5500. {
  5501. return input->queryOutputMeta();
  5502. }
  5503. };
  5504. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5505. {
  5506. unsigned graphId;
  5507. public:
  5508. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5509. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5510. {
  5511. isInternal = true;
  5512. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5513. }
  5514. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5515. {
  5516. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId);
  5517. }
  5518. };
  5519. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5520. {
  5521. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5522. }
  5523. #if 0
  5524. //=====================================================================================================
  5525. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5526. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5527. {
  5528. next = NULL;
  5529. }
  5530. void CHThorLocalResultSpillActivity::ready()
  5531. {
  5532. CHThorSimpleActivityBase::ready();
  5533. next = input->nextInGroup();
  5534. grouped = input->isGrouped();
  5535. rowdata.clear();
  5536. }
  5537. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5538. {
  5539. const void * ret = next;
  5540. next = input->nextInGroup();
  5541. if (!ret && !next)
  5542. return NULL;
  5543. if (ret)
  5544. {
  5545. size32_t thisSize = outputMeta->getRecordSize(ret);
  5546. rowdata.append(thisSize, ret);
  5547. if (grouped)
  5548. rowdata.append(next == NULL);
  5549. }
  5550. return ret;
  5551. }
  5552. void CHThorLocalResultSpillActivity::done()
  5553. {
  5554. loop
  5555. {
  5556. const void * ret = nextInGroup();
  5557. if (!ret)
  5558. {
  5559. ret = nextInGroup();
  5560. if (!ret)
  5561. break;
  5562. }
  5563. ReleaseRoxieRow(ret);
  5564. }
  5565. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5566. CHThorSimpleActivityBase::done();
  5567. }
  5568. #endif
  5569. //=================================================================================
  5570. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5571. {
  5572. IHThorDedupArg &helper;
  5573. bool keepLeft;
  5574. bool first;
  5575. unsigned numKept;
  5576. unsigned numToKeep;
  5577. const void *kept;
  5578. public:
  5579. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5580. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5581. {
  5582. keepLeft = _keepLeft;
  5583. kept = NULL;
  5584. numKept = 0;
  5585. first = true;
  5586. numToKeep = 0;
  5587. }
  5588. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5589. {
  5590. numKept = 0;
  5591. first = true;
  5592. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5593. numToKeep = helper.numToKeep();
  5594. }
  5595. virtual void reset()
  5596. {
  5597. ReleaseClearRoxieRow(kept);
  5598. CRoxieServerActivity::reset();
  5599. }
  5600. virtual const void * nextInGroup()
  5601. {
  5602. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5603. if (first)
  5604. {
  5605. kept = input->nextInGroup();
  5606. first = false;
  5607. }
  5608. const void * next;
  5609. loop
  5610. {
  5611. next = input->nextInGroup();
  5612. if (!kept || !next || !helper.matches(kept,next))
  5613. {
  5614. numKept = 0;
  5615. break;
  5616. }
  5617. if (numKept < numToKeep-1)
  5618. {
  5619. numKept++;
  5620. break;
  5621. }
  5622. if (keepLeft)
  5623. {
  5624. ReleaseRoxieRow(next);
  5625. }
  5626. else
  5627. {
  5628. ReleaseRoxieRow(kept);
  5629. kept = next;
  5630. }
  5631. }
  5632. const void * ret = kept;
  5633. kept = next;
  5634. // CTXLOG("dedup returns %p", ret);
  5635. if (ret) processed++;
  5636. return ret;
  5637. }
  5638. };
  5639. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5640. {
  5641. IHThorDedupArg &helper;
  5642. unsigned survivorIndex;
  5643. ConstPointerArray survivors;
  5644. bool keepLeft;
  5645. bool eof;
  5646. bool first;
  5647. ICompare *primaryCompare;
  5648. public:
  5649. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5650. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5651. {
  5652. keepLeft = _keepLeft;
  5653. primaryCompare = helper.queryComparePrimary();
  5654. eof = false;
  5655. first = true;
  5656. survivorIndex = 0;
  5657. }
  5658. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5659. {
  5660. eof = false;
  5661. first = true;
  5662. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5663. }
  5664. virtual void reset()
  5665. {
  5666. #ifdef _DEBUG
  5667. while (survivors.isItem(survivorIndex))
  5668. {
  5669. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5670. }
  5671. #endif
  5672. survivors.kill();
  5673. eof = false;
  5674. first = true;
  5675. CRoxieServerActivity::reset();
  5676. }
  5677. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5678. {
  5679. for (unsigned idxL = first; idxL < last; idxL++)
  5680. {
  5681. const void * left = group.item(idxL);
  5682. if (left)
  5683. {
  5684. for (unsigned idxR = first; idxR < last; idxR++)
  5685. {
  5686. const void * right = group.item(idxR);
  5687. if ((idxL != idxR) && right)
  5688. {
  5689. if (helper.matches(left, right))
  5690. {
  5691. if (keepLeft)
  5692. {
  5693. group.replace(NULL, idxR);
  5694. ReleaseRoxieRow(right);
  5695. }
  5696. else
  5697. {
  5698. group.replace(NULL, idxL);
  5699. ReleaseRoxieRow(left);
  5700. break;
  5701. }
  5702. }
  5703. }
  5704. }
  5705. }
  5706. }
  5707. }
  5708. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5709. {
  5710. for (unsigned idxL = first; idxL < last; idxL++)
  5711. {
  5712. void * left = *(index[idxL]);
  5713. if (left)
  5714. {
  5715. for (unsigned idxR = first; idxR < last; idxR++)
  5716. {
  5717. void * right = *(index[idxR]);
  5718. if ((idxL != idxR) && right)
  5719. {
  5720. if (helper.matches(left, right))
  5721. {
  5722. if (keepLeft)
  5723. {
  5724. *(index[idxR]) = NULL;
  5725. ReleaseRoxieRow(right);
  5726. }
  5727. else
  5728. {
  5729. *(index[idxL]) = NULL;
  5730. ReleaseRoxieRow(left);
  5731. break;
  5732. }
  5733. }
  5734. }
  5735. }
  5736. }
  5737. }
  5738. }
  5739. bool calcNextDedupAll()
  5740. {
  5741. survivors.kill();
  5742. survivorIndex = 0;
  5743. ConstPointerArray group;
  5744. if (eof || !input->nextGroup(group))
  5745. {
  5746. eof = true;
  5747. return false;
  5748. }
  5749. unsigned max = group.ordinality();
  5750. if (primaryCompare)
  5751. {
  5752. //hard, if not impossible, to hit this code once optimisations in place
  5753. MemoryAttr indexbuff(max*sizeof(void **));
  5754. void *** index = (void ***)indexbuff.bufferBase();
  5755. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  5756. unsigned first = 0;
  5757. for (unsigned idx = 1; idx < max; idx++)
  5758. {
  5759. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  5760. {
  5761. dedupRangeIndirect(first, idx, index);
  5762. first = idx;
  5763. }
  5764. }
  5765. dedupRangeIndirect(first, max, index);
  5766. for(unsigned idx2=0; idx2<max; ++idx2)
  5767. {
  5768. void * cur = *(index[idx2]);
  5769. if(cur)
  5770. survivors.append(cur);
  5771. }
  5772. }
  5773. else
  5774. {
  5775. dedupRange(0, max, group);
  5776. for(unsigned idx=0; idx<max; ++idx)
  5777. {
  5778. const void * cur = group.item(idx);
  5779. if(cur)
  5780. survivors.append(cur);
  5781. }
  5782. }
  5783. return true;
  5784. }
  5785. virtual const void *nextInGroup()
  5786. {
  5787. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5788. if (first)
  5789. {
  5790. calcNextDedupAll();
  5791. first = false;
  5792. }
  5793. while (survivors.isItem(survivorIndex))
  5794. {
  5795. const void *ret = survivors.item(survivorIndex++);
  5796. if (ret)
  5797. {
  5798. processed++;
  5799. return ret;
  5800. }
  5801. }
  5802. calcNextDedupAll();
  5803. return NULL;
  5804. }
  5805. };
  5806. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  5807. {
  5808. bool compareAll;
  5809. bool keepLeft;
  5810. public:
  5811. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5812. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5813. {
  5814. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  5815. compareAll = helper->compareAll();
  5816. keepLeft = helper->keepLeft();
  5817. }
  5818. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5819. {
  5820. if (compareAll)
  5821. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  5822. else
  5823. return new CRoxieServerDedupActivity(this, _probeManager, keepLeft);
  5824. }
  5825. };
  5826. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5827. {
  5828. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5829. }
  5830. //=================================================================================
  5831. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  5832. {
  5833. bool eof;
  5834. IHThorHashDedupArg &helper;
  5835. class HashDedupElement
  5836. {
  5837. public:
  5838. HashDedupElement(unsigned _hash, const void *_keyRow)
  5839. : hash(_hash), keyRow(_keyRow)
  5840. {
  5841. }
  5842. ~HashDedupElement()
  5843. {
  5844. ReleaseRoxieRow(keyRow);
  5845. }
  5846. inline unsigned queryHash() const
  5847. {
  5848. return hash;
  5849. }
  5850. inline const void *queryRow() const
  5851. {
  5852. return keyRow;
  5853. }
  5854. private:
  5855. unsigned hash;
  5856. const void *keyRow;
  5857. };
  5858. class HashDedupTable : public SuperHashTable
  5859. {
  5860. public:
  5861. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  5862. : helper(_helper),
  5863. activityId(_activityId),
  5864. keySize(helper.queryKeySize())
  5865. {
  5866. }
  5867. virtual ~HashDedupTable() { releaseAll(); }
  5868. virtual unsigned getHashFromElement(const void *et) const
  5869. {
  5870. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  5871. return element->queryHash();
  5872. }
  5873. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  5874. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  5875. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  5876. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  5877. {
  5878. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  5879. if (fphash != element->queryHash())
  5880. return false;
  5881. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  5882. }
  5883. virtual void onAdd(void *et) {}
  5884. virtual void onRemove(void *et)
  5885. {
  5886. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  5887. delete element;
  5888. }
  5889. void onCreate(IRoxieSlaveContext *ctx)
  5890. {
  5891. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  5892. }
  5893. void reset()
  5894. {
  5895. kill();
  5896. }
  5897. bool insert(const void * row)
  5898. {
  5899. unsigned hash = helper.queryHash()->hash(row);
  5900. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  5901. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  5902. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  5903. if (find(hash, keyRow.get()))
  5904. return false;
  5905. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  5906. return true;
  5907. }
  5908. private:
  5909. IHThorHashDedupArg & helper;
  5910. CachedOutputMetaData keySize;
  5911. Owned<IEngineRowAllocator> keyRowAllocator;
  5912. unsigned activityId;
  5913. } table;
  5914. public:
  5915. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5916. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  5917. {
  5918. eof = false;
  5919. }
  5920. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5921. {
  5922. eof = false;
  5923. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5924. }
  5925. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  5926. {
  5927. CRoxieServerActivity::onCreate(ctx, colocalParent);
  5928. table.onCreate(ctx);
  5929. }
  5930. virtual void reset()
  5931. {
  5932. table.reset();
  5933. eof = false;
  5934. CRoxieServerActivity::reset();
  5935. }
  5936. virtual const void *nextInGroup()
  5937. {
  5938. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5939. while(!eof)
  5940. {
  5941. const void * next = input->nextInGroup();
  5942. if(!next)
  5943. {
  5944. if (table.count() == 0)
  5945. eof = true;
  5946. table.reset();
  5947. return NULL;
  5948. }
  5949. if(table.insert(next))
  5950. return next;
  5951. else
  5952. ReleaseRoxieRow(next);
  5953. }
  5954. return NULL;
  5955. }
  5956. };
  5957. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  5958. {
  5959. public:
  5960. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5961. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5962. {
  5963. }
  5964. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5965. {
  5966. return new CRoxieServerHashDedupActivity(this, _probeManager);
  5967. }
  5968. };
  5969. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5970. {
  5971. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5972. }
  5973. //=================================================================================
  5974. class CRoxieServerRollupActivity : public CRoxieServerActivity
  5975. {
  5976. IHThorRollupArg &helper;
  5977. OwnedConstRoxieRow left;
  5978. OwnedConstRoxieRow prev;
  5979. OwnedConstRoxieRow right;
  5980. bool readFirstRow;
  5981. public:
  5982. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5983. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  5984. {
  5985. readFirstRow = false;
  5986. }
  5987. ~CRoxieServerRollupActivity()
  5988. {
  5989. }
  5990. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5991. {
  5992. readFirstRow = false;
  5993. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5994. }
  5995. virtual void reset()
  5996. {
  5997. left.clear();
  5998. prev.clear();
  5999. right.clear();
  6000. CRoxieServerActivity::reset();
  6001. }
  6002. virtual bool needsAllocator() const { return true; }
  6003. virtual const void * nextInGroup()
  6004. {
  6005. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6006. if (!readFirstRow)
  6007. {
  6008. left.setown(input->nextInGroup());
  6009. prev.set(left);
  6010. readFirstRow = true;
  6011. }
  6012. loop
  6013. {
  6014. right.setown(input->nextInGroup());
  6015. if(!prev || !right || !helper.matches(prev,right))
  6016. {
  6017. const void * ret = left.getClear();
  6018. if(ret)
  6019. processed++;
  6020. left.setown(right.getClear());
  6021. prev.set(left);
  6022. return ret;
  6023. }
  6024. try
  6025. {
  6026. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6027. unsigned outSize = helper.transform(rowBuilder, left, right);
  6028. if (outSize)
  6029. left.setown(rowBuilder.finalizeRowClear(outSize));
  6030. if (helper.getFlags() & RFrolledismatchleft)
  6031. prev.set(left);
  6032. else
  6033. prev.set(right);
  6034. }
  6035. catch(IException * E)
  6036. {
  6037. throw makeWrappedException(E);
  6038. }
  6039. }
  6040. }
  6041. };
  6042. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6043. {
  6044. public:
  6045. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6046. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6047. {
  6048. }
  6049. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6050. {
  6051. return new CRoxieServerRollupActivity(this, _probeManager);
  6052. }
  6053. };
  6054. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6055. {
  6056. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6057. }
  6058. //=================================================================================
  6059. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6060. {
  6061. IHThorNormalizeArg &helper;
  6062. unsigned numThisRow;
  6063. unsigned curRow;
  6064. const void *buffer;
  6065. unsigned numProcessedLastGroup;
  6066. public:
  6067. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6068. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6069. {
  6070. buffer = NULL;
  6071. numThisRow = 0;
  6072. curRow = 0;
  6073. numProcessedLastGroup = 0;
  6074. }
  6075. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6076. {
  6077. numThisRow = 0;
  6078. curRow = 0;
  6079. numProcessedLastGroup = 0;
  6080. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6081. }
  6082. virtual void reset()
  6083. {
  6084. ReleaseClearRoxieRow(buffer);
  6085. CRoxieServerActivity::reset();
  6086. }
  6087. virtual bool needsAllocator() const { return true; }
  6088. virtual const void * nextInGroup()
  6089. {
  6090. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6091. loop
  6092. {
  6093. while (curRow == numThisRow)
  6094. {
  6095. if (buffer)
  6096. ReleaseClearRoxieRow(buffer);
  6097. buffer = input->nextInGroup();
  6098. if (!buffer && (processed == numProcessedLastGroup))
  6099. buffer = input->nextInGroup();
  6100. if (!buffer)
  6101. {
  6102. numProcessedLastGroup = processed;
  6103. return NULL;
  6104. }
  6105. curRow = 0;
  6106. numThisRow = helper.numExpandedRows(buffer);
  6107. }
  6108. try
  6109. {
  6110. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6111. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6112. if (actualSize != 0)
  6113. {
  6114. processed++;
  6115. return rowBuilder.finalizeRowClear(actualSize);
  6116. }
  6117. }
  6118. catch (IException *E)
  6119. {
  6120. throw makeWrappedException(E);
  6121. }
  6122. }
  6123. }
  6124. };
  6125. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6126. {
  6127. public:
  6128. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6129. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6130. {
  6131. }
  6132. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6133. {
  6134. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6135. }
  6136. };
  6137. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6138. {
  6139. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6140. }
  6141. //=================================================================================
  6142. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6143. {
  6144. IHThorNormalizeChildArg &helper;
  6145. unsigned numThisRow;
  6146. unsigned curRow;
  6147. const void *buffer;
  6148. unsigned numProcessedLastGroup;
  6149. INormalizeChildIterator * cursor;
  6150. const void * curChildRow;
  6151. bool advanceInput()
  6152. {
  6153. loop
  6154. {
  6155. ReleaseClearRoxieRow(buffer);
  6156. buffer = input->nextInGroup();
  6157. if (!buffer && (processed == numProcessedLastGroup))
  6158. buffer = input->nextInGroup();
  6159. if (!buffer)
  6160. {
  6161. numProcessedLastGroup = processed;
  6162. return false;
  6163. }
  6164. curChildRow = cursor->first(buffer);
  6165. if (curChildRow)
  6166. {
  6167. curRow = 0;
  6168. return true;
  6169. }
  6170. }
  6171. }
  6172. public:
  6173. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6174. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6175. {
  6176. buffer = NULL;
  6177. cursor = NULL;
  6178. numThisRow = 0;
  6179. curRow = 0;
  6180. numProcessedLastGroup = 0;
  6181. curChildRow = NULL;
  6182. }
  6183. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6184. {
  6185. numThisRow = 0;
  6186. curRow = 0;
  6187. numProcessedLastGroup = 0;
  6188. curChildRow = NULL;
  6189. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6190. cursor = helper.queryIterator();
  6191. }
  6192. virtual void stop(bool aborting)
  6193. {
  6194. CRoxieServerActivity::stop(aborting);
  6195. }
  6196. virtual void reset()
  6197. {
  6198. cursor = NULL;
  6199. ReleaseClearRoxieRow(buffer);
  6200. CRoxieServerActivity::reset();
  6201. }
  6202. virtual bool needsAllocator() const { return true; }
  6203. const void *nextInGroup()
  6204. {
  6205. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6206. loop
  6207. {
  6208. if (!buffer)
  6209. {
  6210. if (!advanceInput())
  6211. return NULL;
  6212. }
  6213. try
  6214. {
  6215. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6216. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6217. curChildRow = cursor->next();
  6218. if (!curChildRow)
  6219. ReleaseClearRoxieRow(buffer);
  6220. if (outSize != 0)
  6221. {
  6222. processed++;
  6223. return rowBuilder.finalizeRowClear(outSize);
  6224. }
  6225. }
  6226. catch (IException *E)
  6227. {
  6228. throw makeWrappedException(E);
  6229. }
  6230. }
  6231. }
  6232. };
  6233. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6234. {
  6235. public:
  6236. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6237. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6238. {
  6239. }
  6240. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6241. {
  6242. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6243. }
  6244. };
  6245. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6246. {
  6247. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6248. }
  6249. //=================================================================================
  6250. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6251. {
  6252. IHThorNormalizeLinkedChildArg &helper;
  6253. OwnedConstRoxieRow curParent;
  6254. OwnedConstRoxieRow curChild;
  6255. unsigned numProcessedLastGroup;
  6256. bool advanceInput()
  6257. {
  6258. loop
  6259. {
  6260. curParent.setown(input->nextInGroup());
  6261. if (!curParent && (processed == numProcessedLastGroup))
  6262. curParent.setown(input->nextInGroup());
  6263. if (!curParent)
  6264. {
  6265. numProcessedLastGroup = processed;
  6266. return false;
  6267. }
  6268. curChild.set(helper.first(curParent));
  6269. if (curChild)
  6270. return true;
  6271. }
  6272. }
  6273. public:
  6274. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6275. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6276. {
  6277. numProcessedLastGroup = 0;
  6278. }
  6279. ~CRoxieServerNormalizeLinkedChildActivity()
  6280. {
  6281. }
  6282. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6283. {
  6284. numProcessedLastGroup = 0;
  6285. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6286. }
  6287. virtual void reset()
  6288. {
  6289. curParent.clear();
  6290. curChild.clear();
  6291. CRoxieServerActivity::reset();
  6292. }
  6293. const void *nextInGroup()
  6294. {
  6295. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6296. loop
  6297. {
  6298. if (!curParent)
  6299. {
  6300. if (!advanceInput())
  6301. return NULL;
  6302. }
  6303. try
  6304. {
  6305. const void *ret = curChild.getClear();
  6306. curChild.set(helper.next());
  6307. if (!curChild)
  6308. curParent.clear();
  6309. if (ret)
  6310. {
  6311. processed++;
  6312. return ret;
  6313. }
  6314. }
  6315. catch (IException *E)
  6316. {
  6317. throw makeWrappedException(E);
  6318. }
  6319. }
  6320. }
  6321. };
  6322. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6323. {
  6324. public:
  6325. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6326. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6327. {
  6328. }
  6329. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6330. {
  6331. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6332. }
  6333. };
  6334. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6335. {
  6336. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6337. }
  6338. //=================================================================================
  6339. interface ISortAlgorithm : extends IInterface
  6340. {
  6341. virtual void prepare(IRoxieInput *input) = 0;
  6342. virtual const void *next() = 0;
  6343. virtual void reset() = 0;
  6344. };
  6345. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6346. {
  6347. unsigned curIndex;
  6348. ConstPointerArray sorted;
  6349. ICompare *compare;
  6350. public:
  6351. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6352. {
  6353. curIndex = 0;
  6354. }
  6355. virtual void prepare(IRoxieInput *input)
  6356. {
  6357. curIndex = 0;
  6358. if (input->nextGroup(sorted))
  6359. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6360. }
  6361. virtual const void *next()
  6362. {
  6363. if (sorted.isItem(curIndex))
  6364. return sorted.item(curIndex++);
  6365. return NULL;
  6366. }
  6367. virtual void reset()
  6368. {
  6369. while (sorted.isItem(curIndex))
  6370. ReleaseRoxieRow(sorted.item(curIndex++));
  6371. curIndex = 0;
  6372. sorted.kill();
  6373. }
  6374. };
  6375. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6376. {
  6377. enum {
  6378. InitialSortElements = 0,
  6379. //The number of rows that can be added without entering a critical section, and therefore also the number
  6380. //of rows that might not get freed when memory gets tight.
  6381. CommitStep=32
  6382. };
  6383. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6384. roxiemem::RoxieSimpleInputRowArray sorted;
  6385. ICompare *compare;
  6386. IRoxieSlaveContext * ctx;
  6387. Owned<IDiskMerger> diskMerger;
  6388. Owned<IRowStream> diskReader;
  6389. Owned<IOutputMetaData> rowMeta;
  6390. unsigned activityId;
  6391. public:
  6392. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId)
  6393. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep), ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId)
  6394. {
  6395. ctx->queryRowManager().addRowBuffer(this);
  6396. }
  6397. ~CSpillingQuickSortAlgorithm()
  6398. {
  6399. ctx->queryRowManager().removeRowBuffer(this);
  6400. diskReader.clear();
  6401. }
  6402. virtual void prepare(IRoxieInput *input)
  6403. {
  6404. loop
  6405. {
  6406. const void * next = input->nextInGroup();
  6407. if (!next)
  6408. break;
  6409. if (!rowsToSort.append(next))
  6410. {
  6411. {
  6412. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6413. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6414. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6415. //rows first).
  6416. if (rowsToSort.numCommitted() != 0)
  6417. {
  6418. rowsToSort.flush();
  6419. spillRows();
  6420. }
  6421. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6422. //spillRows() cannot shift active row pointer since it can be called from any thread
  6423. rowsToSort.flush();
  6424. }
  6425. if (!rowsToSort.append(next))
  6426. {
  6427. ReleaseRoxieRow(next);
  6428. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6429. }
  6430. }
  6431. }
  6432. rowsToSort.flush();
  6433. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6434. if (diskMerger)
  6435. {
  6436. spillRows();
  6437. rowsToSort.kill();
  6438. diskReader.setown(diskMerger->merge(compare));
  6439. }
  6440. else
  6441. {
  6442. unsigned numRows = rowsToSort.numCommitted();
  6443. if (numRows)
  6444. {
  6445. const void * * rows = rowsToSort.getBlock(numRows);
  6446. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6447. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6448. }
  6449. sorted.transferFrom(rowsToSort);
  6450. }
  6451. }
  6452. virtual const void *next()
  6453. {
  6454. if(diskReader)
  6455. return diskReader->nextRow();
  6456. return sorted.dequeue();
  6457. }
  6458. virtual void reset()
  6459. {
  6460. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6461. //fewer heap allocations with not freeing up the memory from large group sorts.
  6462. rowsToSort.clearRows();
  6463. sorted.kill();
  6464. //Disk reader must be cleared before the merger - or the files may still be locked.
  6465. diskReader.clear();
  6466. diskMerger.clear();
  6467. }
  6468. //interface roxiemem::IBufferedRowCallback
  6469. virtual unsigned getPriority() const
  6470. {
  6471. //Spill global sorts before grouped sorts
  6472. if (rowMeta->isGrouped())
  6473. return 20;
  6474. return 10;
  6475. }
  6476. virtual bool freeBufferedRows(bool critical)
  6477. {
  6478. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6479. return spillRows();
  6480. }
  6481. protected:
  6482. bool spillRows()
  6483. {
  6484. unsigned numRows = rowsToSort.numCommitted();
  6485. if (numRows == 0)
  6486. return false;
  6487. const void * * rows = rowsToSort.getBlock(numRows);
  6488. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6489. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6490. for (unsigned i= 0; i < numRows; i++)
  6491. {
  6492. out->putRow(rows[i]);
  6493. }
  6494. rowsToSort.noteSpilled(numRows);
  6495. return true;
  6496. }
  6497. IDiskMerger * queryMerger()
  6498. {
  6499. if (!diskMerger)
  6500. {
  6501. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6502. StringBuffer spillBasename;
  6503. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%"I64F"u", seq);
  6504. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6505. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6506. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6507. }
  6508. return diskMerger;
  6509. }
  6510. };
  6511. #define INSERTION_SORT_BLOCKSIZE 1024
  6512. class SortedBlock : public CInterface, implements IInterface
  6513. {
  6514. unsigned sequence;
  6515. const void **rows;
  6516. unsigned length;
  6517. unsigned pos;
  6518. SortedBlock(const SortedBlock &);
  6519. public:
  6520. IMPLEMENT_IINTERFACE;
  6521. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6522. {
  6523. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6524. length = 0;
  6525. pos = 0;
  6526. }
  6527. ~SortedBlock()
  6528. {
  6529. while (pos < length)
  6530. ReleaseRoxieRow(rows[pos++]);
  6531. ReleaseRoxieRow(rows);
  6532. }
  6533. int compareTo(SortedBlock *r, ICompare *compare)
  6534. {
  6535. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6536. if (!rc)
  6537. rc = sequence - r->sequence;
  6538. return rc;
  6539. }
  6540. const void *next()
  6541. {
  6542. if (pos < length)
  6543. return rows[pos++];
  6544. else
  6545. return NULL;
  6546. }
  6547. inline bool eof()
  6548. {
  6549. return pos==length;
  6550. }
  6551. bool insert(const void *next, ICompare *_compare )
  6552. {
  6553. unsigned b = length;
  6554. if (b == INSERTION_SORT_BLOCKSIZE)
  6555. return false;
  6556. else if (b < 7)
  6557. {
  6558. while (b)
  6559. {
  6560. if (_compare->docompare(next, rows[b-1]) >= 0)
  6561. break;
  6562. b--;
  6563. }
  6564. if (b != length)
  6565. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6566. rows[b] = next;
  6567. length++;
  6568. return true;
  6569. }
  6570. else
  6571. {
  6572. unsigned int a = 0;
  6573. while ((int)a<b)
  6574. {
  6575. int i = (a+b)/2;
  6576. int rc = _compare->docompare(next, rows[i]);
  6577. if (rc>=0)
  6578. a = i+1;
  6579. else
  6580. b = i;
  6581. }
  6582. if (a != length)
  6583. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6584. rows[a] = next;
  6585. length++;
  6586. return true;
  6587. }
  6588. }
  6589. };
  6590. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6591. {
  6592. SortedBlock *curBlock;
  6593. unsigned blockNo;
  6594. IArrayOf<SortedBlock> blocks;
  6595. unsigned activityId;
  6596. IRowManager *rowManager;
  6597. ICompare *compare;
  6598. void newBlock()
  6599. {
  6600. blocks.append(*curBlock);
  6601. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6602. }
  6603. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6604. {
  6605. return l.compareTo(&r, compare);
  6606. }
  6607. void makeHeap()
  6608. {
  6609. /* Permute blocks to establish the heap property
  6610. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6611. The children of p must both be greater than or equal to p
  6612. The parent of a child c is given by p = (c-1)/2
  6613. */
  6614. unsigned i;
  6615. unsigned n = blocks.length();
  6616. SortedBlock **s = blocks.getArray();
  6617. for (i=1; i<n; i++)
  6618. {
  6619. SortedBlock * r = s[i];
  6620. int c = i; /* child */
  6621. while (c > 0)
  6622. {
  6623. int p = (c-1)/2; /* parent */
  6624. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6625. break;
  6626. s[c] = s[p];
  6627. s[p] = r;
  6628. c = p;
  6629. }
  6630. }
  6631. }
  6632. void remakeHeap()
  6633. {
  6634. /* The row associated with block[0] will have changed
  6635. This code restores the heap property
  6636. */
  6637. unsigned p = 0; /* parent */
  6638. unsigned n = blocks.length();
  6639. SortedBlock **s = blocks.getArray();
  6640. while (1)
  6641. {
  6642. unsigned c = p*2 + 1; /* child */
  6643. if ( c >= n )
  6644. break;
  6645. /* Select smaller child */
  6646. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6647. /* If child is greater or equal than parent then we are done */
  6648. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6649. break;
  6650. /* Swap parent and child */
  6651. SortedBlock *r = s[c];
  6652. s[c] = s[p];
  6653. s[p] = r;
  6654. /* child becomes parent */
  6655. p = c;
  6656. }
  6657. }
  6658. public:
  6659. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6660. : compare(_compare)
  6661. {
  6662. rowManager = _rowManager;
  6663. activityId = _activityId;
  6664. curBlock = NULL;
  6665. blockNo = 0;
  6666. }
  6667. virtual void reset()
  6668. {
  6669. blocks.kill();
  6670. delete curBlock;
  6671. curBlock = NULL;
  6672. blockNo = 0;
  6673. }
  6674. virtual void prepare(IRoxieInput *input)
  6675. {
  6676. blockNo = 0;
  6677. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6678. loop
  6679. {
  6680. const void *next = input->nextInGroup();
  6681. if (!next)
  6682. break;
  6683. if (!curBlock->insert(next, compare))
  6684. {
  6685. newBlock();
  6686. curBlock->insert(next, compare);
  6687. }
  6688. }
  6689. if (blockNo > 1)
  6690. {
  6691. blocks.append(*curBlock);
  6692. curBlock = NULL;
  6693. makeHeap();
  6694. }
  6695. }
  6696. virtual const void * next()
  6697. {
  6698. const void *ret;
  6699. if (blockNo==1) // single block case..
  6700. {
  6701. ret = curBlock->next();
  6702. }
  6703. else if (blocks.length())
  6704. {
  6705. SortedBlock &top = blocks.item(0);
  6706. ret = top.next();
  6707. if (top.eof())
  6708. blocks.replace(blocks.popGet(), 0);
  6709. remakeHeap();
  6710. }
  6711. else
  6712. ret = NULL;
  6713. return ret;
  6714. }
  6715. };
  6716. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6717. {
  6718. unsigned curIndex;
  6719. ConstPointerArray sorted;
  6720. bool inputAlreadySorted;
  6721. IntArray sequences;
  6722. bool eof;
  6723. ICompare *compare;
  6724. #ifdef _CHECK_HEAPSORT
  6725. void checkHeap() const
  6726. {
  6727. unsigned n = sorted.ordinality();
  6728. if (n)
  6729. {
  6730. ICompare *_compare = compare;
  6731. void **s = sorted.getArray();
  6732. int *sq = sequences.getArray();
  6733. unsigned p;
  6734. #if 0
  6735. CTXLOG("------------------------%d entries-----------------", n);
  6736. for (p = 0; p < n; p++)
  6737. {
  6738. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  6739. }
  6740. #endif
  6741. for (p = 0; p < n; p++)
  6742. {
  6743. unsigned c = p*2+1;
  6744. if (c<n)
  6745. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6746. c++;
  6747. if (c<n)
  6748. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6749. }
  6750. }
  6751. }
  6752. #else
  6753. inline void checkHeap() const {}
  6754. #endif
  6755. const void *removeHeap()
  6756. {
  6757. unsigned n = sorted.ordinality();
  6758. if (n)
  6759. {
  6760. const void *ret = sorted.item(0);
  6761. if (n > 1 && ret)
  6762. {
  6763. ICompare *_compare = compare;
  6764. const void **s = sorted.getArray();
  6765. int *sq = sequences.getArray();
  6766. unsigned v = 0; // vacancy
  6767. loop
  6768. {
  6769. unsigned c = 2*v + 1;
  6770. if (c < n)
  6771. {
  6772. unsigned f = c; // favourite to fill it
  6773. c++;
  6774. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  6775. f = c;
  6776. sq[v] = sq[f];
  6777. if ((s[v] = s[f]) != NULL)
  6778. v = f;
  6779. else
  6780. break;
  6781. }
  6782. else
  6783. {
  6784. s[v] = NULL;
  6785. break;
  6786. }
  6787. }
  6788. }
  6789. checkHeap();
  6790. return ret;
  6791. }
  6792. else
  6793. return NULL;
  6794. }
  6795. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  6796. {
  6797. int rc = _compare->docompare(s[l], s[r]);
  6798. if (!rc)
  6799. rc = sq[l] - sq[r];
  6800. return rc;
  6801. }
  6802. void insertHeap(const void *next)
  6803. {
  6804. // Upside-down heap sort
  6805. // Maintain a heap where every parent is lower than each of its children
  6806. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  6807. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  6808. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  6809. // Nice features:
  6810. // 1. Deterministic
  6811. // 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
  6812. // 3. Already sorted case can be spotted at zero cost while reading.
  6813. // 4. If you don't read all the results, you don't have to complete the sort
  6814. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  6815. unsigned n = sorted.ordinality();
  6816. sorted.append(next);
  6817. sequences.append(n);
  6818. if (!n)
  6819. return;
  6820. ICompare *_compare = compare;
  6821. const void **s = sorted.getArray();
  6822. if (inputAlreadySorted)
  6823. {
  6824. if (_compare->docompare(next, s[n-1]) >= 0)
  6825. return;
  6826. else
  6827. {
  6828. // MORE - could delay creating sequences until now...
  6829. inputAlreadySorted = false;
  6830. }
  6831. }
  6832. int *sq = sequences.getArray();
  6833. unsigned q = n;
  6834. while (n)
  6835. {
  6836. unsigned parent = (n-1) / 2;
  6837. const void *p = s[parent];
  6838. if (_compare->docompare(p, next) <= 0)
  6839. break;
  6840. s[n] = p;
  6841. sq[n] = sq[parent];
  6842. s[parent] = next;
  6843. sq[parent] = q;
  6844. n = parent;
  6845. }
  6846. }
  6847. public:
  6848. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  6849. {
  6850. inputAlreadySorted = true;
  6851. curIndex = 0;
  6852. eof = false;
  6853. }
  6854. virtual void reset()
  6855. {
  6856. eof = false;
  6857. if (inputAlreadySorted)
  6858. {
  6859. while (sorted.isItem(curIndex))
  6860. ReleaseRoxieRow(sorted.item(curIndex++));
  6861. sorted.kill();
  6862. }
  6863. else
  6864. {
  6865. ReleaseRoxieRowSet(sorted);
  6866. }
  6867. inputAlreadySorted = true;
  6868. sequences.kill();
  6869. }
  6870. virtual void prepare(IRoxieInput *input)
  6871. {
  6872. inputAlreadySorted = true;
  6873. curIndex = 0;
  6874. eof = false;
  6875. assertex(sorted.ordinality()==0);
  6876. const void *next = input->nextInGroup();
  6877. if (!next)
  6878. {
  6879. eof = true;
  6880. return;
  6881. }
  6882. loop
  6883. {
  6884. insertHeap(next);
  6885. next = input->nextInGroup();
  6886. if (!next)
  6887. break;
  6888. }
  6889. checkHeap();
  6890. }
  6891. virtual const void * next()
  6892. {
  6893. if (inputAlreadySorted)
  6894. {
  6895. if (sorted.isItem(curIndex))
  6896. {
  6897. return sorted.item(curIndex++);
  6898. }
  6899. else
  6900. return NULL;
  6901. }
  6902. else
  6903. return removeHeap();
  6904. }
  6905. };
  6906. typedef enum {heapSort, insertionSort, quickSort, spillingQuickSort, unknownSort } RoxieSortAlgorithm;
  6907. class CRoxieServerSortActivity : public CRoxieServerActivity
  6908. {
  6909. protected:
  6910. IHThorSortArg &helper;
  6911. ICompare *compare;
  6912. Owned<ISortAlgorithm> sorter;
  6913. bool readInput;
  6914. RoxieSortAlgorithm sortAlgorithm;
  6915. unsigned sortFlags;
  6916. public:
  6917. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  6918. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  6919. {
  6920. compare = helper.queryCompare();
  6921. readInput = false;
  6922. }
  6923. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  6924. {
  6925. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  6926. switch (sortAlgorithm)
  6927. {
  6928. case heapSort:
  6929. sorter.setown(new CHeapSortAlgorithm(compare));
  6930. break;
  6931. case insertionSort:
  6932. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  6933. break;
  6934. case quickSort:
  6935. sorter.setown(new CQuickSortAlgorithm(compare));
  6936. break;
  6937. case spillingQuickSort:
  6938. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId));
  6939. break;
  6940. case unknownSort:
  6941. sorter.clear(); // create it later....
  6942. break;
  6943. default:
  6944. throwUnexpected();
  6945. break;
  6946. }
  6947. }
  6948. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6949. {
  6950. assertex(!readInput);
  6951. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6952. }
  6953. virtual void reset()
  6954. {
  6955. if (sorter)
  6956. sorter->reset();
  6957. readInput = false;
  6958. CRoxieServerActivity::reset();
  6959. }
  6960. virtual const void * nextInGroup()
  6961. {
  6962. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6963. if (!readInput)
  6964. {
  6965. if (sortAlgorithm == unknownSort)
  6966. {
  6967. sorter.clear();
  6968. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  6969. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  6970. if (useAlgorithm)
  6971. {
  6972. if (stricmp(useAlgorithm, "quicksort")==0)
  6973. {
  6974. if (sortFlags & TAFstable)
  6975. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  6976. sorter.setown(new CQuickSortAlgorithm(compare));
  6977. }
  6978. else if (stricmp(useAlgorithm, "heapsort")==0)
  6979. sorter.setown(new CHeapSortAlgorithm(compare));
  6980. else if (stricmp(useAlgorithm, "insertionsort")==0)
  6981. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  6982. else
  6983. {
  6984. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  6985. if (sortFlags & TAFunstable)
  6986. sorter.setown(new CQuickSortAlgorithm(compare));
  6987. else
  6988. sorter.setown(new CHeapSortAlgorithm(compare));
  6989. }
  6990. }
  6991. else
  6992. 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...
  6993. }
  6994. sorter->prepare(input);
  6995. readInput = true;
  6996. }
  6997. const void *ret = sorter->next();
  6998. if (ret)
  6999. processed++;
  7000. else
  7001. {
  7002. sorter->reset();
  7003. readInput = false; // ready for next group
  7004. }
  7005. return ret;
  7006. }
  7007. };
  7008. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7009. {
  7010. RoxieSortAlgorithm sortAlgorithm;
  7011. unsigned sortFlags;
  7012. public:
  7013. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7014. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7015. {
  7016. sortAlgorithm = heapSort;
  7017. sortFlags = TAFstable;
  7018. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7019. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7020. if (sortMethod)
  7021. {
  7022. sortFlags = sortMethod->getAlgorithmFlags();
  7023. if (sortFlags & TAFunstable)
  7024. sortAlgorithm = quickSort;
  7025. if (!(sortFlags & TAFconstant))
  7026. sortAlgorithm = unknownSort;
  7027. else
  7028. {
  7029. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7030. if (useAlgorithm)
  7031. {
  7032. if (stricmp(useAlgorithm, "quicksort")==0)
  7033. {
  7034. if (sortFlags & TAFstable)
  7035. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7036. sortAlgorithm = quickSort;
  7037. }
  7038. else if (stricmp(useAlgorithm, "spillingquicksort")==0)
  7039. {
  7040. if (sortFlags & TAFstable)
  7041. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7042. sortAlgorithm = spillingQuickSort;
  7043. }
  7044. else if (stricmp(useAlgorithm, "heapsort")==0)
  7045. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection
  7046. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7047. sortAlgorithm = insertionSort;
  7048. else
  7049. {
  7050. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7051. if (sortFlags & TAFunstable)
  7052. sortAlgorithm = quickSort;
  7053. else
  7054. sortAlgorithm = heapSort;
  7055. }
  7056. }
  7057. }
  7058. }
  7059. }
  7060. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7061. {
  7062. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7063. }
  7064. };
  7065. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7066. {
  7067. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7068. }
  7069. //=====================================================================================================
  7070. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7071. {
  7072. IHThorSortedArg &helper;
  7073. ICompare * compare;
  7074. const void *prev;
  7075. IRangeCompare * stepCompare;
  7076. public:
  7077. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7078. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7079. {
  7080. prev = NULL;
  7081. compare = helper.queryCompare();
  7082. stepCompare = NULL;
  7083. }
  7084. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7085. {
  7086. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7087. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7088. if (stepMeta)
  7089. stepCompare = stepMeta->queryCompare();
  7090. prev = NULL;
  7091. }
  7092. virtual void reset()
  7093. {
  7094. ReleaseClearRoxieRow(prev);
  7095. CRoxieServerActivity::reset();
  7096. }
  7097. virtual const void * nextInGroup()
  7098. {
  7099. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7100. const void *ret = input->nextInGroup();
  7101. if (ret && prev && compare->docompare(prev, ret) > 0)
  7102. {
  7103. // MORE - better to give mismatching rows that indexes?
  7104. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7105. }
  7106. ReleaseRoxieRow(prev);
  7107. prev = ret;
  7108. if (ret)
  7109. {
  7110. LinkRoxieRow(prev);
  7111. processed++;
  7112. }
  7113. return ret;
  7114. }
  7115. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7116. {
  7117. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7118. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7119. if (ret && prev && compare->docompare(prev, ret) > 0)
  7120. {
  7121. // MORE - better to give mismatching rows that indexes?
  7122. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7123. }
  7124. ReleaseRoxieRow(prev);
  7125. prev = ret;
  7126. if (ret)
  7127. {
  7128. LinkRoxieRow(prev);
  7129. processed++;
  7130. }
  7131. return ret;
  7132. }
  7133. IInputSteppingMeta * querySteppingMeta()
  7134. {
  7135. return input->querySteppingMeta();
  7136. }
  7137. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7138. {
  7139. return input->gatherConjunctions(collector);
  7140. }
  7141. virtual void resetEOF()
  7142. {
  7143. input->resetEOF();
  7144. }
  7145. };
  7146. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7147. {
  7148. public:
  7149. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7150. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7151. {
  7152. }
  7153. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7154. {
  7155. return new CRoxieServerSortedActivity(this, _probeManager);
  7156. }
  7157. };
  7158. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7159. {
  7160. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7161. }
  7162. //=====================================================================================================
  7163. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7164. {
  7165. /*
  7166. BE VERY CAREFUL - this code is tricky.
  7167. Note that starts and stops (and resets) can occur in strange orders
  7168. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7169. The last stop should call the upstream stop.
  7170. The first reset should call the upstream reset.
  7171. 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
  7172. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7173. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7174. ignored in the minIndex calculation
  7175. */
  7176. public:
  7177. IHThorArg &helper;
  7178. unsigned activeOutputs;
  7179. unsigned numOutputs;
  7180. unsigned numOriginalOutputs;
  7181. QueueOf<const void, true> buffer;
  7182. CriticalSection crit;
  7183. CriticalSection crit2;
  7184. unsigned tailIdx;
  7185. unsigned headIdx;
  7186. Owned<IException> error;
  7187. class OutputAdaptor : public CInterface, implements IRoxieInput
  7188. {
  7189. bool eof, eofpending, stopped;
  7190. public:
  7191. CRoxieServerThroughSpillActivity *parent;
  7192. unsigned idx;
  7193. unsigned oid;
  7194. unsigned processed;
  7195. unsigned __int64 totalCycles;
  7196. public:
  7197. IMPLEMENT_IINTERFACE;
  7198. OutputAdaptor()
  7199. {
  7200. parent = NULL;
  7201. oid = 0;
  7202. idx = 0;
  7203. processed = 0;
  7204. totalCycles = 0;
  7205. eofpending = false;
  7206. eof = false;
  7207. stopped = false;
  7208. }
  7209. ~OutputAdaptor()
  7210. {
  7211. if (traceStartStop)
  7212. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7213. }
  7214. void init()
  7215. {
  7216. if (traceStartStop)
  7217. DBGLOG("%p init Input adaptor %d", this, oid);
  7218. idx = 0;
  7219. processed = 0;
  7220. totalCycles = 0;
  7221. eofpending = false;
  7222. eof = false;
  7223. stopped = false;
  7224. }
  7225. virtual unsigned queryId() const
  7226. {
  7227. return parent->queryId();
  7228. }
  7229. virtual IRoxieServerActivity *queryActivity()
  7230. {
  7231. return parent;
  7232. }
  7233. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7234. {
  7235. return parent->queryIndexReadActivity();
  7236. }
  7237. virtual unsigned __int64 queryTotalCycles() const
  7238. {
  7239. return totalCycles;
  7240. }
  7241. virtual unsigned __int64 queryLocalCycles() const
  7242. {
  7243. return 0;
  7244. }
  7245. virtual IRoxieInput *queryInput(unsigned idx) const
  7246. {
  7247. return parent->queryInput(idx);
  7248. }
  7249. virtual const void * nextInGroup()
  7250. {
  7251. ActivityTimer t(totalCycles, timeActivities, parent->ctx->queryDebugContext());
  7252. if (eof)
  7253. return NULL;
  7254. const void *ret = parent->readBuffered(idx, oid);
  7255. #ifdef TRACE_SPLIT
  7256. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7257. #endif
  7258. idx++;
  7259. if (ret)
  7260. {
  7261. processed++;
  7262. eofpending = false;
  7263. }
  7264. else if (eofpending)
  7265. eof = true;
  7266. else
  7267. eofpending = true;
  7268. return ret;
  7269. }
  7270. virtual IOutputMetaData * queryOutputMeta() const
  7271. {
  7272. return parent->queryOutputMeta();
  7273. }
  7274. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7275. {
  7276. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7277. // since adaptors that have not yet started or stoppped (but are going to) still need to have been init()'ed
  7278. // for minIndex to give the correct answers
  7279. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7280. if (traceStartStop)
  7281. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7282. parent->start(oid, parentExtractSize, parentExtract, paused);
  7283. }
  7284. virtual void stop(bool aborting)
  7285. {
  7286. if (traceStartStop)
  7287. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7288. if (!stopped)
  7289. {
  7290. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7291. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7292. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7293. }
  7294. };
  7295. virtual void reset()
  7296. {
  7297. if (traceStartStop)
  7298. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7299. parent->reset(oid, processed);
  7300. processed = 0;
  7301. idx = 0; // value should not be relevant really but this is the safest...
  7302. stopped = false;
  7303. };
  7304. virtual void resetEOF()
  7305. {
  7306. parent->resetEOF();
  7307. }
  7308. virtual void checkAbort()
  7309. {
  7310. parent->checkAbort();
  7311. }
  7312. } *adaptors;
  7313. bool *used;
  7314. unsigned nextFreeOutput()
  7315. {
  7316. unsigned i = numOutputs;
  7317. while (i)
  7318. {
  7319. i--;
  7320. if (!used[i])
  7321. return i;
  7322. }
  7323. throwUnexpected();
  7324. }
  7325. unsigned minIndex(unsigned exceptOid)
  7326. {
  7327. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7328. // this is trying to determine whethwe any of the adaptors will in the future read a given record
  7329. unsigned minIdx = (unsigned) -1;
  7330. for (unsigned i = 0; i < numOutputs; i++)
  7331. {
  7332. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7333. minIdx = adaptors[i].idx;
  7334. }
  7335. return minIdx;
  7336. }
  7337. void initOutputs()
  7338. {
  7339. activeOutputs = numOutputs;
  7340. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7341. if (used[i])
  7342. adaptors[i].init();
  7343. state = STATEstarting;
  7344. }
  7345. public:
  7346. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7347. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7348. {
  7349. numOriginalOutputs = numOutputs;
  7350. adaptors = new OutputAdaptor[numOutputs];
  7351. used = new bool[numOutputs];
  7352. for (unsigned i = 0; i < numOutputs; i++)
  7353. {
  7354. adaptors[i].parent = this;
  7355. adaptors[i].oid = i;
  7356. used[i] = false;
  7357. }
  7358. tailIdx = 0;
  7359. headIdx = 0;
  7360. activeOutputs = numOutputs;
  7361. }
  7362. ~CRoxieServerThroughSpillActivity()
  7363. {
  7364. delete [] adaptors;
  7365. delete [] used;
  7366. }
  7367. const void *readBuffered(unsigned idx, unsigned oid)
  7368. {
  7369. CriticalBlock b(crit);
  7370. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // NOTE - time spent waiting for crit not included here. Is that right?
  7371. if (idx == headIdx) // test once without getting the crit2 sec
  7372. {
  7373. CriticalUnblock b1(crit);
  7374. CriticalBlock b2(crit2);
  7375. if (error)
  7376. {
  7377. throw error.getLink();
  7378. }
  7379. if (idx == headIdx) // test again now that we have it
  7380. {
  7381. try
  7382. {
  7383. const void *row = input->nextInGroup();
  7384. CriticalBlock b3(crit);
  7385. headIdx++;
  7386. if (row) processed++;
  7387. if (activeOutputs==1)
  7388. {
  7389. #ifdef TRACE_SPLIT
  7390. CTXLOG("spill %d optimised return of %p", activityId, row);
  7391. #endif
  7392. return row; // optimization for the case where only one output still active.
  7393. }
  7394. buffer.enqueue(row);
  7395. }
  7396. catch (IException *E)
  7397. {
  7398. #ifdef TRACE_SPLIT
  7399. CTXLOG("spill %d caught exception", activityId);
  7400. #endif
  7401. error.set(E);
  7402. throw;
  7403. }
  7404. catch (...)
  7405. {
  7406. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7407. error.set(E);
  7408. throw E;
  7409. }
  7410. }
  7411. }
  7412. idx -= tailIdx;
  7413. if (!idx)
  7414. {
  7415. unsigned min = minIndex(oid);
  7416. if (min > tailIdx)
  7417. {
  7418. tailIdx++;
  7419. const void *ret = buffer.dequeue(); // no need to link - last puller
  7420. #ifdef TRACE_SPLIT
  7421. CTXLOG("last puller return of %p", ret);
  7422. #endif
  7423. return ret;
  7424. }
  7425. }
  7426. const void *ret = buffer.item(idx);
  7427. if (ret) LinkRoxieRow(ret);
  7428. #ifdef TRACE_SPLIT
  7429. CTXLOG("standard return of %p", ret);
  7430. #endif
  7431. return ret;
  7432. }
  7433. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7434. {
  7435. CriticalBlock b(crit);
  7436. if (error)
  7437. throw error.getLink();
  7438. if (factory)
  7439. factory->noteStarted(oid);
  7440. if (traceStartStop)
  7441. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7442. if (state != STATEstarted)
  7443. {
  7444. if (state != STATEstarting)
  7445. initOutputs();
  7446. tailIdx = 0;
  7447. headIdx = 0;
  7448. error.clear();
  7449. try
  7450. {
  7451. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7452. }
  7453. catch (IException *E)
  7454. {
  7455. #ifdef TRACE_SPLIT
  7456. CTXLOG("spill %d caught exception in start", activityId);
  7457. #endif
  7458. error.set(E);
  7459. throw;
  7460. }
  7461. catch (...)
  7462. {
  7463. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7464. error.set(E);
  7465. throw E;
  7466. }
  7467. }
  7468. }
  7469. void stop(unsigned oid, unsigned idx, bool aborting)
  7470. {
  7471. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7472. CriticalBlock b(crit);
  7473. #ifdef TRACE_STARTSTOP
  7474. if (traceStartStop)
  7475. {
  7476. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7477. if (watchActivityId && watchActivityId==activityId)
  7478. {
  7479. CTXLOG("WATCH: stop %d", activityId);
  7480. }
  7481. }
  7482. #endif
  7483. if (state != STATEstarting && state != STATEstarted)
  7484. initOutputs();
  7485. if (activeOutputs > 1)
  7486. {
  7487. if (tailIdx==idx)
  7488. {
  7489. // Discard all buffered rows that are there purely for this adaptor to read them
  7490. unsigned min = minIndex(oid);
  7491. if (min != (unsigned) -1)
  7492. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7493. // Should never happen though if there are still some active.
  7494. // there may be a small window where adaptors are blocked on the semaphore...
  7495. {
  7496. #ifdef TRACE_SPLIT
  7497. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7498. #endif
  7499. while (tailIdx < min)
  7500. {
  7501. ReleaseRoxieRow(buffer.dequeue());
  7502. tailIdx++;
  7503. }
  7504. }
  7505. }
  7506. activeOutputs--;
  7507. return;
  7508. }
  7509. #ifdef TRACE_SPLIT
  7510. CTXLOG("%p: All outputs done", this);
  7511. #endif
  7512. activeOutputs = numOutputs;
  7513. CRoxieServerActivity::stop(aborting);
  7514. };
  7515. void reset(unsigned oid, unsigned _processed)
  7516. {
  7517. if (traceStartStop)
  7518. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7519. activeOutputs = numOutputs;
  7520. while (buffer.ordinality())
  7521. ReleaseRoxieRow(buffer.dequeue());
  7522. error.clear();
  7523. if (state != STATEreset) // make sure input is only reset once
  7524. CRoxieServerActivity::reset();
  7525. };
  7526. virtual unsigned __int64 queryLocalCycles() const
  7527. {
  7528. return 0;
  7529. }
  7530. virtual const void *nextInGroup()
  7531. {
  7532. throwUnexpected(); // Internal logic error - we are not anybody's input
  7533. }
  7534. virtual IOutputMetaData * queryOutputMeta() const
  7535. {
  7536. // if (outputMeta)
  7537. // return outputMeta;
  7538. // else
  7539. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7540. }
  7541. virtual IRoxieInput *queryOutput(unsigned idx)
  7542. {
  7543. if (idx==(unsigned)-1)
  7544. idx = nextFreeOutput(); // MORE - what is this used for?
  7545. assertex(idx < numOriginalOutputs);
  7546. assertex(!used[idx]);
  7547. used[idx] = true;
  7548. return &adaptors[idx];
  7549. }
  7550. virtual void resetOutputsUsed()
  7551. {
  7552. numOutputs = 1;
  7553. activeOutputs = 1;
  7554. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7555. }
  7556. virtual void noteOutputUsed()
  7557. {
  7558. assertex(numOutputs < numOriginalOutputs);
  7559. numOutputs++;
  7560. activeOutputs = numOutputs;
  7561. }
  7562. virtual bool isPassThrough()
  7563. {
  7564. return numOutputs==1;
  7565. }
  7566. };
  7567. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7568. {
  7569. public:
  7570. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7571. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7572. {
  7573. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7574. setNumOutputs(helper->getTempUsageCount() + 1);
  7575. }
  7576. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7577. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7578. {
  7579. setNumOutputs(_numOutputs);
  7580. }
  7581. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7582. {
  7583. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7584. }
  7585. };
  7586. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7587. {
  7588. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7589. }
  7590. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7591. {
  7592. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7593. }
  7594. //----------------------------------------------------------------------------------------------
  7595. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7596. {
  7597. public:
  7598. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7599. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7600. {
  7601. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7602. setNumOutputs(helper->numBranches());
  7603. }
  7604. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7605. {
  7606. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7607. }
  7608. };
  7609. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7610. {
  7611. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7612. }
  7613. //=====================================================================================================
  7614. #define PIPE_BUFSIZE 0x8000
  7615. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7616. {
  7617. StringBuffer msg;
  7618. if(pipe->hasError())
  7619. {
  7620. try
  7621. {
  7622. char error[512];
  7623. size32_t sz = pipe->readError(sizeof(error), error);
  7624. if(sz && sz!=(size32_t)-1)
  7625. msg.append(", stderr: '").append(sz, error).append("'");
  7626. }
  7627. catch (IException *e)
  7628. {
  7629. EXCLOG(e, "Error reading pipe stderr");
  7630. e->Release();
  7631. }
  7632. }
  7633. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7634. }
  7635. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7636. {
  7637. IHThorPipeReadArg &helper;
  7638. Owned<IPipeProcess> pipe;
  7639. StringAttr pipeCommand;
  7640. Owned<IOutputRowDeserializer> rowDeserializer;
  7641. Owned<IReadRowStream> readTransformer;
  7642. bool groupSignalled;
  7643. public:
  7644. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7645. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7646. {
  7647. groupSignalled = true;
  7648. }
  7649. virtual bool needsAllocator() const { return true; }
  7650. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7651. {
  7652. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7653. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7654. }
  7655. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7656. {
  7657. groupSignalled = true; // i.e. don't start with a NULL row
  7658. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7659. if (!readTransformer)
  7660. {
  7661. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7662. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7663. }
  7664. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7665. openPipe(pipeProgram);
  7666. }
  7667. virtual void stop(bool aborting)
  7668. {
  7669. CRoxieServerActivity::stop(aborting);
  7670. pipe.clear();
  7671. readTransformer->setStream(NULL);
  7672. }
  7673. virtual const void *nextInGroup()
  7674. {
  7675. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7676. while (!waitForPipe())
  7677. {
  7678. if (!pipe)
  7679. return NULL;
  7680. if (helper.getPipeFlags() & TPFgroupeachrow)
  7681. {
  7682. if (!groupSignalled)
  7683. {
  7684. groupSignalled = true;
  7685. return NULL;
  7686. }
  7687. }
  7688. }
  7689. const void *ret = readTransformer->next();
  7690. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7691. processed++;
  7692. groupSignalled = false;
  7693. return ret;
  7694. }
  7695. protected:
  7696. bool waitForPipe()
  7697. {
  7698. if (!pipe)
  7699. return false; // done
  7700. if (!readTransformer->eos())
  7701. return true;
  7702. verifyPipe();
  7703. return false;
  7704. }
  7705. void openPipe(char const * cmd)
  7706. {
  7707. pipeCommand.setown(cmd);
  7708. pipe.setown(createPipeProcess());
  7709. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  7710. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7711. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  7712. readTransformer->setStream(pipeReader.get());
  7713. }
  7714. void verifyPipe()
  7715. {
  7716. if (pipe)
  7717. {
  7718. unsigned err = pipe->wait();
  7719. if(err && !(helper.getPipeFlags() & TPFnofail))
  7720. {
  7721. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7722. }
  7723. pipe.clear();
  7724. }
  7725. }
  7726. };
  7727. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  7728. {
  7729. IHThorPipeThroughArg &helper;
  7730. RecordPullerThread puller;
  7731. Owned<IPipeProcess> pipe;
  7732. StringAttr pipeCommand;
  7733. InterruptableSemaphore pipeVerified;
  7734. InterruptableSemaphore pipeOpened;
  7735. CachedOutputMetaData inputMeta;
  7736. Owned<IOutputRowSerializer> rowSerializer;
  7737. Owned<IOutputRowDeserializer> rowDeserializer;
  7738. Owned<IPipeWriteXformHelper> writeTransformer;
  7739. Owned<IReadRowStream> readTransformer;
  7740. bool firstRead;
  7741. bool recreate;
  7742. bool inputExhausted;
  7743. bool groupSignalled;
  7744. public:
  7745. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7746. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  7747. {
  7748. recreate = helper.recreateEachRow();
  7749. groupSignalled = true;
  7750. firstRead = false;
  7751. inputExhausted = false;
  7752. }
  7753. virtual bool needsAllocator() const { return true; }
  7754. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7755. {
  7756. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7757. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  7758. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7759. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  7760. }
  7761. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7762. {
  7763. firstRead = true;
  7764. inputExhausted = false;
  7765. groupSignalled = true; // i.e. don't start with a NULL row
  7766. pipeVerified.reinit();
  7767. pipeOpened.reinit();
  7768. writeTransformer->ready();
  7769. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7770. if (!readTransformer)
  7771. {
  7772. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  7773. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  7774. }
  7775. if(!recreate)
  7776. {
  7777. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7778. openPipe(pipeProgram);
  7779. }
  7780. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  7781. }
  7782. virtual void setInput(unsigned idx, IRoxieInput *_in)
  7783. {
  7784. if (idx)
  7785. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  7786. puller.setInput(this, _in);
  7787. inputMeta.set(_in->queryOutputMeta());
  7788. }
  7789. virtual void stop(bool aborting)
  7790. {
  7791. pipeVerified.interrupt(NULL);
  7792. pipeOpened.interrupt(NULL);
  7793. puller.stop(aborting);
  7794. CRoxieServerActivity::stop(aborting);
  7795. pipe.clear();
  7796. readTransformer->setStream(NULL);
  7797. }
  7798. virtual void reset()
  7799. {
  7800. puller.reset();
  7801. CRoxieServerActivity::reset();
  7802. }
  7803. virtual const void *nextInGroup()
  7804. {
  7805. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7806. while (!waitForPipe())
  7807. {
  7808. if (!pipe)
  7809. return NULL;
  7810. if (helper.getPipeFlags() & TPFgroupeachrow)
  7811. {
  7812. if (!groupSignalled)
  7813. {
  7814. groupSignalled = true;
  7815. return NULL;
  7816. }
  7817. }
  7818. }
  7819. const void *ret = readTransformer->next();
  7820. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7821. processed++;
  7822. groupSignalled = false;
  7823. return ret;
  7824. }
  7825. virtual void processRow(const void *row)
  7826. {
  7827. // called from puller thread
  7828. if(recreate)
  7829. openPipe(helper.getNameFromRow(row));
  7830. writeTransformer->writeTranslatedText(row, pipe);
  7831. ReleaseRoxieRow(row);
  7832. if(recreate)
  7833. {
  7834. closePipe();
  7835. pipeVerified.wait();
  7836. }
  7837. }
  7838. virtual void processDone()
  7839. {
  7840. // called from puller thread
  7841. if(recreate)
  7842. {
  7843. inputExhausted = true;
  7844. pipeOpened.signal();
  7845. }
  7846. else
  7847. {
  7848. closePipe();
  7849. pipeVerified.wait();
  7850. }
  7851. }
  7852. virtual void processEOG()
  7853. {
  7854. }
  7855. void processGroup(const ConstPointerArray &)
  7856. {
  7857. throwUnexpected();
  7858. }
  7859. virtual bool fireException(IException *e)
  7860. {
  7861. pipeOpened.interrupt(LINK(e));
  7862. pipeVerified.interrupt(e);
  7863. return true;
  7864. }
  7865. private:
  7866. bool waitForPipe()
  7867. {
  7868. if (firstRead)
  7869. {
  7870. pipeOpened.wait();
  7871. firstRead = false;
  7872. }
  7873. if (!pipe)
  7874. return false; // done
  7875. if (!readTransformer->eos())
  7876. return true;
  7877. verifyPipe();
  7878. if (recreate && !inputExhausted)
  7879. pipeOpened.wait();
  7880. return false;
  7881. }
  7882. void openPipe(char const * cmd)
  7883. {
  7884. pipeCommand.setown(cmd);
  7885. pipe.setown(createPipeProcess());
  7886. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  7887. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7888. writeTransformer->writeHeader(pipe);
  7889. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  7890. readTransformer->setStream(pipeReader.get());
  7891. pipeOpened.signal();
  7892. }
  7893. void closePipe()
  7894. {
  7895. writeTransformer->writeFooter(pipe);
  7896. pipe->closeInput();
  7897. }
  7898. void verifyPipe()
  7899. {
  7900. if (pipe)
  7901. {
  7902. unsigned err = pipe->wait();
  7903. if(err && !(helper.getPipeFlags() & TPFnofail))
  7904. {
  7905. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7906. }
  7907. pipe.clear();
  7908. pipeVerified.signal();
  7909. }
  7910. }
  7911. };
  7912. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  7913. {
  7914. IHThorPipeWriteArg &helper;
  7915. Owned<IPipeProcess> pipe;
  7916. StringAttr pipeCommand;
  7917. CachedOutputMetaData inputMeta;
  7918. Owned<IOutputRowSerializer> rowSerializer;
  7919. Owned<IPipeWriteXformHelper> writeTransformer;
  7920. bool firstRead;
  7921. bool recreate;
  7922. bool inputExhausted;
  7923. public:
  7924. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7925. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorPipeWriteArg &)basehelper)
  7926. {
  7927. recreate = helper.recreateEachRow();
  7928. firstRead = false;
  7929. inputExhausted = false;
  7930. }
  7931. virtual bool needsAllocator() const { return true; }
  7932. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7933. {
  7934. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7935. inputMeta.set(input->queryOutputMeta());
  7936. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  7937. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  7938. }
  7939. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7940. {
  7941. firstRead = true;
  7942. inputExhausted = false;
  7943. writeTransformer->ready();
  7944. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7945. if(!recreate)
  7946. {
  7947. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7948. openPipe(pipeProgram);
  7949. }
  7950. }
  7951. virtual void stop(bool aborting)
  7952. {
  7953. CRoxieServerActivity::stop(aborting);
  7954. pipe.clear();
  7955. }
  7956. virtual void onExecute()
  7957. {
  7958. loop
  7959. {
  7960. const void *row = input->nextInGroup();
  7961. if (!row)
  7962. {
  7963. row = input->nextInGroup();
  7964. if (!row)
  7965. break;
  7966. }
  7967. processed++;
  7968. if(recreate)
  7969. openPipe(helper.getNameFromRow(row));
  7970. writeTransformer->writeTranslatedText(row, pipe);
  7971. ReleaseRoxieRow(row);
  7972. if(recreate)
  7973. closePipe();
  7974. }
  7975. closePipe();
  7976. }
  7977. private:
  7978. void openPipe(char const * cmd)
  7979. {
  7980. pipeCommand.setown(cmd);
  7981. pipe.setown(createPipeProcess());
  7982. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  7983. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7984. writeTransformer->writeHeader(pipe);
  7985. }
  7986. void closePipe()
  7987. {
  7988. writeTransformer->writeFooter(pipe);
  7989. pipe->closeInput();
  7990. unsigned err = pipe->wait();
  7991. if(err && !(helper.getPipeFlags() & TPFnofail))
  7992. {
  7993. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7994. }
  7995. pipe.clear();
  7996. }
  7997. };
  7998. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  7999. {
  8000. public:
  8001. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8002. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8003. {
  8004. }
  8005. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8006. {
  8007. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8008. }
  8009. };
  8010. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8011. {
  8012. public:
  8013. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8014. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8015. {
  8016. }
  8017. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8018. {
  8019. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8020. }
  8021. };
  8022. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8023. {
  8024. public:
  8025. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8026. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8027. {
  8028. }
  8029. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8030. {
  8031. return new CRoxieServerPipeWriteActivity(this, _probeManager);
  8032. }
  8033. };
  8034. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8035. {
  8036. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8037. }
  8038. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8039. {
  8040. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8041. }
  8042. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8043. {
  8044. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8045. }
  8046. //=====================================================================================================
  8047. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8048. {
  8049. IHThorStreamedIteratorArg &helper;
  8050. Owned<IRowStream> rows;
  8051. public:
  8052. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8053. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8054. {
  8055. }
  8056. ~CRoxieServerStreamedIteratorActivity()
  8057. {
  8058. }
  8059. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8060. {
  8061. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8062. rows.setown(helper.createInput());
  8063. }
  8064. virtual void stop(bool aborting)
  8065. {
  8066. if (rows)
  8067. {
  8068. rows->stop();
  8069. rows.clear();
  8070. }
  8071. CRoxieServerActivity::stop(aborting);
  8072. }
  8073. virtual const void *nextInGroup()
  8074. {
  8075. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8076. assertex(rows != NULL);
  8077. const void * next = rows->nextRow();
  8078. if (next)
  8079. processed++;
  8080. return next;
  8081. }
  8082. };
  8083. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8084. {
  8085. public:
  8086. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8087. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8088. {
  8089. }
  8090. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8091. {
  8092. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8093. }
  8094. };
  8095. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8096. {
  8097. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8098. }
  8099. //=====================================================================================================
  8100. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8101. {
  8102. IHThorFilterArg &helper;
  8103. bool anyThisGroup;
  8104. IRangeCompare * stepCompare;
  8105. public:
  8106. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8107. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8108. {
  8109. anyThisGroup = false;
  8110. stepCompare = NULL;
  8111. }
  8112. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8113. {
  8114. anyThisGroup = false;
  8115. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8116. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8117. stepCompare = NULL;
  8118. if (!eof)
  8119. {
  8120. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8121. if (stepMeta)
  8122. stepCompare = stepMeta->queryCompare();
  8123. }
  8124. }
  8125. virtual const void * nextInGroup()
  8126. {
  8127. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8128. if (eof)
  8129. return NULL;
  8130. loop
  8131. {
  8132. const void * ret = input->nextInGroup();
  8133. if (!ret)
  8134. {
  8135. //stop returning two NULLs in a row.
  8136. if (anyThisGroup)
  8137. {
  8138. anyThisGroup = false;
  8139. return NULL;
  8140. }
  8141. ret = input->nextInGroup();
  8142. if (!ret)
  8143. {
  8144. eof = true;
  8145. return NULL; // eof...
  8146. }
  8147. }
  8148. if (helper.isValid(ret))
  8149. {
  8150. anyThisGroup = true;
  8151. processed++;
  8152. return ret;
  8153. }
  8154. ReleaseRoxieRow(ret);
  8155. }
  8156. }
  8157. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8158. {
  8159. //Could assert that this isn't grouped
  8160. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8161. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8162. if (eof)
  8163. return NULL;
  8164. loop
  8165. {
  8166. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8167. if (!ret)
  8168. {
  8169. eof = true;
  8170. return NULL;
  8171. }
  8172. if (!wasCompleteMatch)
  8173. {
  8174. anyThisGroup = false; // RKC->GH - is this right??
  8175. return ret;
  8176. }
  8177. if (helper.isValid(ret))
  8178. {
  8179. anyThisGroup = true;
  8180. processed++;
  8181. return ret;
  8182. }
  8183. if (!stepExtra.returnMismatches())
  8184. {
  8185. ReleaseRoxieRow(ret);
  8186. return nextInGroup();
  8187. }
  8188. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8189. {
  8190. wasCompleteMatch = false;
  8191. anyThisGroup = false; // WHY?
  8192. return ret;
  8193. }
  8194. ReleaseRoxieRow(ret);
  8195. }
  8196. }
  8197. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8198. {
  8199. return input->gatherConjunctions(collector);
  8200. }
  8201. virtual void resetEOF()
  8202. {
  8203. eof = prefiltered;
  8204. anyThisGroup = false;
  8205. input->resetEOF();
  8206. }
  8207. IInputSteppingMeta * querySteppingMeta()
  8208. {
  8209. return input->querySteppingMeta();
  8210. }
  8211. };
  8212. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8213. {
  8214. public:
  8215. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8216. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8217. {
  8218. }
  8219. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8220. {
  8221. return new CRoxieServerFilterActivity(this, _probeManager);
  8222. }
  8223. };
  8224. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8225. {
  8226. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8227. }
  8228. //=====================================================================================================
  8229. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8230. {
  8231. IHThorFilterGroupArg &helper;
  8232. unsigned curIndex;
  8233. ConstPointerArray gathered;
  8234. IRangeCompare * stepCompare;
  8235. public:
  8236. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8237. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8238. {
  8239. curIndex = 0;
  8240. stepCompare = NULL;
  8241. }
  8242. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8243. {
  8244. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8245. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8246. assertex(eof == !helper.canMatchAny());
  8247. curIndex = 0;
  8248. stepCompare = NULL;
  8249. if (!eof)
  8250. {
  8251. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8252. if (inputStepping)
  8253. stepCompare = inputStepping->queryCompare();
  8254. }
  8255. }
  8256. virtual void reset()
  8257. {
  8258. releaseGathered();
  8259. CRoxieServerLateStartActivity::reset();
  8260. }
  8261. inline void releaseGathered()
  8262. {
  8263. while (gathered.isItem(curIndex))
  8264. ReleaseRoxieRow(gathered.item(curIndex++));
  8265. gathered.kill();
  8266. }
  8267. virtual const void * nextInGroup()
  8268. {
  8269. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8270. loop
  8271. {
  8272. if (eof)
  8273. return NULL;
  8274. if (gathered.ordinality())
  8275. {
  8276. if (gathered.isItem(curIndex))
  8277. {
  8278. const void * ret = gathered.item(curIndex++);
  8279. processed++;
  8280. return ret;
  8281. }
  8282. curIndex = 0;
  8283. gathered.kill();
  8284. return NULL;
  8285. }
  8286. const void * ret = input->nextInGroup();
  8287. while (ret)
  8288. {
  8289. gathered.append(ret);
  8290. ret = input->nextInGroup();
  8291. }
  8292. unsigned num = gathered.ordinality();
  8293. if (num != 0)
  8294. {
  8295. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8296. ReleaseRoxieRowSet(gathered); // read next group
  8297. }
  8298. else
  8299. eof = true;
  8300. }
  8301. }
  8302. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8303. {
  8304. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8305. if (eof)
  8306. return NULL;
  8307. if (gathered.ordinality())
  8308. {
  8309. while (gathered.isItem(curIndex))
  8310. {
  8311. const void * ret = gathered.item(curIndex++);
  8312. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8313. {
  8314. processed++;
  8315. return ret;
  8316. }
  8317. ReleaseRoxieRow(ret);
  8318. }
  8319. curIndex = 0;
  8320. gathered.kill();
  8321. //nextSteppedGE never returns an end of group marker.
  8322. }
  8323. //Not completely sure about this - it could lead the the start of a group being skipped,
  8324. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8325. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8326. //MORE: What do we do with wasCompleteMatch? something like the following????
  8327. #if 0
  8328. loop
  8329. {
  8330. const void * ret;
  8331. if (stepExtra.returnMismatches())
  8332. {
  8333. bool matchedCompletely = true;
  8334. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8335. if (!wasCompleteMatch)
  8336. return ret;
  8337. }
  8338. else
  8339. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8340. #endif
  8341. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8342. while (ret)
  8343. {
  8344. gathered.append(ret);
  8345. ret = input->nextInGroup();
  8346. }
  8347. unsigned num = gathered.ordinality();
  8348. if (num != 0)
  8349. {
  8350. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8351. ReleaseRoxieRowSet(gathered); // read next group
  8352. }
  8353. else
  8354. eof = true;
  8355. return nextUngrouped(this);
  8356. }
  8357. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8358. {
  8359. return input->gatherConjunctions(collector);
  8360. }
  8361. virtual void resetEOF()
  8362. {
  8363. eof = false;
  8364. releaseGathered();
  8365. input->resetEOF();
  8366. }
  8367. IInputSteppingMeta * querySteppingMeta()
  8368. {
  8369. return input->querySteppingMeta();
  8370. }
  8371. };
  8372. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8373. {
  8374. public:
  8375. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8376. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8377. {
  8378. }
  8379. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8380. {
  8381. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8382. }
  8383. };
  8384. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8385. {
  8386. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8387. }
  8388. //=================================================================================
  8389. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8390. {
  8391. IHThorSideEffectArg &helper;
  8392. CriticalSection ecrit;
  8393. Owned<IException> exception;
  8394. bool executed;
  8395. public:
  8396. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8397. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8398. {
  8399. executed = false;
  8400. }
  8401. virtual const void * nextInGroup()
  8402. {
  8403. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8404. CriticalBlock b(ecrit);
  8405. if (exception)
  8406. throw(exception.getLink());
  8407. if (!executed)
  8408. {
  8409. try
  8410. {
  8411. executed = true;
  8412. helper.action();
  8413. }
  8414. catch(IException *E)
  8415. {
  8416. exception.set(E);
  8417. throw;
  8418. }
  8419. }
  8420. return NULL;
  8421. }
  8422. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8423. {
  8424. CriticalBlock b(ecrit);
  8425. if (exception)
  8426. throw(exception.getLink());
  8427. if (!executed)
  8428. {
  8429. try
  8430. {
  8431. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8432. executed = true;
  8433. start(parentExtractSize, parentExtract, false);
  8434. helper.action();
  8435. stop(false);
  8436. }
  8437. catch(IException *E)
  8438. {
  8439. ctx->notifyAbort(E);
  8440. stop(true);
  8441. exception.set(E);
  8442. throw;
  8443. }
  8444. }
  8445. }
  8446. virtual void reset()
  8447. {
  8448. executed = false;
  8449. exception.clear();
  8450. CRoxieServerActivity::reset();
  8451. }
  8452. };
  8453. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8454. {
  8455. bool isRoot;
  8456. public:
  8457. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8458. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8459. {
  8460. }
  8461. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8462. {
  8463. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8464. }
  8465. virtual bool isSink() const
  8466. {
  8467. return isRoot && !meta.queryOriginal();
  8468. }
  8469. };
  8470. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8471. {
  8472. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8473. }
  8474. //=================================================================================
  8475. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8476. {
  8477. IHThorActionArg &helper;
  8478. public:
  8479. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8480. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorActionArg &)basehelper)
  8481. {
  8482. }
  8483. virtual void onExecute()
  8484. {
  8485. helper.action();
  8486. }
  8487. };
  8488. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8489. {
  8490. public:
  8491. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8492. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8493. {
  8494. }
  8495. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8496. {
  8497. return new CRoxieServerActionActivity(this, _probeManager);
  8498. }
  8499. };
  8500. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8501. {
  8502. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8503. }
  8504. //=================================================================================
  8505. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8506. {
  8507. IHThorSampleArg &helper;
  8508. unsigned numSamples;
  8509. unsigned numToSkip;
  8510. unsigned whichSample;
  8511. bool anyThisGroup;
  8512. bool eof;
  8513. public:
  8514. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8515. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8516. {
  8517. numSamples = 0;
  8518. numToSkip = 0;
  8519. whichSample = 0;
  8520. anyThisGroup = false;
  8521. eof = false;
  8522. }
  8523. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8524. {
  8525. anyThisGroup = false;
  8526. eof = false;
  8527. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8528. numSamples = helper.getProportion();
  8529. whichSample = helper.getSampleNumber();
  8530. numToSkip = (whichSample ? whichSample-1 : 0);
  8531. }
  8532. virtual const void * nextInGroup()
  8533. {
  8534. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8535. if (eof)
  8536. return NULL;
  8537. loop
  8538. {
  8539. const void * ret = input->nextInGroup();
  8540. if (!ret)
  8541. {
  8542. //this does work with groups - may or may not be useful...
  8543. //reset the sample for each group.... probably best.
  8544. numToSkip = (whichSample ? whichSample-1 : 0);
  8545. if (anyThisGroup)
  8546. {
  8547. anyThisGroup = false;
  8548. return NULL;
  8549. }
  8550. ret = input->nextInGroup();
  8551. if (!ret)
  8552. {
  8553. eof = true;
  8554. return NULL; // eof...
  8555. }
  8556. }
  8557. if (numToSkip == 0)
  8558. {
  8559. anyThisGroup = true;
  8560. numToSkip = numSamples-1;
  8561. processed++;
  8562. return ret;
  8563. }
  8564. numToSkip--;
  8565. ReleaseRoxieRow(ret);
  8566. }
  8567. }
  8568. };
  8569. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8570. {
  8571. public:
  8572. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8573. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8574. {
  8575. }
  8576. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8577. {
  8578. return new CRoxieServerSampleActivity(this, _probeManager);
  8579. }
  8580. };
  8581. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8582. {
  8583. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8584. }
  8585. //=================================================================================
  8586. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8587. {
  8588. IHThorChooseSetsArg &helper;
  8589. unsigned numSets;
  8590. unsigned * setCounts;
  8591. bool done;
  8592. public:
  8593. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8594. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8595. {
  8596. setCounts = NULL;
  8597. numSets = 0;
  8598. done = false;
  8599. }
  8600. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8601. {
  8602. done = false;
  8603. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8604. numSets = helper.getNumSets();
  8605. setCounts = new unsigned[numSets];
  8606. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8607. helper.setCounts(setCounts);
  8608. }
  8609. virtual void reset()
  8610. {
  8611. delete [] setCounts;
  8612. setCounts = NULL;
  8613. CRoxieServerActivity::reset();
  8614. }
  8615. virtual const void * nextInGroup()
  8616. {
  8617. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8618. if (done)
  8619. return NULL;
  8620. loop
  8621. {
  8622. const void * ret = input->nextInGroup();
  8623. if (!ret)
  8624. {
  8625. ret = input->nextInGroup();
  8626. if (!ret)
  8627. {
  8628. done = true;
  8629. return NULL;
  8630. }
  8631. }
  8632. processed++;
  8633. switch (helper.getRecordAction(ret))
  8634. {
  8635. case 2:
  8636. done = true;
  8637. return ret;
  8638. case 1:
  8639. return ret;
  8640. }
  8641. ReleaseRoxieRow(ret);
  8642. }
  8643. }
  8644. };
  8645. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8646. {
  8647. public:
  8648. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8649. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8650. {
  8651. }
  8652. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8653. {
  8654. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8655. }
  8656. };
  8657. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8658. {
  8659. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8660. }
  8661. //=================================================================================
  8662. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  8663. {
  8664. protected:
  8665. IHThorChooseSetsExArg &helper;
  8666. unsigned numSets;
  8667. unsigned curIndex;
  8668. unsigned * setCounts;
  8669. count_t * limits;
  8670. bool done;
  8671. ConstPointerArray gathered;
  8672. virtual bool includeRow(const void * row) = 0;
  8673. virtual void calculateSelection() = 0;
  8674. public:
  8675. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8676. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  8677. {
  8678. setCounts = NULL;
  8679. limits = NULL;
  8680. done = false;
  8681. curIndex = 0;
  8682. numSets = 0;
  8683. }
  8684. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8685. {
  8686. done = false;
  8687. curIndex = 0;
  8688. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8689. numSets = helper.getNumSets();
  8690. setCounts = new unsigned[numSets];
  8691. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8692. limits = (count_t *)calloc(sizeof(count_t), numSets);
  8693. helper.getLimits(limits);
  8694. }
  8695. virtual void reset()
  8696. {
  8697. delete [] setCounts;
  8698. setCounts = NULL;
  8699. free(limits);
  8700. limits = NULL;
  8701. while (gathered.isItem(curIndex))
  8702. ReleaseRoxieRow(gathered.item(curIndex++));
  8703. gathered.kill();
  8704. CRoxieServerActivity::reset();
  8705. }
  8706. virtual const void * nextInGroup()
  8707. {
  8708. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8709. if (gathered.ordinality() == 0)
  8710. {
  8711. curIndex = 0;
  8712. if (!input->nextGroup(gathered))
  8713. {
  8714. done = true;
  8715. return NULL;
  8716. }
  8717. ForEachItemIn(idx1, gathered)
  8718. {
  8719. unsigned category = helper.getCategory(gathered.item(idx1));
  8720. if (category)
  8721. setCounts[category-1]++;
  8722. }
  8723. calculateSelection();
  8724. }
  8725. while (gathered.isItem(curIndex))
  8726. {
  8727. const void * row = gathered.item(curIndex);
  8728. gathered.replace(NULL, curIndex);
  8729. curIndex++;
  8730. if (includeRow(row))
  8731. {
  8732. processed++;
  8733. return row;
  8734. }
  8735. ReleaseRoxieRow(row);
  8736. }
  8737. gathered.kill();
  8738. return NULL;
  8739. }
  8740. };
  8741. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  8742. {
  8743. unsigned * numToSkip;
  8744. public:
  8745. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8746. {
  8747. numToSkip = NULL;
  8748. }
  8749. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8750. {
  8751. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8752. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  8753. }
  8754. virtual void reset()
  8755. {
  8756. free(numToSkip);
  8757. numToSkip = NULL;
  8758. CRoxieServerChooseSetsExActivity::reset();
  8759. }
  8760. protected:
  8761. virtual void calculateSelection()
  8762. {
  8763. for (unsigned idx=0; idx < numSets; idx++)
  8764. {
  8765. if (setCounts[idx] < limits[idx])
  8766. numToSkip[idx] = 0;
  8767. else
  8768. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  8769. }
  8770. }
  8771. virtual bool includeRow(const void * row)
  8772. {
  8773. unsigned category = helper.getCategory(row);
  8774. if (category)
  8775. {
  8776. if (numToSkip[category-1] == 0)
  8777. return true;
  8778. numToSkip[category-1]--;
  8779. }
  8780. return false;
  8781. }
  8782. };
  8783. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  8784. {
  8785. count_t * counter;
  8786. public:
  8787. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8788. {
  8789. counter = NULL;
  8790. }
  8791. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8792. {
  8793. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8794. counter = (count_t *)calloc(sizeof(count_t), numSets);
  8795. }
  8796. virtual void reset()
  8797. {
  8798. free(counter);
  8799. counter = NULL;
  8800. CRoxieServerChooseSetsExActivity::reset();
  8801. }
  8802. protected:
  8803. virtual void calculateSelection()
  8804. {
  8805. }
  8806. virtual bool includeRow(const void * row)
  8807. {
  8808. unsigned category = helper.getCategory(row);
  8809. if (category)
  8810. {
  8811. assertex(category <= numSets);
  8812. counter[category-1] += limits[category-1];
  8813. if(counter[category-1] >= setCounts[category-1])
  8814. {
  8815. counter[category-1] -= setCounts[category-1];
  8816. return true;
  8817. }
  8818. }
  8819. return false;
  8820. }
  8821. };
  8822. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  8823. {
  8824. public:
  8825. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8826. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8827. {
  8828. }
  8829. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8830. {
  8831. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  8832. }
  8833. };
  8834. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8835. {
  8836. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8837. }
  8838. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  8839. {
  8840. public:
  8841. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8842. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8843. {
  8844. }
  8845. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8846. {
  8847. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  8848. }
  8849. };
  8850. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8851. {
  8852. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8853. }
  8854. //=================================================================================
  8855. class CRoxieServerEnthActivity : public CRoxieServerActivity
  8856. {
  8857. IHThorEnthArg &helper;
  8858. unsigned __int64 numerator;
  8859. unsigned __int64 denominator;
  8860. unsigned __int64 counter;
  8861. bool eof;
  8862. public:
  8863. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8864. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  8865. {
  8866. eof = false;
  8867. numerator = denominator = counter = 0;
  8868. }
  8869. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8870. {
  8871. eof = false;
  8872. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8873. numerator = helper.getProportionNumerator();
  8874. denominator = helper.getProportionDenominator();
  8875. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  8876. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  8877. if (counter >= denominator)
  8878. counter %= denominator;
  8879. }
  8880. inline bool wanted()
  8881. {
  8882. counter += numerator;
  8883. if(counter >= denominator)
  8884. {
  8885. counter -= denominator;
  8886. return true;
  8887. }
  8888. return false;
  8889. }
  8890. virtual const void * nextInGroup()
  8891. {
  8892. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8893. if (eof)
  8894. return NULL;
  8895. const void * ret;
  8896. loop
  8897. {
  8898. ret = input->nextInGroup();
  8899. if(!ret) //end of group
  8900. ret = input->nextInGroup();
  8901. if(!ret) //eof
  8902. {
  8903. eof = true;
  8904. return ret;
  8905. }
  8906. if (wanted())
  8907. return ret;
  8908. ReleaseRoxieRow(ret);
  8909. }
  8910. }
  8911. };
  8912. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  8913. {
  8914. public:
  8915. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8916. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8917. {
  8918. }
  8919. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8920. {
  8921. return new CRoxieServerEnthActivity(this, _probeManager);
  8922. }
  8923. };
  8924. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8925. {
  8926. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8927. }
  8928. //=================================================================================
  8929. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  8930. {
  8931. IHThorAggregateArg &helper;
  8932. bool eof;
  8933. bool isInputGrouped;
  8934. bool abortEarly;
  8935. public:
  8936. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8937. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  8938. {
  8939. eof = false;
  8940. isInputGrouped = false;
  8941. abortEarly = false;
  8942. }
  8943. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8944. {
  8945. eof = false;
  8946. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  8947. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  8948. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8949. }
  8950. virtual bool needsAllocator() const { return true; }
  8951. virtual const void * nextInGroup()
  8952. {
  8953. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8954. if (eof)
  8955. return NULL;
  8956. const void * next = input->nextInGroup();
  8957. if (!next && isInputGrouped)
  8958. {
  8959. eof = true;
  8960. return NULL;
  8961. }
  8962. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  8963. size32_t finalSize = helper.clearAggregate(rowBuilder);
  8964. if (next)
  8965. {
  8966. finalSize = helper.processFirst(rowBuilder, next);
  8967. ReleaseRoxieRow(next);
  8968. if (!abortEarly)
  8969. {
  8970. loop
  8971. {
  8972. next = input->nextInGroup();
  8973. if (!next)
  8974. break;
  8975. finalSize = helper.processNext(rowBuilder, next);
  8976. ReleaseRoxieRow(next);
  8977. }
  8978. }
  8979. }
  8980. if (!isInputGrouped) // either read all, or aborted early
  8981. eof = true;
  8982. processed++;
  8983. return rowBuilder.finalizeRowClear(finalSize);
  8984. }
  8985. };
  8986. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  8987. {
  8988. public:
  8989. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8990. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8991. {
  8992. }
  8993. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8994. {
  8995. return new CRoxieServerAggregateActivity(this, _probeManager);
  8996. }
  8997. };
  8998. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8999. {
  9000. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9001. }
  9002. //=================================================================================
  9003. typedef unsigned t_hashPrefix;
  9004. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9005. {
  9006. IHThorHashAggregateArg &helper;
  9007. RowAggregator aggregated;
  9008. bool eof;
  9009. bool gathered;
  9010. bool isGroupedAggregate;
  9011. public:
  9012. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9013. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9014. isGroupedAggregate(_isGroupedAggregate),
  9015. aggregated(helper, helper)
  9016. {
  9017. eof = false;
  9018. gathered = false;
  9019. }
  9020. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9021. {
  9022. eof = false;
  9023. gathered = false;
  9024. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9025. }
  9026. virtual void reset()
  9027. {
  9028. aggregated.reset();
  9029. CRoxieServerActivity::reset();
  9030. }
  9031. virtual bool needsAllocator() const { return true; }
  9032. virtual const void * nextInGroup()
  9033. {
  9034. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9035. if (eof)
  9036. return NULL;
  9037. if (!gathered)
  9038. {
  9039. aggregated.start(rowAllocator);
  9040. bool eog = true;
  9041. loop
  9042. {
  9043. const void * next = input->nextInGroup();
  9044. if (!next)
  9045. {
  9046. if (isGroupedAggregate)
  9047. {
  9048. if (eog)
  9049. eof = true;
  9050. break;
  9051. }
  9052. next = input->nextInGroup();
  9053. if (!next)
  9054. break;
  9055. }
  9056. eog = false;
  9057. aggregated.addRow(next);
  9058. ReleaseRoxieRow(next);
  9059. }
  9060. gathered = true;
  9061. }
  9062. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9063. if (next)
  9064. {
  9065. processed++;
  9066. return next->finalizeRowClear();
  9067. }
  9068. if (!isGroupedAggregate)
  9069. eof = true;
  9070. aggregated.reset();
  9071. gathered = false;
  9072. return NULL;
  9073. }
  9074. };
  9075. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9076. {
  9077. public:
  9078. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9079. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9080. {
  9081. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9082. }
  9083. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9084. {
  9085. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9086. }
  9087. protected:
  9088. bool isGroupedAggregate;
  9089. };
  9090. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9091. {
  9092. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9093. }
  9094. //=================================================================================
  9095. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9096. {
  9097. IHThorDegroupArg &helper;
  9098. bool eof;
  9099. public:
  9100. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9101. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9102. {
  9103. eof = false;
  9104. }
  9105. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9106. {
  9107. eof = false;
  9108. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9109. }
  9110. virtual const void * nextInGroup()
  9111. {
  9112. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9113. if (eof)
  9114. return NULL;
  9115. const void * ret = input->nextInGroup();
  9116. if (!ret)
  9117. ret = input->nextInGroup();
  9118. if (ret)
  9119. processed++;
  9120. else
  9121. eof = true;
  9122. return ret;
  9123. }
  9124. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9125. {
  9126. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9127. if (eof)
  9128. return NULL;
  9129. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9130. if (ret)
  9131. processed++;
  9132. else
  9133. eof = true;
  9134. return ret;
  9135. }
  9136. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9137. {
  9138. return input->gatherConjunctions(collector);
  9139. }
  9140. virtual void resetEOF()
  9141. {
  9142. eof = false;
  9143. input->resetEOF();
  9144. }
  9145. IInputSteppingMeta * querySteppingMeta()
  9146. {
  9147. return input->querySteppingMeta();
  9148. }
  9149. };
  9150. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9151. {
  9152. public:
  9153. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9154. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9155. {
  9156. }
  9157. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9158. {
  9159. return new CRoxieServerDegroupActivity(this, _probeManager);
  9160. }
  9161. };
  9162. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9163. {
  9164. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9165. }
  9166. //=================================================================================
  9167. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9168. {
  9169. IHThorDiskReadArg &helper;
  9170. bool needTransform;
  9171. bool eof;
  9172. bool anyThisGroup;
  9173. unsigned __int64 rowLimit;
  9174. unsigned __int64 choosenLimit;
  9175. public:
  9176. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9177. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9178. {
  9179. needTransform = helper.needTransform();
  9180. rowLimit = (unsigned __int64) -1;
  9181. choosenLimit = 0;
  9182. eof = false;
  9183. anyThisGroup = false;
  9184. }
  9185. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9186. {
  9187. anyThisGroup = false;
  9188. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9189. if (helper.canMatchAny())
  9190. eof = false;
  9191. else
  9192. eof = true;
  9193. choosenLimit = helper.getChooseNLimit();
  9194. rowLimit = helper.getRowLimit();
  9195. helper.setCallback(NULL); // members should not be called - change if they are
  9196. }
  9197. virtual bool needsAllocator() const { return true; }
  9198. virtual const void * nextInGroup()
  9199. {
  9200. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9201. if (eof)
  9202. return NULL;
  9203. if (processed==choosenLimit)
  9204. {
  9205. eof = true;
  9206. return NULL;
  9207. }
  9208. if (needTransform)
  9209. {
  9210. loop
  9211. {
  9212. const void *in = input->nextInGroup();
  9213. if (!in)
  9214. {
  9215. if (anyThisGroup)
  9216. {
  9217. anyThisGroup = false;
  9218. return NULL;
  9219. }
  9220. in = input->nextInGroup();
  9221. if (!in)
  9222. {
  9223. eof = true;
  9224. return NULL; // eof...
  9225. }
  9226. }
  9227. unsigned outSize;
  9228. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9229. try
  9230. {
  9231. outSize = helper.transform(rowBuilder, in);
  9232. ReleaseRoxieRow(in);
  9233. }
  9234. catch (IException *E)
  9235. {
  9236. throw makeWrappedException(E);
  9237. }
  9238. if (outSize)
  9239. {
  9240. anyThisGroup = true;
  9241. processed++;
  9242. if (processed==rowLimit)
  9243. {
  9244. if (traceLevel > 4)
  9245. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9246. helper.onLimitExceeded();
  9247. }
  9248. return rowBuilder.finalizeRowClear(outSize);
  9249. }
  9250. }
  9251. }
  9252. else
  9253. {
  9254. const void *ret = input->nextInGroup();
  9255. if (ret)
  9256. {
  9257. processed++;
  9258. if (processed==rowLimit)
  9259. {
  9260. if (traceLevel > 4)
  9261. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9262. ReleaseClearRoxieRow(ret);
  9263. helper.onLimitExceeded(); // should not return
  9264. throwUnexpected();
  9265. }
  9266. }
  9267. return ret;
  9268. }
  9269. }
  9270. };
  9271. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9272. {
  9273. public:
  9274. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9275. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9276. {
  9277. }
  9278. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9279. {
  9280. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9281. }
  9282. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9283. {
  9284. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9285. setInput(0, source, sourceIdx);
  9286. else
  9287. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9288. }
  9289. };
  9290. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9291. {
  9292. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9293. }
  9294. //=================================================================================
  9295. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9296. {
  9297. public:
  9298. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9299. : CRoxieServerActivity(_factory, _probeManager)
  9300. {
  9301. }
  9302. ~CRoxieServerSpillWriteActivity()
  9303. {
  9304. }
  9305. virtual const void *nextInGroup()
  9306. {
  9307. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9308. return input->nextInGroup();
  9309. }
  9310. };
  9311. //==================================================================================
  9312. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9313. {
  9314. protected:
  9315. Owned<IExtRowWriter> outSeq;
  9316. Owned<IOutputRowSerializer> rowSerializer;
  9317. Linked<IFileIOStream> diskout;
  9318. bool blockcompressed;
  9319. bool extend;
  9320. bool overwrite;
  9321. bool encrypted;
  9322. bool grouped;
  9323. IHThorDiskWriteArg &helper;
  9324. StringBuffer lfn; // logical filename
  9325. CachedOutputMetaData diskmeta;
  9326. Owned<IRoxieWriteHandler> writer;
  9327. bool tallycrc;
  9328. unsigned __int64 uncompressedBytesWritten;
  9329. CRC32 crc;
  9330. void updateWorkUnitResult(unsigned __int64 reccount)
  9331. {
  9332. assertex(writer);
  9333. // MORE - a lot of this is common with hthor
  9334. if(lfn.length()) //this is required as long as temp files don't get a name which can be stored in the WU and automatically deleted by the WU
  9335. {
  9336. WorkunitUpdate wu = ctx->updateWorkUnit();
  9337. if (wu)
  9338. {
  9339. unsigned flags = helper.getFlags();
  9340. WUFileKind fileKind;
  9341. if (TDXtemporary & flags)
  9342. fileKind = WUFileTemporary;
  9343. else if(TDXjobtemp & flags)
  9344. fileKind = WUFileJobOwned;
  9345. else if(TDWowned & flags)
  9346. fileKind = WUFileOwned;
  9347. else
  9348. fileKind = WUFileStandard;
  9349. StringArray clusters;
  9350. writer->getClusters(clusters);
  9351. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9352. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9353. {
  9354. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9355. if (result)
  9356. {
  9357. result->setResultTotalRowCount(reccount);
  9358. result->setResultStatus(ResultStatusCalculated);
  9359. if (helper.getFlags() & TDWresult)
  9360. result->setResultFilename(lfn.str());
  9361. else
  9362. result->setResultLogicalName(lfn.str());
  9363. }
  9364. }
  9365. }
  9366. }
  9367. }
  9368. void resolve()
  9369. {
  9370. OwnedRoxieString rawLogicalName = helper.getFileName();
  9371. assertex(rawLogicalName);
  9372. assertex((helper.getFlags() & TDXtemporary) == 0);
  9373. StringArray clusters;
  9374. unsigned clusterIdx = 0;
  9375. while(true)
  9376. {
  9377. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9378. if(!cluster)
  9379. break;
  9380. clusters.append(cluster);
  9381. clusterIdx++;
  9382. }
  9383. if (clusters.length())
  9384. {
  9385. if (extend)
  9386. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9387. }
  9388. else
  9389. {
  9390. if (roxieName.length())
  9391. clusters.append(roxieName.str());
  9392. else
  9393. clusters.append(".");
  9394. }
  9395. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters)); // MORE - if there's a workunit, use if for scope.
  9396. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9397. }
  9398. public:
  9399. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9400. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDiskWriteArg &)basehelper)
  9401. {
  9402. extend = ((helper.getFlags() & TDWextend) != 0);
  9403. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9404. grouped = false; // don't think we need to support it...
  9405. diskmeta.set(helper.queryDiskRecordSize());
  9406. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9407. encrypted = false; // set later
  9408. tallycrc = true;
  9409. uncompressedBytesWritten = 0;
  9410. }
  9411. ~CRoxieServerDiskWriteActivity()
  9412. {
  9413. }
  9414. virtual bool needsAllocator() const
  9415. {
  9416. return true;
  9417. }
  9418. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9419. {
  9420. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9421. resolve();
  9422. Owned<IFileIO> io;
  9423. void *ekey;
  9424. size32_t ekeylen;
  9425. helper.getEncryptKey(ekeylen, ekey);
  9426. Owned<ICompressor> ecomp;
  9427. if (ekeylen!=0)
  9428. {
  9429. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9430. memset(ekey,0,ekeylen);
  9431. rtlFree(ekey);
  9432. encrypted = true;
  9433. blockcompressed = true;
  9434. }
  9435. if (blockcompressed)
  9436. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9437. else
  9438. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9439. if (!io)
  9440. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9441. diskout.setown(createBufferedIOStream(io));
  9442. if (extend)
  9443. diskout->seek(0, IFSend);
  9444. tallycrc = !factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9445. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9446. rowSerializer.set(rowIf->queryRowSerializer());
  9447. unsigned rwFlags = rw_autoflush;
  9448. if(grouped)
  9449. rwFlags |= rw_grouped;
  9450. if(tallycrc)
  9451. rwFlags |= rw_crc;
  9452. if(!factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck))
  9453. rwFlags |= rw_crc;
  9454. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9455. }
  9456. virtual void stop(bool aborting)
  9457. {
  9458. if (aborting)
  9459. {
  9460. if (writer)
  9461. writer->finish(false, this);
  9462. }
  9463. else
  9464. {
  9465. outSeq->flush(&crc);
  9466. updateWorkUnitResult(processed);
  9467. uncompressedBytesWritten = outSeq->getPosition();
  9468. writer->finish(true, this);
  9469. }
  9470. writer.clear();
  9471. CRoxieServerActivity::stop(aborting);
  9472. }
  9473. virtual void reset()
  9474. {
  9475. CRoxieServerActivity::reset();
  9476. diskout.clear();
  9477. outSeq.clear();
  9478. writer.clear();
  9479. uncompressedBytesWritten = 0;
  9480. crc.reset();
  9481. }
  9482. virtual void onExecute()
  9483. {
  9484. loop
  9485. {
  9486. const void *nextrec = input->nextInGroup();
  9487. if (!nextrec)
  9488. {
  9489. nextrec = input->nextInGroup();
  9490. if (!nextrec)
  9491. break;
  9492. }
  9493. processed++;
  9494. outSeq->putRow(nextrec);
  9495. }
  9496. }
  9497. virtual void setFileProperties(IFileDescriptor *desc) const
  9498. {
  9499. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9500. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9501. if (blockcompressed)
  9502. {
  9503. // caller has already set @size from file size...
  9504. fileProps.setPropBool("@blockCompressed", true);
  9505. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0)); // MORE should this be on logical too?
  9506. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9507. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9508. }
  9509. else if (tallycrc)
  9510. partProps.setPropInt64("@fileCrc", crc.get());
  9511. if (encrypted)
  9512. fileProps.setPropBool("@encrypted", true);
  9513. fileProps.setPropInt64("@recordCount", processed);
  9514. unsigned flags = helper.getFlags();
  9515. if (flags & TDWpersist)
  9516. fileProps.setPropBool("@persistent", true);
  9517. if (grouped)
  9518. fileProps.setPropBool("@grouped", true);
  9519. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9520. fileProps.setPropBool("@owned", true);
  9521. if (flags & TDWresult)
  9522. fileProps.setPropBool("@result", true);
  9523. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9524. if (workUnit)
  9525. {
  9526. SCMStringBuffer owner, wuid, job;
  9527. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9528. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9529. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9530. }
  9531. setExpiryTime(fileProps, helper.getExpiryDays());
  9532. if (flags & TDWupdate)
  9533. {
  9534. unsigned eclCRC;
  9535. unsigned __int64 totalCRC;
  9536. helper.getUpdateCRCs(eclCRC, totalCRC);
  9537. fileProps.setPropInt("@eclCRC", eclCRC);
  9538. fileProps.setPropInt64("@totalCRC", totalCRC);
  9539. }
  9540. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9541. IRecordSize * inputMeta = input->queryOutputMeta();
  9542. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9543. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9544. const char *recordECL = helper.queryRecordECL();
  9545. if (recordECL && *recordECL)
  9546. fileProps.setProp("ECL", recordECL);
  9547. }
  9548. virtual IUserDescriptor *queryUserDescriptor() const
  9549. {
  9550. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9551. if (workUnit)
  9552. return workUnit->queryUserDescriptor();
  9553. else
  9554. return NULL;
  9555. }
  9556. virtual bool isOutputTransformed() const { return false; }
  9557. };
  9558. //=================================================================================
  9559. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9560. {
  9561. IHThorCsvWriteArg &csvHelper;
  9562. CSVOutputStream csvOutput;
  9563. public:
  9564. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9565. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9566. {
  9567. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9568. }
  9569. virtual void onExecute()
  9570. {
  9571. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9572. if (header)
  9573. {
  9574. csvOutput.beginLine();
  9575. csvOutput.writeHeaderLn(strlen(header), header);
  9576. diskout->write(csvOutput.length(), csvOutput.str());
  9577. }
  9578. loop
  9579. {
  9580. const void *nextrec = input->nextInGroup();
  9581. if (!nextrec)
  9582. {
  9583. nextrec = input->nextInGroup();
  9584. if (!nextrec)
  9585. break;
  9586. }
  9587. processed++;
  9588. csvOutput.beginLine();
  9589. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9590. csvOutput.endLine();
  9591. diskout->write(csvOutput.length(), csvOutput.str());
  9592. ReleaseRoxieRow(nextrec);
  9593. }
  9594. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9595. if (footer)
  9596. {
  9597. csvOutput.beginLine();
  9598. csvOutput.writeHeaderLn(strlen(footer), footer);
  9599. diskout->write(csvOutput.length(), csvOutput.str());
  9600. }
  9601. }
  9602. virtual void setFileProperties(IFileDescriptor *desc) const
  9603. {
  9604. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9605. IPropertyTree &props = desc->queryProperties();
  9606. props.setProp("@format","utf8n");
  9607. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9608. StringBuffer separator;
  9609. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9610. const char *s = rs;
  9611. while (s && *s)
  9612. {
  9613. if (',' == *s)
  9614. separator.append("\\,");
  9615. else
  9616. separator.append(*s);
  9617. ++s;
  9618. }
  9619. props.setProp("@csvSeparate", separator.str());
  9620. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9621. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9622. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9623. }
  9624. virtual bool isOutputTransformed() const { return true; }
  9625. };
  9626. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9627. {
  9628. IHThorXmlWriteArg &xmlHelper;
  9629. StringAttr rowTag;
  9630. public:
  9631. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9632. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper))
  9633. {
  9634. }
  9635. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9636. {
  9637. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9638. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9639. if (!xmlpath)
  9640. rowTag.set("Row");
  9641. else
  9642. {
  9643. const char *path = xmlpath;
  9644. if (*path == '/') path++;
  9645. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  9646. rowTag.set(path);
  9647. }
  9648. }
  9649. virtual void onExecute()
  9650. {
  9651. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  9652. const char *header = suppliedHeader;
  9653. if (!header) header = "<Dataset>\n";
  9654. diskout->write(strlen(header), header);
  9655. CommonXmlWriter xmlOutput(xmlHelper.getXmlFlags());
  9656. loop
  9657. {
  9658. OwnedConstRoxieRow nextrec = input->nextInGroup();
  9659. if (!nextrec)
  9660. {
  9661. nextrec.setown(input->nextInGroup());
  9662. if (!nextrec)
  9663. break;
  9664. }
  9665. processed++;
  9666. xmlOutput.clear().outputBeginNested(rowTag, false);
  9667. xmlHelper.toXML((const byte *)nextrec.get(), xmlOutput);
  9668. xmlOutput.outputEndNested(rowTag);
  9669. diskout->write(xmlOutput.length(), xmlOutput.str());
  9670. }
  9671. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  9672. const char * footer = suppliedFooter;
  9673. if (!footer) footer = "</Dataset>\n";
  9674. diskout->write(strlen(footer), footer);
  9675. }
  9676. virtual void reset()
  9677. {
  9678. CRoxieServerDiskWriteActivity::reset();
  9679. rowTag.clear();
  9680. }
  9681. virtual void setFileProperties(IFileDescriptor *desc) const
  9682. {
  9683. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9684. desc->queryProperties().setProp("@format","utf8n");
  9685. desc->queryProperties().setProp("@rowTag",rowTag.get());
  9686. }
  9687. virtual bool isOutputTransformed() const { return true; }
  9688. };
  9689. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  9690. {
  9691. bool isRoot;
  9692. public:
  9693. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9694. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  9695. {
  9696. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  9697. setNumOutputs(helper->getTempUsageCount());
  9698. if (_kind!=TAKdiskwrite)
  9699. assertex(numOutputs == 0);
  9700. }
  9701. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9702. {
  9703. switch (numOutputs)
  9704. {
  9705. case 0:
  9706. switch (kind)
  9707. {
  9708. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  9709. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  9710. case TAKxmlwrite: return new CRoxieServerXmlWriteActivity(this, _probeManager);
  9711. };
  9712. throwUnexpected();
  9713. case 1:
  9714. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  9715. default:
  9716. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  9717. }
  9718. }
  9719. virtual bool isSink() const
  9720. {
  9721. return numOutputs == 0; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  9722. }
  9723. };
  9724. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9725. {
  9726. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  9727. }
  9728. //=================================================================================
  9729. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9730. {
  9731. IHThorIndexWriteArg &helper;
  9732. bool overwrite;
  9733. Owned<ClusterWriteHandler> clusterHandler;
  9734. Owned<IRoxieWriteHandler> writer;
  9735. unsigned __int64 reccount;
  9736. unsigned int fileCrc;
  9737. StringBuffer filename;
  9738. void updateWorkUnitResult()
  9739. {
  9740. if(filename.length()) //this is required as long as temp files don't get a name which can be stored in the WU and automatically deleted by the WU
  9741. {
  9742. WorkunitUpdate wu = ctx->updateWorkUnit();
  9743. if (wu)
  9744. {
  9745. if (!(helper.getFlags() & TDXtemporary) && helper.getSequence() >= 0)
  9746. {
  9747. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9748. if (result)
  9749. {
  9750. result->setResultTotalRowCount(reccount);
  9751. result->setResultStatus(ResultStatusCalculated);
  9752. result->setResultLogicalName(filename.str());
  9753. }
  9754. }
  9755. if(clusterHandler)
  9756. clusterHandler->finish(writer->queryFile());
  9757. }
  9758. CTXLOG("Created roxie index file %s", filename.str());
  9759. }
  9760. }
  9761. virtual void resolve()
  9762. {
  9763. StringArray clusters;
  9764. unsigned clusterIdx = 0;
  9765. while(true)
  9766. {
  9767. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9768. if(!cluster)
  9769. break;
  9770. clusters.append(cluster);
  9771. clusterIdx++;
  9772. }
  9773. if (roxieName.length())
  9774. clusters.append(roxieName.str());
  9775. else
  9776. clusters.append(".");
  9777. OwnedRoxieString fname(helper.getFileName());
  9778. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  9779. filename.set(writer->queryFile()->queryFilename());
  9780. if (writer->queryFile()->exists())
  9781. {
  9782. if (overwrite)
  9783. {
  9784. CTXLOG("Removing existing %s from DFS",filename.str());
  9785. writer->queryFile()->remove();
  9786. }
  9787. else
  9788. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  9789. }
  9790. }
  9791. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  9792. {
  9793. size32_t nameLen;
  9794. char * nameBuff;
  9795. size32_t valueLen;
  9796. char * valueBuff;
  9797. unsigned idx = 0;
  9798. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  9799. {
  9800. StringBuffer name(nameLen, nameBuff);
  9801. StringBuffer value(valueLen, valueBuff);
  9802. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  9803. {
  9804. OwnedRoxieString fname(helper.getFileName());
  9805. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  9806. }
  9807. if(!validateXMLTag(name.str()))
  9808. {
  9809. OwnedRoxieString fname(helper.getFileName());
  9810. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  9811. }
  9812. if(!metadata)
  9813. metadata.setown(createPTree("metadata"));
  9814. metadata->setProp(name.str(), value.str());
  9815. }
  9816. }
  9817. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  9818. {
  9819. if(!metadata)
  9820. metadata.setown(createPTree("metadata"));
  9821. metadata->setProp("_record_ECL", helper.queryRecordECL());
  9822. void * layoutMetaBuff;
  9823. size32_t layoutMetaSize;
  9824. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  9825. {
  9826. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  9827. rtlFree(layoutMetaBuff);
  9828. }
  9829. }
  9830. public:
  9831. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9832. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  9833. {
  9834. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  9835. reccount = 0;
  9836. }
  9837. ~CRoxieServerIndexWriteActivity()
  9838. {
  9839. }
  9840. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9841. {
  9842. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9843. resolve();
  9844. }
  9845. virtual void onExecute()
  9846. {
  9847. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  9848. size32_t maxDiskRecordSize;
  9849. if (isVariable)
  9850. maxDiskRecordSize = 0x8000;
  9851. else
  9852. {
  9853. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  9854. if (maxDiskRecordSize > 0x8000)
  9855. throw MakeStringException(99, "Index minimum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  9856. }
  9857. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  9858. unsigned __int64 fileSize = 0;
  9859. fileCrc = -1;
  9860. OwnedRoxieString dsName(helper.getFileName());
  9861. if (dsName.get())
  9862. {
  9863. Owned<const IResolvedFile> dsFileInfo = resolveLFN(dsName, false);
  9864. if (dsFileInfo)
  9865. {
  9866. fileSize = dsFileInfo->getFileSize();
  9867. }
  9868. }
  9869. {
  9870. Owned<IFileIO> io;
  9871. try
  9872. {
  9873. io.setown(writer->queryFile()->open(IFOcreate));
  9874. }
  9875. catch(IException * e)
  9876. {
  9877. e->Release();
  9878. clearKeyStoreCache(false);
  9879. io.setown(writer->queryFile()->open(IFOcreate));
  9880. }
  9881. if(!io)
  9882. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  9883. Owned<IFileIOStream> out = createIOStream(io);
  9884. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  9885. if (helper.getFlags() & TIWrowcompress)
  9886. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  9887. else if (!(helper.getFlags() & TIWnolzwcompress))
  9888. flags |= HTREE_COMPRESSED_KEY;
  9889. if (isVariable)
  9890. flags |= HTREE_VARSIZE;
  9891. Owned<IPropertyTree> metadata;
  9892. buildUserMetadata(metadata);
  9893. buildLayoutMetadata(metadata);
  9894. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  9895. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, fileSize, nodeSize, helper.getKeyedSize(), 0);
  9896. class BcWrapper : implements IBlobCreator
  9897. {
  9898. IKeyBuilder *builder;
  9899. public:
  9900. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  9901. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  9902. {
  9903. return builder->createBlob(size, (const char *) ptr);
  9904. }
  9905. } bc(builder);
  9906. // Loop thru the results
  9907. loop
  9908. {
  9909. OwnedConstRoxieRow nextrec(input->nextInGroup());
  9910. if (!nextrec)
  9911. {
  9912. nextrec.setown(input->nextInGroup());
  9913. if (!nextrec)
  9914. break;
  9915. }
  9916. try
  9917. {
  9918. unsigned __int64 fpos;
  9919. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  9920. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  9921. builder->processKeyData(rowBuffer, fpos, thisSize);
  9922. }
  9923. catch(IException * e)
  9924. {
  9925. throw makeWrappedException(e);
  9926. }
  9927. reccount++;
  9928. }
  9929. if(metadata)
  9930. builder->finish(metadata,&fileCrc);
  9931. else
  9932. builder->finish(&fileCrc);
  9933. }
  9934. }
  9935. virtual void stop(bool aborting)
  9936. {
  9937. if (writer)
  9938. {
  9939. if (!aborting)
  9940. updateWorkUnitResult();
  9941. writer->finish(!aborting, this);
  9942. writer.clear();
  9943. }
  9944. CRoxieServerActivity::stop(aborting);
  9945. }
  9946. virtual void reset()
  9947. {
  9948. CRoxieServerActivity::reset();
  9949. writer.clear();
  9950. }
  9951. //interface IRoxiePublishCallback
  9952. virtual void setFileProperties(IFileDescriptor *desc) const
  9953. {
  9954. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9955. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9956. // Now publish to name services
  9957. StringBuffer dir,base;
  9958. offset_t indexFileSize = writer->queryFile()->size();
  9959. if(clusterHandler)
  9960. clusterHandler->splitPhysicalFilename(dir, base);
  9961. else
  9962. splitFilename(filename.str(), &dir, &dir, &base, &base);
  9963. desc->setDefaultDir(dir.str());
  9964. //properties of the first file part.
  9965. Owned<IPropertyTree> attrs;
  9966. if(clusterHandler)
  9967. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  9968. else
  9969. {
  9970. // add cluster
  9971. StringBuffer mygroupname;
  9972. desc->setNumParts(1);
  9973. desc->setPartMask(base.str());
  9974. attrs.set(&desc->queryPart(0)->queryProperties());
  9975. }
  9976. attrs->setPropInt64("@size", indexFileSize);
  9977. CDateTime createTime, modifiedTime, accessedTime;
  9978. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  9979. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  9980. unsigned hour, min, sec, nanosec;
  9981. modifiedTime.getTime(hour, min, sec, nanosec);
  9982. modifiedTime.setTime(hour, min, sec, 0);
  9983. StringBuffer timestr;
  9984. modifiedTime.getString(timestr);
  9985. if(timestr.length())
  9986. attrs->setProp("@modified", timestr.str());
  9987. if(clusterHandler)
  9988. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  9989. // properties of the logical file
  9990. IPropertyTree & properties = desc->queryProperties();
  9991. properties.setProp("@kind", "key");
  9992. properties.setPropInt64("@size", indexFileSize);
  9993. properties.setPropInt64("@recordCount", reccount);
  9994. SCMStringBuffer info;
  9995. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  9996. if (workUnit)
  9997. {
  9998. properties.setProp("@owner", workUnit->getUser(info).str());
  9999. info.clear();
  10000. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10001. info.clear();
  10002. properties.setProp("@job", workUnit->getJobName(info).str());
  10003. }
  10004. char const * rececl = helper.queryRecordECL();
  10005. if(rececl && *rececl)
  10006. properties.setProp("ECL", rececl);
  10007. setExpiryTime(properties, helper.getExpiryDays());
  10008. if (helper.getFlags() & TIWupdate)
  10009. {
  10010. unsigned eclCRC;
  10011. unsigned __int64 totalCRC;
  10012. helper.getUpdateCRCs(eclCRC, totalCRC);
  10013. properties.setPropInt("@eclCRC", eclCRC);
  10014. properties.setPropInt64("@totalCRC", totalCRC);
  10015. }
  10016. properties.setPropInt("@fileCrc", fileCrc);
  10017. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10018. void * layoutMetaBuff;
  10019. size32_t layoutMetaSize;
  10020. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10021. {
  10022. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10023. rtlFree(layoutMetaBuff);
  10024. }
  10025. }
  10026. IUserDescriptor *queryUserDescriptor() const
  10027. {
  10028. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10029. if (workUnit)
  10030. return workUnit->queryUserDescriptor();
  10031. else
  10032. return NULL;
  10033. }
  10034. };
  10035. //=================================================================================
  10036. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10037. {
  10038. public:
  10039. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10040. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10041. {
  10042. setNumOutputs(0);
  10043. }
  10044. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10045. {
  10046. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10047. }
  10048. virtual bool isSink() const
  10049. {
  10050. return true;
  10051. }
  10052. };
  10053. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10054. {
  10055. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10056. }
  10057. //=================================================================================
  10058. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10059. {
  10060. if((flags & JFmatchAbortLimitSkips) != 0)
  10061. {
  10062. limitFail = false;
  10063. limitOnFail = false;
  10064. }
  10065. else
  10066. {
  10067. limitOnFail = ((flags & JFonfail) != 0);
  10068. limitFail = !limitOnFail;
  10069. }
  10070. }
  10071. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10072. {
  10073. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10074. IHThorJoinArg &helper;
  10075. ICompare * collate;
  10076. ICompare * collateupper;
  10077. ThorActivityKind activityKind;
  10078. bool leftOuterJoin;
  10079. bool rightOuterJoin;
  10080. bool exclude;
  10081. bool limitFail;
  10082. bool limitOnFail;
  10083. unsigned keepLimit;
  10084. unsigned joinLimit;
  10085. unsigned atmostLimit;
  10086. unsigned abortLimit;
  10087. unsigned atmostsTriggered;
  10088. bool betweenjoin;
  10089. OwnedRowArray right;
  10090. const void * left;
  10091. const void * pendingRight;
  10092. unsigned rightIndex;
  10093. BoolArray matchedRight;
  10094. bool matchedLeft;
  10095. Owned<IException> failingLimit;
  10096. ConstPointerArray filteredRight;
  10097. Owned<IRHLimitedCompareHelper> limitedhelper;
  10098. OwnedConstRoxieRow defaultLeft;
  10099. OwnedConstRoxieRow defaultRight;
  10100. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10101. Owned<IEngineRowAllocator> defaultRightAllocator;
  10102. bool cloneLeft;
  10103. void createDefaultLeft()
  10104. {
  10105. if (!defaultLeft)
  10106. {
  10107. if (!defaultLeftAllocator)
  10108. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10109. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10110. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10111. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10112. }
  10113. }
  10114. void createDefaultRight()
  10115. {
  10116. if (!defaultRight)
  10117. {
  10118. if (!defaultRightAllocator)
  10119. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10120. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10121. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10122. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10123. }
  10124. }
  10125. public:
  10126. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10127. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10128. {
  10129. // MORE - some of this should be done in factory
  10130. unsigned joinFlags = helper.getJoinFlags();
  10131. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10132. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10133. exclude = (joinFlags & JFexclude) != 0;
  10134. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10135. getLimitType(joinFlags, limitFail, limitOnFail);
  10136. if (joinFlags & JFslidingmatch)
  10137. {
  10138. betweenjoin = true;
  10139. collate = helper.queryCompareLeftRightLower();
  10140. collateupper = helper.queryCompareLeftRightUpper();
  10141. }
  10142. else
  10143. {
  10144. betweenjoin = false;
  10145. collate = collateupper = helper.queryCompareLeftRight();
  10146. }
  10147. rightIndex = 0;
  10148. state = JSfill;
  10149. matchedLeft = false;
  10150. joinLimit = 0;
  10151. keepLimit = 0; // wait until ctx available
  10152. atmostLimit = 0; // wait until ctx available
  10153. abortLimit = 0; // wait until ctx available
  10154. atmostsTriggered = 0;
  10155. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10156. left = NULL;
  10157. pendingRight = NULL;
  10158. activityKind = _factory->getKind();
  10159. }
  10160. virtual bool needsAllocator() const { return true; }
  10161. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10162. {
  10163. left = NULL;
  10164. rightIndex = 0;
  10165. state = JSfill;
  10166. matchedLeft = false;
  10167. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10168. keepLimit = helper.getKeepLimit();
  10169. if (keepLimit == 0)
  10170. keepLimit = (unsigned)-1;
  10171. atmostsTriggered = 0;
  10172. atmostLimit = helper.getJoinLimit();
  10173. if(atmostLimit == 0)
  10174. atmostLimit = (unsigned)-1;
  10175. else
  10176. assertex(!rightOuterJoin && !betweenjoin);
  10177. abortLimit = helper.getMatchAbortLimit();
  10178. if (abortLimit == 0)
  10179. abortLimit = (unsigned)-1;
  10180. if (rightOuterJoin)
  10181. createDefaultLeft();
  10182. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10183. createDefaultRight();
  10184. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10185. { //limited match join (s[1..n])
  10186. limitedhelper.setown(createRHLimitedCompareHelper());
  10187. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10188. }
  10189. }
  10190. virtual void reset()
  10191. {
  10192. if (atmostsTriggered)
  10193. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  10194. right.clear();
  10195. ReleaseClearRoxieRow(left);
  10196. ReleaseClearRoxieRow(pendingRight);
  10197. defaultRight.clear();
  10198. defaultLeft.clear();
  10199. CRoxieServerTwoInputActivity::reset();
  10200. }
  10201. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10202. {
  10203. switch(idx)
  10204. {
  10205. case 0:
  10206. if ((helper.getJoinFlags() & JFparallel) != 0)
  10207. {
  10208. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10209. puller->setInput(0, _in);
  10210. _in = puller;
  10211. }
  10212. input = _in;
  10213. break;
  10214. case 1:
  10215. input1 = _in;
  10216. break;
  10217. default:
  10218. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10219. }
  10220. }
  10221. virtual IRoxieInput *queryOutput(unsigned idx)
  10222. {
  10223. if (idx==(unsigned)-1)
  10224. idx = 0;
  10225. return idx ? NULL : this;
  10226. }
  10227. void fillLeft()
  10228. {
  10229. matchedLeft = false;
  10230. left = input->nextInGroup();
  10231. if (!left)
  10232. left = input->nextInGroup();
  10233. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10234. fillRight();
  10235. if (limitedhelper && 0==rightIndex)
  10236. {
  10237. rightIndex = 0;
  10238. right.clear();
  10239. matchedRight.kill();
  10240. if (left)
  10241. {
  10242. limitedhelper->getGroup(right,left);
  10243. ForEachItemIn(idx, right)
  10244. matchedRight.append(false);
  10245. }
  10246. }
  10247. }
  10248. void fillRight()
  10249. {
  10250. if (limitedhelper)
  10251. return;
  10252. failingLimit.clear();
  10253. if(betweenjoin && left)
  10254. {
  10255. aindex_t start = 0;
  10256. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10257. start++;
  10258. if(start>0)
  10259. right.clearPart(0, start);
  10260. }
  10261. else
  10262. right.clear();
  10263. rightIndex = 0;
  10264. unsigned groupCount = 0;
  10265. const void * next;
  10266. while(true)
  10267. {
  10268. if(pendingRight)
  10269. {
  10270. next = pendingRight;
  10271. pendingRight = NULL;
  10272. }
  10273. else
  10274. {
  10275. next = input1->nextInGroup();
  10276. }
  10277. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10278. {
  10279. while(next)
  10280. {
  10281. ReleaseClearRoxieRow(next);
  10282. next = input1->nextInGroup();
  10283. }
  10284. continue;
  10285. }
  10286. while(next)
  10287. {
  10288. if(groupCount==abortLimit)
  10289. {
  10290. if(limitFail)
  10291. failLimit();
  10292. if (ctx->queryDebugContext())
  10293. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10294. if(limitOnFail)
  10295. {
  10296. assertex(!failingLimit);
  10297. try
  10298. {
  10299. failLimit();
  10300. }
  10301. catch(IException * except)
  10302. {
  10303. failingLimit.setown(except);
  10304. }
  10305. assertex(failingLimit != NULL);
  10306. }
  10307. right.append(next);
  10308. do
  10309. {
  10310. next = input1->nextInGroup();
  10311. ReleaseRoxieRow(next);
  10312. } while(next);
  10313. break;
  10314. }
  10315. else if(groupCount==atmostLimit)
  10316. {
  10317. atmostsTriggered++;
  10318. right.clear();
  10319. groupCount = 0;
  10320. while(next)
  10321. {
  10322. ReleaseRoxieRow(next);
  10323. next = input1->nextInGroup();
  10324. }
  10325. }
  10326. else
  10327. {
  10328. right.append(next);
  10329. groupCount++;
  10330. }
  10331. next = input1->nextInGroup();
  10332. }
  10333. // 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
  10334. if(betweenjoin && left)
  10335. {
  10336. pendingRight = input1->nextInGroup();
  10337. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10338. break;
  10339. }
  10340. else
  10341. break;
  10342. }
  10343. matchedRight.kill();
  10344. ForEachItemIn(idx, right)
  10345. matchedRight.append(false);
  10346. }
  10347. const void * joinRecords(const void * curLeft, const void * curRight)
  10348. {
  10349. if (cloneLeft)
  10350. {
  10351. LinkRoxieRow(curLeft);
  10352. return curLeft;
  10353. }
  10354. try
  10355. {
  10356. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10357. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight);
  10358. if (thisSize)
  10359. return rowBuilder.finalizeRowClear(thisSize);
  10360. else
  10361. return NULL;
  10362. }
  10363. catch (IException *E)
  10364. {
  10365. throw makeWrappedException(E);
  10366. }
  10367. }
  10368. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10369. {
  10370. try
  10371. {
  10372. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10373. unsigned numRows = rows.ordinality();
  10374. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10375. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10376. if (thisSize)
  10377. return rowBuilder.finalizeRowClear(thisSize);
  10378. else
  10379. return NULL;
  10380. }
  10381. catch (IException *E)
  10382. {
  10383. throw makeWrappedException(E);
  10384. }
  10385. }
  10386. const void * joinException(const void * curLeft, IException * except)
  10387. {
  10388. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10389. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10390. return rowBuilder.finalizeRowClear(thisSize);
  10391. }
  10392. void failLimit()
  10393. {
  10394. helper.onMatchAbortLimitExceeded();
  10395. CommonXmlWriter xmlwrite(0);
  10396. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10397. {
  10398. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10399. }
  10400. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10401. }
  10402. virtual const void * nextInGroup()
  10403. {
  10404. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10405. loop
  10406. {
  10407. switch (state)
  10408. {
  10409. case JSfill:
  10410. fillLeft();
  10411. state = JSfillright;
  10412. break;
  10413. case JSfillright:
  10414. fillRight();
  10415. state = JScollate;
  10416. break;
  10417. case JSfillleft:
  10418. fillLeft();
  10419. state = JScollate;
  10420. break;
  10421. case JScollate:
  10422. if (right.ordinality() == 0)
  10423. {
  10424. if (left == NULL)
  10425. return NULL;
  10426. state = JSleftonly;
  10427. }
  10428. else
  10429. {
  10430. if (!left)
  10431. state = JSrightonly;
  10432. else
  10433. {
  10434. int diff;
  10435. if(betweenjoin)
  10436. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10437. else
  10438. diff = collate->docompare(left, right.item(0));
  10439. bool limitExceeded = right.ordinality()>abortLimit;
  10440. if (diff == 0)
  10441. {
  10442. if (limitExceeded)
  10443. {
  10444. const void * ret = NULL;
  10445. if(failingLimit)
  10446. ret = joinException(left, failingLimit);
  10447. ReleaseRoxieRow(left);
  10448. left = NULL;
  10449. state = JSfillleft;
  10450. ForEachItemIn(idx, right)
  10451. matchedRight.replace(true, idx);
  10452. if(ret)
  10453. {
  10454. processed++;
  10455. return ret;
  10456. }
  10457. }
  10458. else
  10459. {
  10460. state = JScompare;
  10461. joinLimit = keepLimit;
  10462. }
  10463. }
  10464. else if (diff < 0)
  10465. state = JSleftonly;
  10466. else if (limitExceeded)
  10467. {
  10468. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10469. state = JSfillright;
  10470. }
  10471. else
  10472. state = JSrightonly;
  10473. }
  10474. }
  10475. break;
  10476. case JSrightonly:
  10477. if (rightOuterJoin)
  10478. {
  10479. switch (activityKind)
  10480. {
  10481. case TAKjoin:
  10482. {
  10483. while (right.isItem(rightIndex))
  10484. {
  10485. if (!matchedRight.item(rightIndex))
  10486. {
  10487. const void * rhs = right.item(rightIndex++);
  10488. const void *ret = joinRecords(defaultLeft, rhs);
  10489. if (ret)
  10490. {
  10491. processed++;
  10492. return ret;
  10493. }
  10494. }
  10495. rightIndex++;
  10496. }
  10497. break;
  10498. }
  10499. //Probably excessive to implement the following, but possibly useful
  10500. case TAKdenormalize:
  10501. {
  10502. OwnedConstRoxieRow newLeft;
  10503. newLeft.set(defaultLeft);
  10504. unsigned rowSize = 0;
  10505. unsigned leftCount = 0;
  10506. while (right.isItem(rightIndex))
  10507. {
  10508. if (!matchedRight.item(rightIndex))
  10509. {
  10510. const void * rhs = right.item(rightIndex);
  10511. try
  10512. {
  10513. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10514. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10515. if (thisSize)
  10516. {
  10517. rowSize = thisSize;
  10518. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10519. }
  10520. }
  10521. catch (IException *E)
  10522. {
  10523. throw makeWrappedException(E);
  10524. }
  10525. }
  10526. rightIndex++;
  10527. }
  10528. state = JSfillright;
  10529. if (rowSize)
  10530. {
  10531. processed++;
  10532. return newLeft.getClear();
  10533. }
  10534. break;
  10535. }
  10536. case TAKdenormalizegroup:
  10537. {
  10538. filteredRight.kill();
  10539. while (right.isItem(rightIndex))
  10540. {
  10541. if (!matchedRight.item(rightIndex))
  10542. filteredRight.append(right.item(rightIndex));
  10543. rightIndex++;
  10544. }
  10545. state = JSfillright;
  10546. if (filteredRight.ordinality())
  10547. {
  10548. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10549. filteredRight.kill();
  10550. if (ret)
  10551. {
  10552. processed++;
  10553. return ret;
  10554. }
  10555. }
  10556. break;
  10557. }
  10558. }
  10559. }
  10560. state = JSfillright;
  10561. break;
  10562. case JSleftonly:
  10563. {
  10564. const void * ret = NULL;
  10565. if (!matchedLeft && leftOuterJoin)
  10566. {
  10567. switch (activityKind)
  10568. {
  10569. case TAKjoin:
  10570. ret = joinRecords(left, defaultRight);
  10571. break;
  10572. case TAKdenormalize:
  10573. ret = left;
  10574. left = NULL;
  10575. break;
  10576. case TAKdenormalizegroup:
  10577. filteredRight.kill();
  10578. ret = denormalizeRecords(left, filteredRight);
  10579. break;
  10580. }
  10581. }
  10582. ReleaseRoxieRow(left);
  10583. left = NULL;
  10584. state = JSfillleft;
  10585. if (ret)
  10586. {
  10587. processed++;
  10588. return ret;
  10589. }
  10590. break;
  10591. }
  10592. case JScompare:
  10593. if (joinLimit != 0)
  10594. {
  10595. switch (activityKind)
  10596. {
  10597. case TAKjoin:
  10598. {
  10599. while (right.isItem(rightIndex))
  10600. {
  10601. const void * rhs = right.item(rightIndex++);
  10602. if (helper.match(left, rhs))
  10603. {
  10604. matchedRight.replace(true, rightIndex-1);
  10605. matchedLeft = true;
  10606. if (!exclude)
  10607. {
  10608. const void *ret = joinRecords(left, rhs);
  10609. if (ret)
  10610. {
  10611. processed++;
  10612. joinLimit--;
  10613. return ret;
  10614. }
  10615. }
  10616. }
  10617. }
  10618. break;
  10619. }
  10620. case TAKdenormalize:
  10621. {
  10622. OwnedConstRoxieRow newLeft;
  10623. newLeft.set(left);
  10624. unsigned rowSize = 0;
  10625. unsigned leftCount = 0;
  10626. while (right.isItem(rightIndex) && joinLimit)
  10627. {
  10628. try
  10629. {
  10630. const void * rhs = right.item(rightIndex++);
  10631. if (helper.match(left, rhs))
  10632. {
  10633. matchedRight.replace(true, rightIndex-1);
  10634. matchedLeft = true;
  10635. if (!exclude)
  10636. {
  10637. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10638. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10639. if (thisSize)
  10640. {
  10641. rowSize = thisSize;
  10642. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10643. joinLimit--;
  10644. }
  10645. }
  10646. }
  10647. }
  10648. catch (IException *E)
  10649. {
  10650. throw makeWrappedException(E);
  10651. }
  10652. }
  10653. state = JSleftonly;
  10654. rightIndex = 0;
  10655. if (rowSize)
  10656. {
  10657. processed++;
  10658. return newLeft.getClear();
  10659. }
  10660. break;
  10661. }
  10662. case TAKdenormalizegroup:
  10663. {
  10664. filteredRight.kill();
  10665. while (right.isItem(rightIndex))
  10666. {
  10667. const void * rhs = right.item(rightIndex++);
  10668. if (helper.match(left, rhs))
  10669. {
  10670. matchedRight.replace(true, rightIndex-1);
  10671. filteredRight.append(rhs);
  10672. matchedLeft = true;
  10673. if (filteredRight.ordinality()==joinLimit)
  10674. break;
  10675. }
  10676. }
  10677. state = JSleftonly;
  10678. rightIndex = 0;
  10679. if (!exclude && filteredRight.ordinality())
  10680. {
  10681. const void * ret = denormalizeRecords(left, filteredRight);
  10682. filteredRight.kill();
  10683. if (ret)
  10684. {
  10685. processed++;
  10686. return ret;
  10687. }
  10688. }
  10689. break;
  10690. }
  10691. }
  10692. }
  10693. state = JSleftonly;
  10694. rightIndex = 0;
  10695. break;
  10696. }
  10697. }
  10698. }
  10699. };
  10700. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  10701. {
  10702. unsigned input2;
  10703. unsigned input2idx;
  10704. public:
  10705. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10706. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10707. {
  10708. input2 = 0;
  10709. input2idx = 0;
  10710. }
  10711. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10712. {
  10713. return new CRoxieServerJoinActivity(this, _probeManager);
  10714. }
  10715. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  10716. {
  10717. if (idx==1)
  10718. {
  10719. input2 = source;
  10720. input2idx = sourceidx;
  10721. }
  10722. else
  10723. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  10724. }
  10725. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  10726. {
  10727. switch (idx)
  10728. {
  10729. case 1:
  10730. sourceidx = input2idx;
  10731. return input2;
  10732. case 0:
  10733. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  10734. default:
  10735. return (unsigned) -1;
  10736. }
  10737. }
  10738. virtual unsigned numInputs() const { return 2; }
  10739. };
  10740. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10741. {
  10742. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  10743. }
  10744. //=================================================================================
  10745. #define CONCAT_READAHEAD 1000
  10746. MAKEPointerArray(RecordPullerThread, RecordPullerArray);
  10747. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  10748. {
  10749. QueueOf<const void, true> buffer;
  10750. InterruptableSemaphore ready;
  10751. InterruptableSemaphore space;
  10752. CriticalSection crit;
  10753. unsigned eofs;
  10754. RecordPullerArray pullers;
  10755. unsigned numInputs;
  10756. public:
  10757. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  10758. : CRoxieServerActivity(_factory, _probeManager)
  10759. {
  10760. eofs = 0;
  10761. numInputs = _numInputs;
  10762. for (unsigned i = 0; i < numInputs; i++)
  10763. pullers.append(*new RecordPullerThread(_grouped));
  10764. }
  10765. ~CRoxieServerThreadedConcatActivity()
  10766. {
  10767. ForEachItemIn(idx, pullers)
  10768. delete &pullers.item(idx);
  10769. }
  10770. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10771. {
  10772. space.reinit(CONCAT_READAHEAD);
  10773. ready.reinit();
  10774. eofs = 0;
  10775. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10776. ForEachItemIn(idx, pullers)
  10777. {
  10778. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx->concatPreload(), false, ctx);
  10779. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  10780. // in the part of the subgraph that the thread uses has been started.
  10781. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  10782. }
  10783. }
  10784. virtual void stop(bool aborting)
  10785. {
  10786. space.interrupt();
  10787. ready.interrupt();
  10788. ForEachItemIn(idx, pullers)
  10789. pullers.item(idx).stop(aborting);
  10790. CRoxieServerActivity::stop(aborting);
  10791. }
  10792. virtual unsigned __int64 queryLocalCycles() const
  10793. {
  10794. return 0;
  10795. }
  10796. virtual IRoxieInput *queryInput(unsigned idx) const
  10797. {
  10798. if (pullers.isItem(idx))
  10799. return pullers.item(idx).queryInput();
  10800. else
  10801. return NULL;
  10802. }
  10803. virtual void reset()
  10804. {
  10805. CRoxieServerActivity::reset();
  10806. ForEachItemIn(idx, pullers)
  10807. pullers.item(idx).reset();
  10808. ForEachItemIn(idx1, buffer)
  10809. ReleaseRoxieRow(buffer.item(idx1));
  10810. buffer.clear();
  10811. }
  10812. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10813. {
  10814. if (pullers.isItem(idx))
  10815. pullers.item(idx).setInput(this, _in);
  10816. else
  10817. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10818. }
  10819. virtual const void * nextInGroup()
  10820. {
  10821. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10822. loop
  10823. {
  10824. {
  10825. CriticalBlock b(crit);
  10826. if (eofs==numInputs && !buffer.ordinality())
  10827. return NULL; // eof
  10828. }
  10829. ready.wait();
  10830. const void *ret;
  10831. {
  10832. CriticalBlock b(crit);
  10833. ret = buffer.dequeue();
  10834. }
  10835. if (ret)
  10836. processed++;
  10837. space.signal();
  10838. return ret;
  10839. }
  10840. }
  10841. virtual bool fireException(IException *e)
  10842. {
  10843. // called from puller thread on failure
  10844. ready.interrupt(LINK(e));
  10845. space.interrupt(e);
  10846. return true;
  10847. }
  10848. virtual void processRow(const void *row)
  10849. {
  10850. {
  10851. CriticalBlock b(crit);
  10852. buffer.enqueue(row);
  10853. }
  10854. ready.signal();
  10855. space.wait();
  10856. }
  10857. virtual void processGroup(const ConstPointerArray &rows)
  10858. {
  10859. // NOTE - a bit bizzare in that it waits for the space AFTER using it.
  10860. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  10861. // if group was larger than max(space)
  10862. {
  10863. CriticalBlock b(crit);
  10864. ForEachItemIn(idx, rows)
  10865. buffer.enqueue(rows.item(idx));
  10866. buffer.enqueue(NULL);
  10867. }
  10868. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  10869. {
  10870. ready.signal();
  10871. space.wait();
  10872. }
  10873. }
  10874. virtual void processEOG()
  10875. {
  10876. // Used when output is not grouped - just ignore
  10877. }
  10878. virtual void processDone()
  10879. {
  10880. CriticalBlock b(crit);
  10881. eofs++;
  10882. if (eofs == numInputs)
  10883. ready.signal();
  10884. }
  10885. };
  10886. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  10887. {
  10888. IRoxieInput *curInput;
  10889. bool eogSeen;
  10890. bool anyThisGroup;
  10891. bool grouped;
  10892. unsigned numInputs;
  10893. unsigned inputIdx;
  10894. IRoxieInput **inputArray;
  10895. public:
  10896. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  10897. : CRoxieServerActivity(_factory, _probeManager)
  10898. {
  10899. eogSeen = false;
  10900. anyThisGroup = false;
  10901. grouped = _grouped;
  10902. numInputs = _numInputs;
  10903. inputIdx = 0;
  10904. inputArray = new IRoxieInput*[numInputs];
  10905. for (unsigned i = 0; i < numInputs; i++)
  10906. inputArray[i] = NULL;
  10907. }
  10908. ~CRoxieServerOrderedConcatActivity()
  10909. {
  10910. delete [] inputArray;
  10911. }
  10912. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10913. {
  10914. inputIdx = 0;
  10915. curInput = inputArray[inputIdx];
  10916. eogSeen = false;
  10917. anyThisGroup = false;
  10918. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10919. for (unsigned i = 0; i < numInputs; i++)
  10920. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  10921. }
  10922. virtual void stop(bool aborting)
  10923. {
  10924. for (unsigned i = 0; i < numInputs; i++)
  10925. inputArray[i]->stop(aborting);
  10926. CRoxieServerActivity::stop(aborting);
  10927. }
  10928. virtual unsigned __int64 queryLocalCycles() const
  10929. {
  10930. return 0;
  10931. }
  10932. virtual IRoxieInput *queryInput(unsigned idx) const
  10933. {
  10934. if (idx < numInputs)
  10935. return inputArray[idx];
  10936. else
  10937. return NULL;
  10938. }
  10939. virtual void reset()
  10940. {
  10941. CRoxieServerActivity::reset();
  10942. for (unsigned i = 0; i < numInputs; i++)
  10943. inputArray[i]->reset();
  10944. }
  10945. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10946. {
  10947. inputArray[idx] = _in;
  10948. }
  10949. virtual const void * nextInGroup()
  10950. {
  10951. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10952. if (!curInput)
  10953. return NULL; // eof
  10954. const void * next = curInput->nextInGroup();
  10955. if (next)
  10956. {
  10957. anyThisGroup = true;
  10958. eogSeen = false;
  10959. processed++;
  10960. return next;
  10961. }
  10962. else if (!eogSeen)
  10963. {
  10964. eogSeen = true;
  10965. if (grouped)
  10966. {
  10967. if (anyThisGroup)
  10968. {
  10969. anyThisGroup = false;
  10970. return NULL;
  10971. }
  10972. else
  10973. return nextInGroup();
  10974. }
  10975. else
  10976. return nextInGroup();
  10977. }
  10978. else if (inputIdx < numInputs-1)
  10979. {
  10980. inputIdx++;
  10981. curInput = inputArray[inputIdx];
  10982. eogSeen = false;
  10983. return nextInGroup();
  10984. }
  10985. else
  10986. {
  10987. curInput = NULL;
  10988. return NULL;
  10989. }
  10990. }
  10991. };
  10992. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  10993. {
  10994. bool ordered;
  10995. bool grouped;
  10996. public:
  10997. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10998. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10999. {
  11000. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11001. ordered = helper->isOrdered();
  11002. grouped = helper->queryOutputMeta()->isGrouped();
  11003. }
  11004. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11005. {
  11006. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11007. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11008. else
  11009. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11010. }
  11011. };
  11012. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11013. {
  11014. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11015. }
  11016. //=================================================================================
  11017. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11018. {
  11019. IRoxieInput * selectedInput;
  11020. unsigned savedParentExtractSize;
  11021. const byte * savedParentExtract;
  11022. bool foundInput;
  11023. public:
  11024. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11025. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11026. {
  11027. foundInput = false;
  11028. selectedInput = NULL;
  11029. savedParentExtractSize = 0;;
  11030. savedParentExtract = NULL;
  11031. }
  11032. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11033. {
  11034. //Don't start the inputs yet so we can short-circuit...
  11035. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11036. savedParentExtractSize = parentExtractSize;
  11037. savedParentExtract = parentExtract;
  11038. }
  11039. virtual void stop(bool aborting)
  11040. {
  11041. if (foundInput)
  11042. {
  11043. if (selectedInput)
  11044. selectedInput->stop(aborting);
  11045. }
  11046. else
  11047. {
  11048. for (unsigned i = 0; i < numInputs; i++)
  11049. inputArray[i]->stop(aborting);
  11050. }
  11051. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11052. }
  11053. virtual void reset()
  11054. {
  11055. CRoxieServerMultiInputBaseActivity::reset();
  11056. foundInput = false;
  11057. selectedInput = NULL;
  11058. }
  11059. virtual unsigned __int64 queryLocalCycles() const
  11060. {
  11061. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11062. }
  11063. virtual const void * nextInGroup()
  11064. {
  11065. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11066. if (!foundInput)
  11067. {
  11068. foundInput = true;
  11069. //If we get an exception in this loop then stop() will stop any started inputs
  11070. for (unsigned i=0; i < numInputs; i++)
  11071. {
  11072. selectedInput = inputArray[i];
  11073. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11074. const void * next = selectedInput->nextInGroup();
  11075. if (next)
  11076. {
  11077. //Found a row so stop remaining
  11078. for (unsigned j=i+1; j < numInputs; j++)
  11079. inputArray[j]->stop(false);
  11080. processed++;
  11081. return next;
  11082. }
  11083. selectedInput->stop(false);
  11084. }
  11085. selectedInput = NULL;
  11086. return NULL;
  11087. }
  11088. if (!selectedInput)
  11089. return NULL;
  11090. const void * next = selectedInput->nextInGroup();
  11091. if (next)
  11092. processed++;
  11093. return next;
  11094. }
  11095. };
  11096. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11097. {
  11098. public:
  11099. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11100. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11101. {
  11102. }
  11103. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11104. {
  11105. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11106. }
  11107. };
  11108. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11109. {
  11110. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11111. }
  11112. //=================================================================================
  11113. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11114. {
  11115. IHThorMergeArg &helper;
  11116. unsigned *mergeheap;
  11117. unsigned activeInputs;
  11118. unsigned numInputs;
  11119. IRoxieInput **inputArray;
  11120. const void **pending;
  11121. bool first;
  11122. ICompare *compare;
  11123. bool dedup;
  11124. void permute()
  11125. {
  11126. assertex(activeInputs == 0);
  11127. for(unsigned i = 0; i < numInputs; i++)
  11128. if(pullInput(i))
  11129. mergeheap[activeInputs++] = i;
  11130. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11131. // the heap property: no element should be smaller than its parent
  11132. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11133. // 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
  11134. if (activeInputs >= 2)
  11135. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11136. siftDown(p);
  11137. if(dedup)
  11138. siftDownDedupTop();
  11139. else
  11140. siftDown(0);
  11141. }
  11142. void readNext()
  11143. {
  11144. if(!pullInput(mergeheap[0]))
  11145. if(!promote(0))
  11146. return;
  11147. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11148. if(dedup)
  11149. siftDownDedupTop();
  11150. else
  11151. siftDown(0);
  11152. }
  11153. bool pullInput(unsigned i)
  11154. {
  11155. const void *next = inputArray[i]->nextInGroup();
  11156. if (!next)
  11157. next = inputArray[i]->nextInGroup();
  11158. pending[i] = next;
  11159. return (next != NULL);
  11160. }
  11161. bool promote(unsigned p)
  11162. {
  11163. activeInputs--;
  11164. if(activeInputs == p)
  11165. return false;
  11166. mergeheap[p] = mergeheap[activeInputs];
  11167. return true;
  11168. }
  11169. bool siftDown(unsigned p)
  11170. {
  11171. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11172. bool nochange = true;
  11173. while(1)
  11174. {
  11175. unsigned c = p*2 + 1;
  11176. if(c >= activeInputs)
  11177. return nochange;
  11178. if(c+1 < activeInputs)
  11179. {
  11180. int childcmp = BuffCompare(c+1, c);
  11181. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11182. ++c;
  11183. }
  11184. int cmp = BuffCompare(c, p);
  11185. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11186. return nochange;
  11187. nochange = false;
  11188. unsigned r = mergeheap[c];
  11189. mergeheap[c] = mergeheap[p];
  11190. mergeheap[p] = r;
  11191. p = c;
  11192. }
  11193. }
  11194. void siftDownDedupTop()
  11195. {
  11196. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11197. if(activeInputs < 2)
  11198. return;
  11199. unsigned c = 1;
  11200. int childcmp = 1;
  11201. if(activeInputs >= 3)
  11202. {
  11203. childcmp = BuffCompare(2, 1);
  11204. if(childcmp < 0)
  11205. c = 2;
  11206. }
  11207. int cmp = BuffCompare(c, 0);
  11208. if(cmp > 0)
  11209. return;
  11210. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11211. while(cmp <= 0)
  11212. {
  11213. if(cmp == 0)
  11214. {
  11215. if(mergeheap[c] < mergeheap[0])
  11216. {
  11217. unsigned r = mergeheap[c];
  11218. mergeheap[c] = mergeheap[0];
  11219. mergeheap[0] = r;
  11220. }
  11221. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11222. if(!pullInput(mergeheap[c]))
  11223. if(!promote(c))
  11224. break;
  11225. siftDown(c);
  11226. }
  11227. else
  11228. {
  11229. unsigned r = mergeheap[c];
  11230. mergeheap[c] = mergeheap[0];
  11231. mergeheap[0] = r;
  11232. if(siftDown(c))
  11233. break;
  11234. }
  11235. cmp = BuffCompare(c, 0);
  11236. }
  11237. // the following loop ensures the uniqueness property holds on the other branch too
  11238. c = 3-c;
  11239. if(activeInputs <= c)
  11240. return;
  11241. while(childcmp == 0)
  11242. {
  11243. if(mergeheap[c] < mergeheap[0])
  11244. {
  11245. unsigned r = mergeheap[c];
  11246. mergeheap[c] = mergeheap[0];
  11247. mergeheap[0] = r;
  11248. }
  11249. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11250. if(!pullInput(mergeheap[c]))
  11251. if(!promote(c))
  11252. break;
  11253. siftDown(c);
  11254. childcmp = BuffCompare(c, 0);
  11255. }
  11256. }
  11257. inline int BuffCompare(unsigned a, unsigned b)
  11258. {
  11259. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11260. }
  11261. public:
  11262. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11263. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11264. {
  11265. activeInputs = 0;
  11266. first = true;
  11267. mergeheap = new unsigned[numInputs];
  11268. inputArray = new IRoxieInput*[numInputs];
  11269. pending = new const void *[numInputs];
  11270. compare = helper.queryCompare();
  11271. dedup = helper.dedup();
  11272. for (unsigned i = 0; i < numInputs; i++)
  11273. {
  11274. inputArray[i] = NULL;
  11275. pending[i] = NULL;
  11276. }
  11277. }
  11278. ~CRoxieServerMergeActivity()
  11279. {
  11280. delete [] mergeheap;
  11281. delete [] inputArray;
  11282. delete [] pending;
  11283. }
  11284. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11285. {
  11286. activeInputs = 0;
  11287. first = true;
  11288. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11289. for (unsigned i = 0; i < numInputs; i++)
  11290. {
  11291. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11292. }
  11293. }
  11294. virtual void stop(bool aborting)
  11295. {
  11296. for (unsigned i = 0; i < numInputs; i++)
  11297. {
  11298. inputArray[i]->stop(aborting);
  11299. }
  11300. CRoxieServerActivity::stop(aborting);
  11301. }
  11302. virtual void reset()
  11303. {
  11304. for (unsigned i = 0; i < numInputs; i++)
  11305. {
  11306. ReleaseClearRoxieRow(pending[i]);
  11307. inputArray[i]->reset();
  11308. }
  11309. CRoxieServerActivity::reset();
  11310. }
  11311. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11312. {
  11313. inputArray[idx] = _in;
  11314. }
  11315. virtual const void * nextInGroup()
  11316. {
  11317. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11318. if (first)
  11319. {
  11320. permute();
  11321. first = false;
  11322. }
  11323. if (activeInputs)
  11324. {
  11325. const void *next = pending[mergeheap[0]];
  11326. readNext();
  11327. if (next)
  11328. processed++;
  11329. return next;
  11330. }
  11331. else
  11332. return NULL;
  11333. }
  11334. };
  11335. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11336. {
  11337. public:
  11338. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11339. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11340. {
  11341. }
  11342. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11343. {
  11344. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11345. }
  11346. };
  11347. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11348. {
  11349. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11350. }
  11351. //=================================================================================
  11352. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11353. {
  11354. IHThorRegroupArg &helper;
  11355. unsigned inputIndex;
  11356. bool eof;
  11357. unsigned __int64 numProcessedLastGroup;
  11358. public:
  11359. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11360. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11361. {
  11362. inputIndex = 0;
  11363. eof = false;
  11364. numProcessedLastGroup = 0;
  11365. }
  11366. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11367. {
  11368. inputIndex = 0;
  11369. eof = false;
  11370. numProcessedLastGroup = processed;
  11371. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11372. }
  11373. const void * nextFromInputs()
  11374. {
  11375. unsigned initialInput = inputIndex;
  11376. while (inputIndex < numInputs)
  11377. {
  11378. const void * next = inputArray[inputIndex]->nextInGroup();
  11379. if (next)
  11380. {
  11381. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11382. {
  11383. ReleaseRoxieRow(next);
  11384. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11385. }
  11386. return next;
  11387. }
  11388. inputIndex++;
  11389. }
  11390. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11391. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11392. inputIndex = 0;
  11393. return NULL;
  11394. }
  11395. virtual const void * nextInGroup()
  11396. {
  11397. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11398. if (eof)
  11399. return NULL;
  11400. const void * ret = nextFromInputs();
  11401. if (ret)
  11402. {
  11403. processed++;
  11404. return ret;
  11405. }
  11406. if (numProcessedLastGroup != processed)
  11407. {
  11408. numProcessedLastGroup = processed;
  11409. return NULL;
  11410. }
  11411. eof = true;
  11412. return NULL;
  11413. }
  11414. #if 0
  11415. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11416. {
  11417. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11418. if (idx)
  11419. {
  11420. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11421. puller->setInput(0, _in);
  11422. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11423. }
  11424. else
  11425. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11426. }
  11427. #endif
  11428. };
  11429. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11430. {
  11431. public:
  11432. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11433. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11434. {
  11435. }
  11436. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11437. {
  11438. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11439. }
  11440. };
  11441. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11442. {
  11443. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11444. }
  11445. //=================================================================================
  11446. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11447. {
  11448. IHThorCombineArg &helper;
  11449. unsigned __int64 numProcessedLastGroup;
  11450. public:
  11451. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11452. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11453. {
  11454. numProcessedLastGroup = 0;
  11455. }
  11456. ~CRoxieServerCombineActivity()
  11457. {
  11458. }
  11459. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11460. {
  11461. numProcessedLastGroup = processed;
  11462. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11463. }
  11464. void nextInputs(ConstPointerArray & out)
  11465. {
  11466. for (unsigned i=0; i < numInputs; i++)
  11467. {
  11468. const void * next = inputArray[i]->nextInGroup();
  11469. if (next)
  11470. out.append(next);
  11471. }
  11472. }
  11473. virtual bool needsAllocator() const { return true; }
  11474. virtual const void * nextInGroup()
  11475. {
  11476. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11477. loop
  11478. {
  11479. ConstPointerArray group;
  11480. nextInputs(group);
  11481. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11482. nextInputs(group);
  11483. if (group.ordinality() == 0)
  11484. {
  11485. numProcessedLastGroup = processed;
  11486. return NULL;
  11487. }
  11488. else if (group.ordinality() != numInputs)
  11489. {
  11490. ReleaseRoxieRowSet(group);
  11491. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11492. }
  11493. try
  11494. {
  11495. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11496. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11497. ReleaseRoxieRowSet(group);
  11498. if (outSize)
  11499. {
  11500. processed++;
  11501. return rowBuilder.finalizeRowClear(outSize);
  11502. }
  11503. }
  11504. catch (IException *E)
  11505. {
  11506. ReleaseRoxieRowSet(group);
  11507. throw makeWrappedException(E);
  11508. }
  11509. }
  11510. }
  11511. };
  11512. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11513. {
  11514. public:
  11515. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11516. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11517. {
  11518. }
  11519. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11520. {
  11521. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11522. }
  11523. };
  11524. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11525. {
  11526. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11527. }
  11528. //=================================================================================
  11529. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  11530. {
  11531. IHThorCombineGroupArg &helper;
  11532. unsigned __int64 numProcessedLastGroup;
  11533. public:
  11534. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11535. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  11536. {
  11537. numProcessedLastGroup = 0;
  11538. }
  11539. ~CRoxieServerCombineGroupActivity()
  11540. {
  11541. }
  11542. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11543. {
  11544. numProcessedLastGroup = processed;
  11545. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11546. }
  11547. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11548. {
  11549. switch(idx)
  11550. {
  11551. case 0:
  11552. #if 0
  11553. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11554. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11555. puller->setInput(0, _in);
  11556. _in = puller;
  11557. #endif
  11558. input = _in;
  11559. break;
  11560. case 1:
  11561. input1 = _in;
  11562. break;
  11563. default:
  11564. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11565. }
  11566. }
  11567. virtual IRoxieInput *queryOutput(unsigned idx)
  11568. {
  11569. if (idx==(unsigned)-1)
  11570. idx = 0;
  11571. return idx ? NULL : this;
  11572. }
  11573. virtual bool needsAllocator() const { return true; }
  11574. virtual const void * nextInGroup()
  11575. {
  11576. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11577. loop
  11578. {
  11579. const void * left = input->nextInGroup();
  11580. if (!left && (numProcessedLastGroup == processed))
  11581. left = input->nextInGroup();
  11582. if (!left)
  11583. {
  11584. if (numProcessedLastGroup == processed)
  11585. {
  11586. const void * nextRight = input1->nextInGroup();
  11587. if (nextRight)
  11588. {
  11589. ReleaseRoxieRow(nextRight);
  11590. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  11591. }
  11592. }
  11593. else
  11594. numProcessedLastGroup = processed;
  11595. return NULL;
  11596. }
  11597. ConstPointerArray group;
  11598. loop
  11599. {
  11600. const void * in = input1->nextInGroup();
  11601. if (!in)
  11602. break;
  11603. group.append(in);
  11604. }
  11605. if (group.ordinality() == 0)
  11606. {
  11607. ReleaseRoxieRow(left);
  11608. ReleaseRoxieRowSet(group);
  11609. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  11610. }
  11611. try
  11612. {
  11613. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11614. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  11615. ReleaseRoxieRow(left);
  11616. ReleaseRoxieRowSet(group);
  11617. if (outSize)
  11618. {
  11619. processed++;
  11620. return rowBuilder.finalizeRowClear(outSize);
  11621. }
  11622. }
  11623. catch (IException *E)
  11624. {
  11625. ReleaseRoxieRow(left);
  11626. ReleaseRoxieRowSet(group);
  11627. throw makeWrappedException(E);
  11628. }
  11629. }
  11630. }
  11631. };
  11632. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  11633. {
  11634. unsigned input2;
  11635. unsigned input2idx;
  11636. public:
  11637. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11638. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11639. {
  11640. input2 = 0;
  11641. input2idx = 0;
  11642. }
  11643. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11644. {
  11645. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  11646. }
  11647. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11648. {
  11649. if (idx==1)
  11650. {
  11651. input2 = source;
  11652. input2idx = sourceidx;
  11653. }
  11654. else
  11655. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11656. }
  11657. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11658. {
  11659. switch (idx)
  11660. {
  11661. case 1:
  11662. sourceidx = input2idx;
  11663. return input2;
  11664. case 0:
  11665. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11666. default:
  11667. return (unsigned) -1;
  11668. }
  11669. }
  11670. virtual unsigned numInputs() const { return 2; }
  11671. };
  11672. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11673. {
  11674. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11675. }
  11676. //=================================================================================
  11677. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  11678. {
  11679. IHThorRollupGroupArg &helper;
  11680. bool eof;
  11681. public:
  11682. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11683. : CRoxieServerActivity(_factory, _probeManager),
  11684. helper((IHThorRollupGroupArg &)basehelper)
  11685. {
  11686. eof = false;
  11687. }
  11688. ~CRoxieServerRollupGroupActivity()
  11689. {
  11690. }
  11691. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11692. {
  11693. eof = false;
  11694. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11695. }
  11696. virtual bool needsAllocator() const { return true; }
  11697. virtual const void * nextInGroup()
  11698. {
  11699. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11700. if (eof)
  11701. return NULL;
  11702. loop
  11703. {
  11704. ConstPointerArray group;
  11705. loop
  11706. {
  11707. const void * in = input->nextInGroup();
  11708. if (!in)
  11709. break;
  11710. group.append(in);
  11711. }
  11712. if (group.ordinality() == 0)
  11713. {
  11714. eof = true;
  11715. return NULL;
  11716. }
  11717. try
  11718. {
  11719. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11720. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  11721. ReleaseRoxieRowSet(group);
  11722. if (outSize)
  11723. {
  11724. processed++;
  11725. return rowBuilder.finalizeRowClear(outSize);
  11726. }
  11727. }
  11728. catch (IException * E)
  11729. {
  11730. ReleaseRoxieRowSet(group);
  11731. throw makeWrappedException(E);
  11732. }
  11733. }
  11734. }
  11735. };
  11736. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  11737. {
  11738. public:
  11739. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11740. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11741. {
  11742. }
  11743. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11744. {
  11745. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  11746. }
  11747. };
  11748. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11749. {
  11750. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11751. }
  11752. //=================================================================================
  11753. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  11754. {
  11755. IHThorFilterProjectArg &helper;
  11756. unsigned numProcessedLastGroup;
  11757. unsigned __int64 recordCount;
  11758. public:
  11759. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11760. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  11761. {
  11762. numProcessedLastGroup = 0;
  11763. recordCount = 0;
  11764. }
  11765. ~CRoxieServerFilterProjectActivity()
  11766. {
  11767. }
  11768. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11769. {
  11770. numProcessedLastGroup = 0;
  11771. recordCount = 0;
  11772. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  11773. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  11774. }
  11775. virtual bool needsAllocator() const { return true; }
  11776. virtual const void * nextInGroup()
  11777. {
  11778. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11779. if (eof)
  11780. return NULL;
  11781. loop
  11782. {
  11783. const void * in = input->nextInGroup();
  11784. if (!in)
  11785. {
  11786. recordCount = 0;
  11787. if (numProcessedLastGroup == processed)
  11788. in = input->nextInGroup();
  11789. if (!in)
  11790. {
  11791. numProcessedLastGroup = processed;
  11792. return NULL;
  11793. }
  11794. }
  11795. try
  11796. {
  11797. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11798. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  11799. ReleaseRoxieRow(in);
  11800. if (outSize)
  11801. {
  11802. processed++;
  11803. return rowBuilder.finalizeRowClear(outSize);
  11804. }
  11805. }
  11806. catch (IException *E)
  11807. {
  11808. throw makeWrappedException(E);
  11809. }
  11810. }
  11811. }
  11812. };
  11813. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  11814. {
  11815. public:
  11816. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11817. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11818. {
  11819. }
  11820. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11821. {
  11822. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  11823. }
  11824. };
  11825. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11826. {
  11827. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11828. }
  11829. //=================================================================================
  11830. class CRoxieServerProjectActivity : public CRoxieServerActivity
  11831. {
  11832. unsigned numProcessedLastGroup;
  11833. bool count;
  11834. unsigned __int64 recordCount;
  11835. public:
  11836. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  11837. : CRoxieServerActivity(_factory, _probeManager),
  11838. count(_count)
  11839. {
  11840. numProcessedLastGroup = 0;
  11841. recordCount = 0;
  11842. }
  11843. ~CRoxieServerProjectActivity()
  11844. {
  11845. }
  11846. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11847. {
  11848. numProcessedLastGroup = 0;
  11849. recordCount = 0;
  11850. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11851. }
  11852. virtual bool needsAllocator() const { return true; }
  11853. virtual const void * nextInGroup()
  11854. {
  11855. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11856. loop
  11857. {
  11858. OwnedConstRoxieRow in = input->nextInGroup();
  11859. if (!in)
  11860. {
  11861. recordCount = 0;
  11862. if (numProcessedLastGroup == processed)
  11863. in.setown(input->nextInGroup());
  11864. if (!in)
  11865. {
  11866. numProcessedLastGroup = processed;
  11867. return NULL;
  11868. }
  11869. }
  11870. try
  11871. {
  11872. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11873. size32_t outSize;
  11874. if (count)
  11875. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  11876. else
  11877. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  11878. if (outSize)
  11879. {
  11880. processed++;
  11881. return rowBuilder.finalizeRowClear(outSize);
  11882. }
  11883. }
  11884. catch (IException *E)
  11885. {
  11886. throw makeWrappedException(E);
  11887. }
  11888. }
  11889. }
  11890. };
  11891. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  11892. {
  11893. protected:
  11894. bool count;
  11895. public:
  11896. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11897. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11898. {
  11899. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  11900. }
  11901. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11902. {
  11903. return new CRoxieServerProjectActivity(this, _probeManager, count);
  11904. }
  11905. };
  11906. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11907. {
  11908. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11909. }
  11910. //=================================================================================
  11911. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  11912. {
  11913. unsigned numProcessedLastGroup;
  11914. bool count;
  11915. bool eof;
  11916. bool allPulled;
  11917. bool isThreaded;
  11918. unsigned preload;
  11919. unsigned __int64 recordCount;
  11920. IHThorPrefetchProjectArg &helper;
  11921. RecordPullerThread puller;
  11922. InterruptableSemaphore ready;
  11923. InterruptableSemaphore space;
  11924. class PrefetchInfo : public CInterface
  11925. {
  11926. public:
  11927. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  11928. {
  11929. if (helper.preTransform(extract, _in, _recordCount))
  11930. {
  11931. in.setown(_in);
  11932. recordCount = _recordCount;
  11933. }
  11934. else
  11935. ReleaseRoxieRow(_in);
  11936. }
  11937. OwnedConstRoxieRow in;
  11938. unsigned __int64 recordCount;
  11939. rtlRowBuilder extract;
  11940. };
  11941. QueueOf<PrefetchInfo, true> pulled;
  11942. CriticalSection pulledCrit;
  11943. public:
  11944. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  11945. : CRoxieServerActivity(_factory, _probeManager),
  11946. helper((IHThorPrefetchProjectArg &) basehelper),
  11947. puller(false),
  11948. count(_count)
  11949. {
  11950. numProcessedLastGroup = 0;
  11951. recordCount = 0;
  11952. eof = false;
  11953. allPulled = false;
  11954. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  11955. preload = 0;
  11956. }
  11957. ~CRoxieServerPrefetchProjectActivity()
  11958. {
  11959. while (pulled.ordinality())
  11960. ::Release(pulled.dequeue());
  11961. }
  11962. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11963. {
  11964. if (idx)
  11965. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11966. puller.setInput(this, _in);
  11967. }
  11968. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11969. {
  11970. numProcessedLastGroup = 0;
  11971. recordCount = 0;
  11972. eof = false;
  11973. allPulled = false;
  11974. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11975. preload = helper.getLookahead();
  11976. if (!preload)
  11977. preload = ctx->prefetchProjectPreload();
  11978. space.reinit(preload);
  11979. ready.reinit();
  11980. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  11981. }
  11982. virtual void stop(bool aborting)
  11983. {
  11984. space.interrupt();
  11985. ready.interrupt();
  11986. CRoxieServerActivity::stop(aborting);
  11987. puller.stop(aborting);
  11988. }
  11989. virtual void reset()
  11990. {
  11991. CRoxieServerActivity::reset();
  11992. puller.reset();
  11993. allPulled = false;
  11994. while (pulled.ordinality())
  11995. ::Release(pulled.dequeue());
  11996. }
  11997. virtual PrefetchInfo *readNextRecord()
  11998. {
  11999. if (!isThreaded)
  12000. {
  12001. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12002. puller.pullRecords(1);
  12003. }
  12004. else
  12005. ready.wait();
  12006. CriticalBlock b(pulledCrit);
  12007. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12008. space.signal();
  12009. return ret;
  12010. }
  12011. virtual bool needsAllocator() const { return true; }
  12012. virtual const void * nextInGroup()
  12013. {
  12014. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12015. if (eof)
  12016. return NULL;
  12017. loop
  12018. {
  12019. Owned<PrefetchInfo> in = readNextRecord();
  12020. if (!in)
  12021. {
  12022. recordCount = 0;
  12023. if (numProcessedLastGroup == processed)
  12024. in.setown(readNextRecord());
  12025. if (!in)
  12026. {
  12027. numProcessedLastGroup = processed;
  12028. eof = true;
  12029. return NULL;
  12030. }
  12031. }
  12032. try
  12033. {
  12034. if (in->in)
  12035. {
  12036. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12037. size32_t outSize;
  12038. IThorChildGraph *child = helper.queryChild();
  12039. Owned<IEclGraphResults> results;
  12040. if (child)
  12041. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12042. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12043. if (outSize)
  12044. {
  12045. processed++;
  12046. return rowBuilder.finalizeRowClear(outSize);
  12047. }
  12048. }
  12049. }
  12050. catch (IException *E)
  12051. {
  12052. throw makeWrappedException(E);
  12053. }
  12054. }
  12055. }
  12056. // interface IExceptionHandler
  12057. virtual bool fireException(IException *e)
  12058. {
  12059. // called from puller thread on failure
  12060. ready.interrupt(LINK(e));
  12061. space.interrupt(e);
  12062. return true;
  12063. }
  12064. // interface IRecordPullerCallback
  12065. virtual void processRow(const void *row)
  12066. {
  12067. {
  12068. CriticalBlock b(pulledCrit);
  12069. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12070. }
  12071. if (isThreaded)
  12072. {
  12073. ready.signal();
  12074. space.wait();
  12075. }
  12076. }
  12077. virtual void processEOG()
  12078. {
  12079. {
  12080. CriticalBlock b(pulledCrit);
  12081. pulled.enqueue(NULL);
  12082. }
  12083. if (isThreaded)
  12084. {
  12085. ready.signal();
  12086. space.wait();
  12087. }
  12088. }
  12089. virtual void processGroup(const ConstPointerArray &rows)
  12090. {
  12091. throwUnexpected();
  12092. }
  12093. virtual void processDone()
  12094. {
  12095. CriticalBlock b(pulledCrit);
  12096. allPulled = true;
  12097. if (isThreaded)
  12098. ready.signal();
  12099. }
  12100. };
  12101. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12102. {
  12103. public:
  12104. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12105. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12106. {
  12107. }
  12108. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12109. {
  12110. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12111. }
  12112. };
  12113. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12114. {
  12115. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12116. }
  12117. //=================================================================================
  12118. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12119. {
  12120. public:
  12121. CPointerArrayRoxieInput()
  12122. {
  12123. rowset = NULL;
  12124. rowcount = 0;
  12125. curRow = 0;
  12126. }
  12127. void init(size32_t _rowcount, byte **_rowset)
  12128. {
  12129. rowset = _rowset;
  12130. rowcount = _rowcount;
  12131. curRow = 0;
  12132. }
  12133. virtual const void * nextInGroup()
  12134. {
  12135. if (curRow < rowcount)
  12136. {
  12137. const void * ret = rowset[curRow];
  12138. if (ret)
  12139. LinkRoxieRow(ret);
  12140. curRow++;
  12141. return ret;
  12142. }
  12143. return NULL;
  12144. }
  12145. protected:
  12146. byte **rowset;
  12147. size32_t rowcount;
  12148. size32_t curRow;
  12149. };
  12150. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12151. {
  12152. protected:
  12153. IHThorLoopArg &helper;
  12154. ThorActivityKind activityKind;
  12155. unsigned maxIterations;
  12156. bool finishedLooping;
  12157. unsigned flags;
  12158. bool eof;
  12159. rtlRowBuilder loopExtractBuilder;
  12160. unsigned loopGraphId;
  12161. Linked<IOutputMetaData> counterMeta;
  12162. public:
  12163. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12164. : CRoxieServerActivity(_factory, _probeManager),
  12165. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12166. {
  12167. eof = false;
  12168. finishedLooping = false;
  12169. activityKind = factory->getKind();
  12170. flags = helper.getFlags();
  12171. maxIterations = 0;
  12172. }
  12173. virtual bool needsAllocator() const { return true; }
  12174. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12175. {
  12176. eof = false;
  12177. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12178. int iterations = (int) helper.numIterations();
  12179. maxIterations = (iterations >= 0) ? iterations : 0;
  12180. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12181. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12182. finishedLooping = true;
  12183. loopExtractBuilder.clear();
  12184. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12185. }
  12186. virtual void stop(bool aborting)
  12187. {
  12188. CRoxieServerActivity::stop(aborting);
  12189. loopExtractBuilder.clear();
  12190. }
  12191. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12192. {
  12193. if (flags & IHThorLoopArg::LFcounter)
  12194. {
  12195. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12196. *((thor_loop_counter_t *)counterRow) = counter;
  12197. RtlLinkedDatasetBuilder builder(rowAllocator);
  12198. builder.appendOwn(counterRow);
  12199. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12200. graph->setInputResult(2, counterResult);
  12201. }
  12202. }
  12203. };
  12204. //=================================================================================
  12205. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12206. {
  12207. Owned<IActivityGraph> loopQuery;
  12208. Owned<IRoxieServerChildGraph> loopGraph;
  12209. IRoxieInput * curInput;
  12210. RtlLinkedDatasetBuilder *loopInputBuilder;
  12211. CPointerArrayRoxieInput arrayInput;
  12212. Linked<IRoxieInput> resultInput;
  12213. unsigned loopCounter;
  12214. public:
  12215. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12216. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12217. {
  12218. curInput = NULL;
  12219. loopCounter = 0;
  12220. loopInputBuilder = NULL;
  12221. }
  12222. virtual bool needsAllocator() const { return true; }
  12223. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12224. {
  12225. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12226. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12227. }
  12228. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12229. {
  12230. curInput = input;
  12231. loopCounter = 1;
  12232. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12233. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12234. loopGraph.set(loopQuery->queryLoopGraph());
  12235. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12236. }
  12237. virtual void stop(bool aborting)
  12238. {
  12239. delete loopInputBuilder;
  12240. loopInputBuilder = NULL;
  12241. CRoxieServerLoopActivity::stop(aborting);
  12242. }
  12243. virtual const void * nextInGroup()
  12244. {
  12245. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12246. if (eof)
  12247. return NULL;
  12248. unsigned emptyIterations = 0;
  12249. loop
  12250. {
  12251. loop
  12252. {
  12253. const void * ret = curInput->nextInGroup();
  12254. if (!ret)
  12255. {
  12256. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12257. if (!ret)
  12258. {
  12259. if (finishedLooping)
  12260. {
  12261. eof = true;
  12262. return NULL;
  12263. }
  12264. break;
  12265. }
  12266. }
  12267. if (finishedLooping ||
  12268. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12269. {
  12270. processed++;
  12271. return ret;
  12272. }
  12273. loopInputBuilder->appendOwn(ret);
  12274. }
  12275. switch (activityKind)
  12276. {
  12277. case TAKloopdataset:
  12278. {
  12279. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12280. {
  12281. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12282. {
  12283. if (loopInputBuilder->getcount() == 0)
  12284. {
  12285. eof = true;
  12286. return NULL;
  12287. }
  12288. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12289. // MORE - should builder be cleared here?
  12290. curInput = &arrayInput;
  12291. finishedLooping = true;
  12292. continue; // back to the input loop again
  12293. }
  12294. }
  12295. break;
  12296. }
  12297. case TAKlooprow:
  12298. if (!loopInputBuilder->getcount())
  12299. {
  12300. finishedLooping = true;
  12301. eof = true;
  12302. return NULL;
  12303. }
  12304. break;
  12305. }
  12306. if (loopInputBuilder->getcount())
  12307. emptyIterations = 0;
  12308. else
  12309. {
  12310. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12311. emptyIterations++;
  12312. if (emptyIterations > maxEmptyLoopIterations)
  12313. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12314. if (emptyIterations % 32 == 0)
  12315. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12316. }
  12317. checkAbort();
  12318. try
  12319. {
  12320. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12321. resultInput.setown(results->createIterator(0));
  12322. if (flags & IHThorLoopArg::LFnewloopagain)
  12323. {
  12324. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12325. OwnedConstRoxieRow row = againResult->nextInGroup();
  12326. assertex(row);
  12327. //Result is a row which contains a single boolean field.
  12328. if (!((const bool *)row.get())[0])
  12329. finishedLooping = true;
  12330. }
  12331. }
  12332. catch (IException *E)
  12333. {
  12334. throw makeWrappedException(E);
  12335. }
  12336. curInput = resultInput.get();
  12337. loopCounter++;
  12338. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12339. finishedLooping = true;
  12340. }
  12341. }
  12342. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12343. {
  12344. try
  12345. {
  12346. loopGraph->beforeExecute();
  12347. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12348. loopInputBuilder->clear();
  12349. loopGraph->setInputResult(1, inputRowsResult);
  12350. createCounterResult(loopGraph, counter);
  12351. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12352. loopGraph->afterExecute();
  12353. return ret.getClear();
  12354. }
  12355. catch (...)
  12356. {
  12357. CTXLOG("Exception thrown in loop body - cleaning up");
  12358. loopGraph->afterExecute();
  12359. throw;
  12360. }
  12361. }
  12362. };
  12363. //=================================================================================
  12364. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12365. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12366. {
  12367. public:
  12368. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12369. input(_input)
  12370. {
  12371. eof = false;
  12372. }
  12373. virtual const void * nextInGroup()
  12374. {
  12375. if (eof)
  12376. return NULL;
  12377. const void * ret = input.dequeue();
  12378. if (!ret)
  12379. eof = true;
  12380. return ret;
  12381. }
  12382. protected:
  12383. SafeRowQueue & input;
  12384. bool eof;
  12385. };
  12386. class CRoxieServerParallelLoopActivity;
  12387. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12388. {
  12389. public:
  12390. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12391. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12392. {
  12393. }
  12394. virtual const void * nextInGroup();
  12395. protected:
  12396. CRoxieServerParallelLoopActivity * activity;
  12397. unsigned counter;
  12398. };
  12399. class LoopExecutorThread : public RestartableThread
  12400. {
  12401. protected:
  12402. Owned<IRoxieInput> safeInput;
  12403. CRoxieServerParallelLoopActivity * activity;
  12404. bool eof;
  12405. CriticalSection crit;
  12406. unsigned flags;
  12407. SafeRowQueue tempResults[2];
  12408. unsigned savedParentExtractSize;
  12409. const byte * savedParentExtract;
  12410. IArrayOf<IActivityGraph> cachedGraphs;
  12411. IRoxieSlaveContext *ctx;
  12412. public:
  12413. LoopExecutorThread()
  12414. : RestartableThread("LoopExecutorThread")
  12415. {
  12416. activity = NULL;
  12417. eof = false;
  12418. flags = 0;
  12419. ctx = NULL;
  12420. savedParentExtract = NULL;
  12421. savedParentExtractSize = 0;
  12422. }
  12423. virtual IRoxieInput *queryInput(unsigned idx) const
  12424. {
  12425. return safeInput->queryInput(idx);
  12426. }
  12427. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12428. {
  12429. activity = _activity;
  12430. flags = _flags;
  12431. // 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.
  12432. safeInput.setown(new CSafeRoxieInput(_input));
  12433. }
  12434. IRoxieInput *queryInput() const
  12435. {
  12436. return safeInput;
  12437. }
  12438. void onCreate(IRoxieSlaveContext * _ctx);
  12439. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12440. void stop(bool aborting);
  12441. void reset();
  12442. virtual int run();
  12443. protected:
  12444. void executeLoop();
  12445. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12446. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12447. };
  12448. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12449. {
  12450. friend class LoopFilterPseudoInput;
  12451. friend class LoopExecutorThread;
  12452. QueueOf<const void, true> ready;
  12453. CriticalSection helperCS;
  12454. CriticalSection cs;
  12455. size32_t sizeNumParallel;
  12456. rtlDataAttr listNumParallel;
  12457. unsigned defaultNumParallel;
  12458. LoopExecutorThread executor;
  12459. IProbeManager* probeManager;
  12460. CriticalSection canAccess;
  12461. CriticalSection scrit;
  12462. InterruptableSemaphore readySpace;
  12463. InterruptableSemaphore recordsReady;
  12464. protected:
  12465. bool includeInLoop(unsigned counter, const void * row)
  12466. {
  12467. CriticalBlock b(helperCS);
  12468. return helper.sendToLoop(counter, row);
  12469. }
  12470. public:
  12471. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12472. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12473. readySpace(parallelLoopFlowLimit)
  12474. {
  12475. probeManager = _probeManager;
  12476. defaultNumParallel = 0;
  12477. }
  12478. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12479. {
  12480. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12481. executor.onCreate(_ctx);
  12482. }
  12483. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12484. {
  12485. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12486. readySpace.reinit(parallelLoopFlowLimit);
  12487. recordsReady.reinit();
  12488. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12489. defaultNumParallel = helper.defaultParallelIterations();
  12490. if (!defaultNumParallel)
  12491. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12492. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12493. //MORE: If numIterations <= number of parallel iterations[1],
  12494. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12495. //being transferred via a queue
  12496. executor.start(parentExtractSize, parentExtract, paused);
  12497. }
  12498. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12499. {
  12500. if (idx)
  12501. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12502. executor.setInput(this, _in, flags);
  12503. }
  12504. virtual void stop(bool aborting)
  12505. {
  12506. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12507. readySpace.interrupt();
  12508. recordsReady.interrupt();
  12509. executor.join(); // MORE - may not be needed given stop/reset split
  12510. CRoxieServerLoopActivity::stop(aborting);
  12511. }
  12512. virtual void reset()
  12513. {
  12514. while (ready.ordinality())
  12515. ReleaseRoxieRow(ready.dequeue());
  12516. executor.reset();
  12517. CRoxieServerActivity::reset();
  12518. }
  12519. virtual const void * nextInGroup()
  12520. {
  12521. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12522. loop
  12523. {
  12524. if (eof)
  12525. return NULL;
  12526. recordsReady.wait();
  12527. CriticalBlock procedure(canAccess);
  12528. if (ready.ordinality())
  12529. {
  12530. const void *result = ready.dequeue();
  12531. readySpace.signal();
  12532. if (result)
  12533. processed++;
  12534. return result;
  12535. }
  12536. else
  12537. eof = true;
  12538. }
  12539. }
  12540. unsigned getNumParallel(unsigned iter)
  12541. {
  12542. if (iter * sizeof(unsigned) >= sizeNumParallel)
  12543. return defaultNumParallel;
  12544. return ((unsigned *)listNumParallel.getdata())[iter];
  12545. }
  12546. inline void enqueueResult(const void * row)
  12547. {
  12548. try
  12549. {
  12550. while(!readySpace.wait(1000))
  12551. {
  12552. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  12553. }
  12554. }
  12555. catch (...)
  12556. {
  12557. ReleaseRoxieRow(row);
  12558. throw;
  12559. }
  12560. CriticalBlock b2(canAccess);
  12561. ready.enqueue(row);
  12562. recordsReady.signal();
  12563. }
  12564. inline void finishResults()
  12565. {
  12566. recordsReady.signal();
  12567. }
  12568. virtual bool fireException(IException *e)
  12569. {
  12570. readySpace.interrupt(LINK(e));
  12571. recordsReady.interrupt(e);
  12572. return true;
  12573. }
  12574. IActivityGraph * createChildGraphInstance()
  12575. {
  12576. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  12577. }
  12578. IActivityGraph * queryChildGraph()
  12579. {
  12580. return ctx->queryChildGraph(loopGraphId);
  12581. }
  12582. };
  12583. //=================================================================================
  12584. const void * LoopFilterPseudoInput::nextInGroup()
  12585. {
  12586. loop
  12587. {
  12588. const void * next = input->nextInGroup();
  12589. if (!next || activity->includeInLoop(counter, next))
  12590. return next;
  12591. activity->enqueueResult(next);
  12592. }
  12593. }
  12594. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  12595. {
  12596. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  12597. ctx = _ctx;
  12598. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  12599. }
  12600. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12601. {
  12602. savedParentExtractSize = parentExtractSize;
  12603. savedParentExtract = parentExtract;
  12604. eof = false;
  12605. StringBuffer logPrefix("[");
  12606. ctx->getLogPrefix(logPrefix).append("] ");
  12607. RestartableThread::start(logPrefix);
  12608. }
  12609. int LoopExecutorThread::run()
  12610. {
  12611. try
  12612. {
  12613. executeLoop();
  12614. }
  12615. catch (IException *e)
  12616. {
  12617. activity->fireException(e);
  12618. }
  12619. catch (...)
  12620. {
  12621. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  12622. }
  12623. return 0;
  12624. }
  12625. void LoopExecutorThread::stop(bool aborting)
  12626. {
  12627. safeInput->stop(aborting);
  12628. RestartableThread::join();
  12629. }
  12630. void LoopExecutorThread::reset()
  12631. {
  12632. safeInput->reset();
  12633. }
  12634. void LoopExecutorThread::executeLoop()
  12635. {
  12636. unsigned iterations = 0;
  12637. unsigned counter = 0;
  12638. unsigned outputIndex = 0;
  12639. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  12640. loop
  12641. {
  12642. if (activity->activityKind == TAKloopcount)
  12643. {
  12644. if (counter == activity->maxIterations)
  12645. break;
  12646. }
  12647. else
  12648. {
  12649. //This condition isn't quite right because it needs to be whether the filtered
  12650. //input is empty. May be ok if we include that in the semantics,
  12651. if (tempResults[1-outputIndex].ordinality() == 0)
  12652. break;
  12653. }
  12654. unsigned numParallel = activity->getNumParallel(iterations);
  12655. Linked<IRoxieInput> curInput;
  12656. if (iterations == 0)
  12657. curInput.set(safeInput);
  12658. else
  12659. {
  12660. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12661. inputQueue.enqueue(NULL);
  12662. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  12663. }
  12664. SafeRowQueue * curOutput = NULL;
  12665. if (counter+numParallel > activity->maxIterations)
  12666. numParallel = activity->maxIterations - counter;
  12667. else if (counter+numParallel < activity->maxIterations)
  12668. curOutput = &tempResults[outputIndex];
  12669. executeLoopInstance(counter, numParallel, curInput, curOutput);
  12670. outputIndex = 1-outputIndex;
  12671. counter += numParallel;
  12672. iterations++;
  12673. }
  12674. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  12675. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12676. while (inputQueue.ordinality())
  12677. {
  12678. const void * next = inputQueue.dequeue();
  12679. activity->enqueueResult(next);
  12680. }
  12681. activity->finishResults();
  12682. }
  12683. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  12684. {
  12685. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  12686. Linked<IRoxieInput> curInput = input;
  12687. unsigned i;
  12688. for (i= 0; i != numIterations; i++)
  12689. {
  12690. unsigned thisCounter = counter+i+1;
  12691. IRoxieInput * filtered = curInput;
  12692. if (flags & IHThorLoopArg::LFfiltered)
  12693. {
  12694. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  12695. savedInputs.append(*filtered);
  12696. }
  12697. //graph is kept, so new curInput will be guaranteed to exist
  12698. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  12699. }
  12700. try
  12701. {
  12702. curInput->start(savedParentExtractSize, savedParentExtract, false);
  12703. if (spillOutput)
  12704. {
  12705. loop
  12706. {
  12707. const void * next = curInput->nextInGroup();
  12708. if (!next)
  12709. break;
  12710. spillOutput->enqueue(next);
  12711. }
  12712. }
  12713. else
  12714. {
  12715. loop
  12716. {
  12717. const void * next = curInput->nextInGroup();
  12718. if (!next)
  12719. break;
  12720. activity->enqueueResult(next);
  12721. }
  12722. }
  12723. }
  12724. catch (IException *E)
  12725. {
  12726. ctx->notifyAbort(E);
  12727. for (i= 0; i != numIterations; i++)
  12728. {
  12729. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12730. }
  12731. curInput->stop(true);
  12732. curInput->reset();
  12733. throw;
  12734. }
  12735. for (i= 0; i != numIterations; i++)
  12736. {
  12737. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12738. }
  12739. curInput->stop(false);
  12740. curInput->reset();
  12741. }
  12742. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  12743. {
  12744. if (!cachedGraphs.isItem(i))
  12745. cachedGraphs.append(*activity->createChildGraphInstance());
  12746. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  12747. loopGraph->beforeExecute();
  12748. if (!loopGraph->querySetInputResult(1, input))
  12749. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  12750. activity->createCounterResult(loopGraph, counter);
  12751. return loopGraph->selectOutput(0);
  12752. }
  12753. //=================================================================================
  12754. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  12755. {
  12756. public:
  12757. IMPLEMENT_IINTERFACE
  12758. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  12759. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  12760. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  12761. virtual void toXML(const byte * self, IXmlWriter & out) { }
  12762. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  12763. virtual unsigned getMetaFlags() { return 0; }
  12764. virtual void destruct(byte * self) {}
  12765. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12766. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12767. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12768. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  12769. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12770. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12771. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  12772. };
  12773. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  12774. {
  12775. unsigned loopGraphId;
  12776. unsigned flags;
  12777. Linked<IOutputMetaData> counterMeta;
  12778. public:
  12779. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12780. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  12781. {
  12782. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  12783. flags = helper->getFlags();
  12784. counterMeta.setown(new CCounterRowMetaData);
  12785. }
  12786. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12787. {
  12788. if (flags & IHThorLoopArg::LFparallel)
  12789. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12790. else
  12791. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12792. }
  12793. };
  12794. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12795. {
  12796. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  12797. }
  12798. //=================================================================================
  12799. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  12800. {
  12801. protected:
  12802. IHThorGraphLoopArg &helper;
  12803. unsigned maxIterations;
  12804. unsigned flags;
  12805. rtlRowBuilder GraphExtractBuilder;
  12806. unsigned loopGraphId;
  12807. Linked<IOutputMetaData> counterMeta;
  12808. public:
  12809. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  12810. : CRoxieServerActivity(_factory, _probeManager),
  12811. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  12812. {
  12813. flags = helper.getFlags();
  12814. maxIterations = 0;
  12815. }
  12816. virtual bool needsAllocator() const { return true; }
  12817. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12818. {
  12819. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12820. int iterations = (int) helper.numIterations();
  12821. maxIterations = (iterations >= 0) ? iterations : 0;
  12822. if (maxIterations > maxGraphLoopIterations)
  12823. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  12824. if (maxIterations != 0)
  12825. {
  12826. GraphExtractBuilder.clear();
  12827. helper.createParentExtract(GraphExtractBuilder);
  12828. }
  12829. }
  12830. virtual void stop(bool aborting)
  12831. {
  12832. CRoxieServerActivity::stop(aborting);
  12833. GraphExtractBuilder.clear();
  12834. }
  12835. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12836. {
  12837. if (flags & IHThorGraphLoopArg::GLFcounter)
  12838. {
  12839. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12840. *((thor_loop_counter_t *)counterRow) = counter;
  12841. RtlLinkedDatasetBuilder builder(rowAllocator);
  12842. builder.appendOwn(counterRow);
  12843. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12844. graph->setInputResult(0, counterResult);
  12845. }
  12846. }
  12847. };
  12848. //=================================================================================
  12849. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  12850. {
  12851. Owned<IActivityGraph> GraphQuery;
  12852. Owned<IRoxieServerChildGraph> loopGraph;
  12853. Linked<IRoxieInput> resultInput;
  12854. bool evaluated;
  12855. public:
  12856. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  12857. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  12858. {
  12859. evaluated = false;
  12860. }
  12861. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12862. {
  12863. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  12864. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  12865. }
  12866. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12867. {
  12868. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  12869. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12870. loopGraph.set(GraphQuery->queryLoopGraph());
  12871. evaluated = false;
  12872. }
  12873. virtual void stop(bool aborting)
  12874. {
  12875. if (loopGraph)
  12876. loopGraph->clearGraphLoopResults();
  12877. CRoxieServerGraphLoopActivity::stop(aborting);
  12878. }
  12879. virtual const void * nextInGroup()
  12880. {
  12881. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12882. if (!evaluated)
  12883. {
  12884. executeEntireGraph();
  12885. evaluated = true;
  12886. }
  12887. const void * ret = resultInput->nextInGroup();
  12888. if (ret)
  12889. processed++;
  12890. return ret;
  12891. }
  12892. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12893. {
  12894. try
  12895. {
  12896. loopGraph->beforeExecute();
  12897. createCounterResult(loopGraph, counter);
  12898. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  12899. loopGraph->afterExecute();
  12900. }
  12901. catch (...)
  12902. {
  12903. CTXLOG("Exception thrown in graph body - cleaning up");
  12904. loopGraph->afterExecute();
  12905. throw;
  12906. }
  12907. }
  12908. void createInitialGraphInput()
  12909. {
  12910. loopGraph->clearGraphLoopResults();
  12911. RtlLinkedDatasetBuilder builder(rowAllocator);
  12912. input->readAll(builder);
  12913. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  12914. loopGraph->setGraphLoopResult(0, result);
  12915. }
  12916. void executeEntireGraph()
  12917. {
  12918. createInitialGraphInput();
  12919. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  12920. {
  12921. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  12922. }
  12923. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  12924. }
  12925. };
  12926. //=================================================================================
  12927. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  12928. {
  12929. public:
  12930. virtual unsigned numBranches()
  12931. {
  12932. return 0;
  12933. }
  12934. virtual IOutputMetaData * queryOutputMeta()
  12935. {
  12936. return NULL;// get it from the parent..
  12937. }
  12938. };
  12939. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  12940. class CGraphIterationInfo : public CInterface
  12941. {
  12942. private:
  12943. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  12944. unsigned sourceIdx;
  12945. Linked<IRoxieServerActivity> sourceAct;
  12946. Linked<IRoxieInput> sourceInput;
  12947. unsigned numUses;
  12948. unsigned iteration;
  12949. public:
  12950. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  12951. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  12952. {
  12953. numUses = 0;
  12954. }
  12955. inline void noteUsed()
  12956. {
  12957. numUses++;
  12958. }
  12959. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  12960. {
  12961. if (numUses > 1)
  12962. {
  12963. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  12964. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  12965. splitter->onCreate(ctx, NULL);
  12966. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  12967. if (probeManager)
  12968. {
  12969. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  12970. input = static_cast<IRoxieInput*>(inputBase);
  12971. // MORE - shouldn't this be added to probes?
  12972. }
  12973. sourceAct.setown(splitter);
  12974. sourceAct->setInput(0, input);
  12975. sourceIdx = 0;
  12976. sourceInput.clear();
  12977. }
  12978. }
  12979. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  12980. {
  12981. // MORE - not really necessary to create splitters in separate pass, is it?
  12982. if (factory) // we created a splitter....
  12983. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  12984. IRoxieInput *ret = sourceInput;
  12985. if (probeManager)
  12986. {
  12987. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  12988. ret = static_cast<IRoxieInput *>(inputBase);
  12989. probes.append(*LINK(ret));
  12990. }
  12991. if (factory) // we created a splitter....
  12992. sourceIdx++;
  12993. return ret;
  12994. }
  12995. };
  12996. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  12997. {
  12998. Owned<IActivityGraph> childGraph;
  12999. IRoxieInput * resultInput;
  13000. CIArrayOf<CGraphIterationInfo> outputs;
  13001. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13002. Owned<CExtractMapperInput> inputExtractMapper;
  13003. IProbeManager *probeManager;
  13004. unsigned createLoopCounter;
  13005. IArrayOf<IRoxieInput> probes;
  13006. public:
  13007. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13008. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13009. {
  13010. inputExtractMapper.setown(new CExtractMapperInput);
  13011. resultInput = NULL;
  13012. createLoopCounter = 0;
  13013. }
  13014. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13015. {
  13016. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13017. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13018. }
  13019. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13020. {
  13021. //Input needs to be handled very carefully.....
  13022. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13023. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13024. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13025. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13026. assertex(idx == 0);
  13027. inputExtractMapper->setInput(_in);
  13028. }
  13029. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13030. {
  13031. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13032. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13033. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13034. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13035. }
  13036. virtual void stop(bool aborting)
  13037. {
  13038. if (resultInput)
  13039. resultInput->stop(aborting);
  13040. CRoxieServerGraphLoopActivity::stop(aborting);
  13041. }
  13042. virtual void reset()
  13043. {
  13044. if (resultInput)
  13045. resultInput->reset();
  13046. resultInput = NULL;
  13047. iterationGraphs.kill();
  13048. outputs.kill();
  13049. if (probeManager)
  13050. {
  13051. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13052. probes.kill();
  13053. }
  13054. CRoxieServerGraphLoopActivity::reset();
  13055. }
  13056. virtual const void * nextInGroup()
  13057. {
  13058. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13059. const void * ret = resultInput->nextInGroup();
  13060. if (ret)
  13061. processed++;
  13062. return ret;
  13063. }
  13064. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13065. {
  13066. //result(0) is the input to the graph.
  13067. resultInput = inputExtractMapper;
  13068. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13069. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13070. {
  13071. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13072. graph->beforeExecute();
  13073. iterationGraphs.append(*graph);
  13074. graph->gatherIterationUsage(*this);
  13075. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13076. outputs.append(*iteration);
  13077. }
  13078. createLoopCounter = 0;
  13079. createSplitters(probeManager);
  13080. ForEachItemIn(i2, iterationGraphs)
  13081. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13082. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13083. }
  13084. void createSplitters(IProbeManager *probeManager)
  13085. {
  13086. ForEachItemIn(i, outputs)
  13087. {
  13088. CGraphIterationInfo & next = outputs.item(i);
  13089. next.createSplitter(ctx, probeManager);
  13090. }
  13091. }
  13092. //IRoxieServerLoopResultProcessor
  13093. virtual void noteUseIteration(unsigned _whichIteration)
  13094. {
  13095. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13096. if (whichIteration >= 0)
  13097. {
  13098. if (!outputs.isItem(whichIteration))
  13099. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13100. outputs.item(whichIteration).noteUsed();
  13101. }
  13102. }
  13103. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13104. {
  13105. if (outputs.isItem(whichIteration))
  13106. {
  13107. CGraphIterationInfo & next = outputs.item(whichIteration);
  13108. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13109. }
  13110. return NULL;
  13111. }
  13112. };
  13113. //=================================================================================
  13114. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13115. {
  13116. unsigned loopGraphId;
  13117. unsigned flags;
  13118. Linked<IOutputMetaData> counterMeta;
  13119. public:
  13120. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13121. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13122. {
  13123. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13124. flags = helper->getFlags();
  13125. counterMeta.setown(new CCounterRowMetaData);
  13126. }
  13127. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13128. {
  13129. if (kind == TAKparallelgraphloop)
  13130. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13131. else
  13132. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13133. }
  13134. };
  13135. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13136. {
  13137. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13138. }
  13139. //=====================================================================================================
  13140. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13141. {
  13142. class OutputAdaptor : public CExtractMapperInput
  13143. {
  13144. bool stopped;
  13145. public:
  13146. CRoxieServerLibraryCallActivity *parent;
  13147. unsigned oid;
  13148. unsigned processed;
  13149. public:
  13150. IMPLEMENT_IINTERFACE;
  13151. OutputAdaptor() : CExtractMapperInput(NULL)
  13152. {
  13153. parent = NULL;
  13154. oid = 0;
  13155. init();
  13156. }
  13157. void init()
  13158. {
  13159. processed = 0;
  13160. stopped = false;
  13161. }
  13162. virtual unsigned queryId() const
  13163. {
  13164. return parent->queryId();
  13165. }
  13166. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13167. {
  13168. parent->start(oid, parentExtractSize, parentExtract, paused);
  13169. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13170. }
  13171. virtual void stop(bool aborting)
  13172. {
  13173. if (!stopped)
  13174. {
  13175. stopped = true;
  13176. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13177. CExtractMapperInput::stop(aborting);
  13178. }
  13179. };
  13180. virtual void reset()
  13181. {
  13182. parent->reset(oid, processed);
  13183. CExtractMapperInput::reset();
  13184. init();
  13185. };
  13186. virtual void checkAbort()
  13187. {
  13188. parent->checkAbort();
  13189. }
  13190. };
  13191. IHThorLibraryCallArg &helper;
  13192. unsigned numInputs;
  13193. unsigned numOutputs;
  13194. unsigned numActiveOutputs;
  13195. bool started;
  13196. OutputAdaptor* outputAdaptors;
  13197. CExtractMapperInput * * inputAdaptors;
  13198. bool * inputUsed;
  13199. bool * outputUsed;
  13200. Owned<IException> error;
  13201. CriticalSection crit;
  13202. rtlRowBuilder libraryExtractBuilder;
  13203. Owned<IActivityGraph> libraryGraph;
  13204. const LibraryCallFactoryExtra & extra;
  13205. public:
  13206. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13207. : CRoxieServerActivity(_factory, _probeManager),
  13208. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13209. {
  13210. numInputs = _numInputs;
  13211. numOutputs = _numOutputs;
  13212. numActiveOutputs = numOutputs;
  13213. inputAdaptors = new CExtractMapperInput*[numInputs];
  13214. inputUsed = new bool[numInputs];
  13215. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13216. {
  13217. inputAdaptors[i1] = new CExtractMapperInput;
  13218. inputUsed[i1] = false;
  13219. }
  13220. outputAdaptors = new OutputAdaptor[numOutputs];
  13221. outputUsed = new bool[numOutputs];
  13222. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13223. {
  13224. outputAdaptors[i2].parent = this;
  13225. outputAdaptors[i2].oid = i2;
  13226. outputUsed[i2] = false;
  13227. }
  13228. started = false;
  13229. }
  13230. ~CRoxieServerLibraryCallActivity()
  13231. {
  13232. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13233. ::Release(inputAdaptors[i1]);
  13234. delete [] inputAdaptors;
  13235. delete [] inputUsed;
  13236. delete [] outputAdaptors;
  13237. delete [] outputUsed;
  13238. }
  13239. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13240. {
  13241. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13242. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13243. libraryGraph->onCreate(_ctx, _colocalParent);
  13244. //Now map the inputs and outputs to the adapters
  13245. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13246. for (unsigned i1=0; i1<numInputs; i1++)
  13247. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13248. for (unsigned i2=0; i2<numOutputs; i2++)
  13249. {
  13250. unsigned outputIndex = extra.outputs.item(i2);
  13251. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13252. outputAdaptors[i2].setInput(output);
  13253. }
  13254. }
  13255. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13256. {
  13257. CriticalBlock b(crit);
  13258. if (error)
  13259. throw error.getLink();
  13260. if (factory)
  13261. factory->noteStarted(oid);
  13262. if (!started)
  13263. {
  13264. // even though it is not complete, we don't want to run this again if it fails.
  13265. started = true;
  13266. //see notes on splitter above
  13267. try
  13268. {
  13269. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13270. }
  13271. catch (IException *E)
  13272. {
  13273. #ifdef TRACE_SPLIT
  13274. CTXLOG("spill %d caught exception in start", activityId);
  13275. #endif
  13276. error.set(E);
  13277. throw;
  13278. }
  13279. catch (...)
  13280. {
  13281. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13282. error.set(E);
  13283. throw E;
  13284. }
  13285. //recreate the parent extract, and use it to reinitialize the graphs...
  13286. libraryExtractBuilder.clear();
  13287. helper.createParentExtract(libraryExtractBuilder);
  13288. // 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
  13289. // some inputs before we see start on others.
  13290. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13291. {
  13292. if (inputUsed[i1])
  13293. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13294. else
  13295. inputAdaptors[i1]->stop(false);
  13296. }
  13297. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13298. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13299. //call stop on all the unused inputs.
  13300. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13301. graph->beforeExecute();
  13302. ForEachItemIn(i3, extra.unusedOutputs)
  13303. {
  13304. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13305. output->stop(false);
  13306. }
  13307. }
  13308. }
  13309. virtual void stop(unsigned oid, bool aborting)
  13310. {
  13311. CriticalBlock b(crit);
  13312. if (--numActiveOutputs == 0)
  13313. {
  13314. //call stop on all the unused inputs.
  13315. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13316. graph->beforeExecute();
  13317. ForEachItemIn(i3, extra.unusedOutputs)
  13318. {
  13319. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13320. output->stop(false);
  13321. }
  13322. CRoxieServerActivity::stop(aborting);
  13323. }
  13324. }
  13325. void reset(unsigned oid, unsigned _processed)
  13326. {
  13327. noteProcessed(oid, _processed, 0, 0);
  13328. started = false;
  13329. error.clear();
  13330. numActiveOutputs = numOutputs;
  13331. if (state != STATEreset) // make sure input is only reset once
  13332. {
  13333. CRoxieServerActivity::reset();
  13334. libraryGraph->reset();
  13335. //Call reset on all unused outputs from the graph - no one else will.
  13336. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13337. ForEachItemIn(i3, extra.unusedOutputs)
  13338. {
  13339. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13340. output->reset();
  13341. }
  13342. }
  13343. };
  13344. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13345. {
  13346. inputAdaptors[idx]->setInput(_in);
  13347. }
  13348. public:
  13349. virtual const void *nextInGroup()
  13350. {
  13351. throwUnexpected(); // Internal logic error - we are not anybody's input
  13352. }
  13353. virtual IOutputMetaData * queryOutputMeta() const
  13354. {
  13355. throwUnexpected(); // should be called on outputs instead
  13356. }
  13357. virtual IRoxieInput *queryOutput(unsigned idx)
  13358. {
  13359. assertex(idx!=(unsigned)-1);
  13360. assertex(!outputUsed[idx]);
  13361. outputUsed[idx] = true;
  13362. return &outputAdaptors[idx];
  13363. }
  13364. };
  13365. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13366. {
  13367. ForEachItemIn(i1, _other.outputs)
  13368. outputs.append(_other.outputs.item(i1));
  13369. ForEachItemIn(i2, _other.unusedOutputs)
  13370. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13371. maxOutputs = _other.maxOutputs;
  13372. graphid = _other.graphid;
  13373. libraryName.set(_other.libraryName);
  13374. interfaceHash = _other.interfaceHash;
  13375. embedded = _other.embedded;
  13376. }
  13377. void LibraryCallFactoryExtra::calcUnused()
  13378. {
  13379. for (unsigned i=0; i < maxOutputs; i++)
  13380. if (!outputs.contains(i))
  13381. unusedOutputs.append(i);
  13382. }
  13383. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13384. {
  13385. private:
  13386. CRoxieServerMultiInputInfo inputs;
  13387. LibraryCallFactoryExtra extra;
  13388. public:
  13389. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13390. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13391. {
  13392. extra.set(_extra);
  13393. extra.calcUnused();
  13394. setNumOutputs(extra.outputs.ordinality());
  13395. }
  13396. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13397. {
  13398. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13399. }
  13400. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13401. {
  13402. inputs.set(idx, source, sourceidx);
  13403. }
  13404. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13405. {
  13406. return inputs.get(idx, sourceidx);
  13407. }
  13408. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13409. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13410. {
  13411. addXrefLibraryInfo(reply, extra.libraryName);
  13412. }
  13413. };
  13414. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13415. {
  13416. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13417. }
  13418. //=====================================================================================================
  13419. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13420. {
  13421. IHThorNWayInputArg & helper;
  13422. IRoxieInput ** inputs;
  13423. PointerArrayOf<IRoxieInput> selectedInputs;
  13424. unsigned numInputs;
  13425. public:
  13426. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13427. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13428. {
  13429. inputs = new IRoxieInput*[numInputs];
  13430. for (unsigned i = 0; i < numInputs; i++)
  13431. inputs[i] = NULL;
  13432. }
  13433. ~CRoxieServerNWayInputActivity()
  13434. {
  13435. delete [] inputs;
  13436. }
  13437. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13438. {
  13439. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13440. bool selectionIsAll;
  13441. size32_t selectionLen;
  13442. rtlDataAttr selection;
  13443. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13444. selectedInputs.kill();
  13445. if (selectionIsAll)
  13446. {
  13447. for (unsigned i=0; i < numInputs; i++)
  13448. selectedInputs.append(inputs[i]);
  13449. }
  13450. else
  13451. {
  13452. const size32_t * selections = (const size32_t *)selection.getdata();
  13453. unsigned max = selectionLen/sizeof(size32_t);
  13454. for (unsigned i = 0; i < max; i++)
  13455. {
  13456. unsigned nextIndex = selections[i];
  13457. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13458. for (unsigned j=i+1; j < max; j++)
  13459. {
  13460. if (nextIndex == selections[j])
  13461. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13462. }
  13463. if (nextIndex > numInputs)
  13464. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13465. selectedInputs.append(inputs[nextIndex-1]);
  13466. }
  13467. }
  13468. ForEachItemIn(i2, selectedInputs)
  13469. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13470. }
  13471. virtual void stop(bool aborting)
  13472. {
  13473. ForEachItemIn(i2, selectedInputs)
  13474. selectedInputs.item(i2)->stop(aborting);
  13475. CRoxieServerActivity::stop(aborting);
  13476. }
  13477. virtual unsigned __int64 queryLocalCycles() const
  13478. {
  13479. __int64 localCycles = totalCycles;
  13480. ForEachItemIn(i, selectedInputs)
  13481. {
  13482. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13483. }
  13484. if (localCycles < 0)
  13485. localCycles = 0;
  13486. return localCycles;
  13487. }
  13488. virtual IRoxieInput *queryInput(unsigned idx) const
  13489. {
  13490. if (selectedInputs.isItem(idx))
  13491. return selectedInputs.item(idx);
  13492. else
  13493. return NULL;
  13494. }
  13495. virtual void reset()
  13496. {
  13497. ForEachItemIn(i, selectedInputs)
  13498. selectedInputs.item(i)->reset();
  13499. selectedInputs.kill();
  13500. CRoxieServerActivity::reset();
  13501. }
  13502. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13503. {
  13504. assertex(idx < numInputs);
  13505. inputs[idx] = _in;
  13506. }
  13507. virtual const void * nextInGroup()
  13508. {
  13509. throwUnexpected();
  13510. }
  13511. virtual unsigned numConcreteOutputs() const
  13512. {
  13513. return selectedInputs.ordinality();
  13514. }
  13515. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13516. {
  13517. if (selectedInputs.isItem(idx))
  13518. return selectedInputs.item(idx);
  13519. return NULL;
  13520. }
  13521. };
  13522. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  13523. {
  13524. // bool ordered;
  13525. public:
  13526. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13527. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13528. {
  13529. }
  13530. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13531. {
  13532. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  13533. }
  13534. };
  13535. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13536. {
  13537. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  13538. }
  13539. //=====================================================================================================
  13540. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  13541. {
  13542. IHThorNWayGraphLoopResultReadArg & helper;
  13543. CIArrayOf<CRoxieServerActivity> resultReaders;
  13544. PointerArrayOf<IRoxieInput> inputs;
  13545. unsigned graphId;
  13546. bool grouped;
  13547. bool selectionIsAll;
  13548. size32_t selectionLen;
  13549. rtlDataAttr selection;
  13550. public:
  13551. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  13552. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  13553. {
  13554. grouped = helper.isGrouped();
  13555. graphId = _graphId;
  13556. selectionIsAll = false;
  13557. }
  13558. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13559. {
  13560. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13561. if (inputs.ordinality() == 0)
  13562. {
  13563. initInputSelection();
  13564. unsigned max = selectionLen / sizeof(size32_t);
  13565. const size32_t * selections = (const size32_t *)selection.getdata();
  13566. IProbeManager * probeManager = NULL; // MORE!!
  13567. for (unsigned i = 0; i < max; i++)
  13568. {
  13569. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  13570. resultReaders.append(*resultInput);
  13571. inputs.append(resultInput->queryOutput(0));
  13572. resultInput->onCreate(ctx, colocalParent);
  13573. resultInput->start(parentExtractSize, parentExtract, paused);
  13574. }
  13575. }
  13576. else
  13577. {
  13578. ForEachItemIn(i, inputs)
  13579. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  13580. }
  13581. }
  13582. virtual void stop(bool aborting)
  13583. {
  13584. ForEachItemIn(i, inputs)
  13585. inputs.item(i)->stop(aborting);
  13586. CRoxieServerActivity::stop(aborting);
  13587. }
  13588. virtual void reset()
  13589. {
  13590. ForEachItemIn(i, inputs)
  13591. inputs.item(i)->reset();
  13592. inputs.kill();
  13593. resultReaders.kill();
  13594. CRoxieServerActivity::reset();
  13595. }
  13596. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13597. {
  13598. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  13599. }
  13600. virtual const void * nextInGroup()
  13601. {
  13602. throwUnexpected();
  13603. }
  13604. virtual unsigned numConcreteOutputs() const
  13605. {
  13606. return inputs.ordinality();
  13607. }
  13608. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13609. {
  13610. if (inputs.isItem(idx))
  13611. return inputs.item(idx);
  13612. return NULL;
  13613. }
  13614. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  13615. {
  13616. ensureCreated();
  13617. basehelper.onStart(parentExtract, NULL);
  13618. initInputSelection();
  13619. unsigned max = selectionLen / sizeof(size32_t);
  13620. const size32_t * selections = (const size32_t *)selection.getdata();
  13621. for (unsigned i = 0; i < max; i++)
  13622. processor.noteUseIteration(selections[i]);
  13623. }
  13624. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  13625. {
  13626. //selection etc. already initialised from the gratherIterationUsage() call.
  13627. unsigned max = selectionLen / sizeof(size32_t);
  13628. const size32_t * selections = (const size32_t *)selection.getdata();
  13629. for (unsigned i = 0; i < max; i++)
  13630. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  13631. }
  13632. protected:
  13633. void initInputSelection()
  13634. {
  13635. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13636. if (selectionIsAll)
  13637. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  13638. }
  13639. };
  13640. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  13641. {
  13642. unsigned graphId;
  13643. public:
  13644. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  13645. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  13646. {
  13647. }
  13648. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13649. {
  13650. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  13651. }
  13652. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13653. {
  13654. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  13655. }
  13656. };
  13657. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  13658. {
  13659. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  13660. }
  13661. //=================================================================================
  13662. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  13663. {
  13664. public:
  13665. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  13666. IMPLEMENT_IINTERFACE
  13667. protected:
  13668. virtual const void * nextInputRow()
  13669. {
  13670. #ifdef TRACE_SEEK_REQUESTS
  13671. IRoxieContextLogger * logger = input->queryActivity();
  13672. const void * ret = doNextInputRow();
  13673. {
  13674. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13675. if (!ret)
  13676. xmlwrite.outputBool(true,"eof");
  13677. else if (input->queryOutputMeta()->hasXML())
  13678. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13679. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  13680. }
  13681. return ret;
  13682. #else
  13683. return doNextInputRow();
  13684. #endif
  13685. }
  13686. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13687. {
  13688. #ifdef TRACE_SEEK_REQUESTS
  13689. IRoxieContextLogger * logger = input->queryActivity();
  13690. {
  13691. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13692. if (input->queryOutputMeta()->hasXML())
  13693. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  13694. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  13695. numFields,
  13696. stepExtra.readAheadManyResults() ? "readahead " : "",
  13697. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13698. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13699. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13700. xmlwrite.str());
  13701. }
  13702. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13703. {
  13704. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13705. if (!ret)
  13706. xmlwrite.outputBool(true,"eof");
  13707. else if (input->queryOutputMeta()->hasXML())
  13708. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13709. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  13710. numFields,
  13711. stepExtra.readAheadManyResults() ? "readahead " : "",
  13712. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13713. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13714. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13715. xmlwrite.str());
  13716. }
  13717. return ret;
  13718. #else
  13719. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13720. #endif
  13721. }
  13722. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  13723. {
  13724. return input->gatherConjunctions(collector);
  13725. }
  13726. virtual void resetEOF()
  13727. {
  13728. input->resetEOF();
  13729. }
  13730. virtual IInputSteppingMeta * queryInputSteppingMeta()
  13731. {
  13732. return input->querySteppingMeta();
  13733. }
  13734. inline const void * doNextInputRow()
  13735. {
  13736. const void * ret = input->nextInGroup();
  13737. if (!ret)
  13738. ret = input->nextInGroup();
  13739. return ret;
  13740. }
  13741. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13742. {
  13743. assertex(wasCompleteMatch);
  13744. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  13745. }
  13746. protected:
  13747. IRoxieInput * input;
  13748. };
  13749. //=================================================================================
  13750. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  13751. {
  13752. public:
  13753. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13754. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  13755. {
  13756. }
  13757. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13758. {
  13759. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  13760. for (unsigned i=0; i < numInputs; i++)
  13761. {
  13762. IRoxieInput * cur = inputArray[i];
  13763. unsigned numRealInputs = cur->numConcreteOutputs();
  13764. for (unsigned j = 0; j < numRealInputs; j++)
  13765. {
  13766. IRoxieInput * curReal = cur->queryConcreteInput(j);
  13767. expandedInputs.append(curReal);
  13768. }
  13769. }
  13770. }
  13771. virtual void reset()
  13772. {
  13773. expandedInputs.kill();
  13774. CRoxieServerMultiInputActivity::reset();
  13775. }
  13776. protected:
  13777. PointerArrayOf<IRoxieInput> expandedInputs;
  13778. };
  13779. //=================================================================================
  13780. class CRoxieStreamMerger : public CStreamMerger
  13781. {
  13782. public:
  13783. CRoxieStreamMerger() : CStreamMerger(true) {}
  13784. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  13785. {
  13786. CStreamMerger::initInputs(_numInputs);
  13787. inputArray = _inputArray;
  13788. }
  13789. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  13790. {
  13791. const void * next;
  13792. bool matches = true;
  13793. if (seek)
  13794. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  13795. else
  13796. next = nextUngrouped(inputArray[i]);
  13797. pending[i] = next;
  13798. pendingMatches[i] = matches;
  13799. return (next != NULL);
  13800. }
  13801. virtual void releaseRow(const void * row)
  13802. {
  13803. ReleaseRoxieRow(row);
  13804. }
  13805. protected:
  13806. IRoxieInput **inputArray;
  13807. };
  13808. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  13809. {
  13810. public:
  13811. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13812. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  13813. helper((IHThorNWayMergeArg &)basehelper)
  13814. {
  13815. initializedMeta = false;
  13816. }
  13817. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13818. {
  13819. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  13820. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  13821. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  13822. }
  13823. virtual void stop(bool aborting)
  13824. {
  13825. merger.done();
  13826. CRoxieServerNaryActivity::stop(aborting);
  13827. }
  13828. virtual void reset()
  13829. {
  13830. merger.cleanup();
  13831. CRoxieServerNaryActivity::reset();
  13832. initializedMeta = false;
  13833. }
  13834. virtual const void * nextInGroup()
  13835. {
  13836. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13837. const void * next = merger.nextRow();
  13838. if (next)
  13839. processed++;
  13840. return next;
  13841. }
  13842. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13843. {
  13844. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13845. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13846. if (next)
  13847. processed++;
  13848. return next;
  13849. }
  13850. virtual IInputSteppingMeta * querySteppingMeta()
  13851. {
  13852. if (expandedInputs.ordinality() == 0)
  13853. return NULL;
  13854. if (!initializedMeta)
  13855. {
  13856. meta.init(helper.querySteppingMeta(), false);
  13857. ForEachItemIn(i, expandedInputs)
  13858. {
  13859. if (meta.getNumFields() == 0)
  13860. break;
  13861. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  13862. meta.intersect(inputMeta);
  13863. }
  13864. initializedMeta = true;
  13865. }
  13866. if (meta.getNumFields() == 0)
  13867. return NULL;
  13868. return &meta;
  13869. }
  13870. protected:
  13871. IHThorNWayMergeArg &helper;
  13872. CRoxieStreamMerger merger;
  13873. CSteppingMeta meta;
  13874. bool initializedMeta;
  13875. };
  13876. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  13877. {
  13878. public:
  13879. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13880. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13881. {
  13882. }
  13883. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13884. {
  13885. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  13886. }
  13887. };
  13888. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13889. {
  13890. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  13891. }
  13892. //=================================================================================
  13893. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  13894. {
  13895. public:
  13896. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  13897. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  13898. helper((IHThorNWayMergeJoinArg &)basehelper)
  13899. {
  13900. }
  13901. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13902. {
  13903. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  13904. ForEachItemIn(i1, expandedInputs)
  13905. {
  13906. IRoxieInput * cur = expandedInputs.item(i1);
  13907. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  13908. processor.addInput(stepInput);
  13909. }
  13910. ICodeContext * codectx = ctx->queryCodeContext();
  13911. Owned<IEngineRowAllocator> inputAllocator = codectx->getRowAllocator(helper.queryInputMeta(), activityId);
  13912. Owned<IEngineRowAllocator> outputAllocator = codectx->getRowAllocator(helper.queryOutputMeta(), activityId);
  13913. processor.beforeProcessing(inputAllocator, outputAllocator);
  13914. }
  13915. virtual void stop(bool aborting)
  13916. {
  13917. processor.afterProcessing();
  13918. CRoxieServerNaryActivity::stop(aborting);
  13919. }
  13920. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  13921. {
  13922. return processor.gatherConjunctions(collector);
  13923. }
  13924. virtual void resetEOF()
  13925. {
  13926. processor.queryResetEOF();
  13927. }
  13928. virtual const void * nextInGroup()
  13929. {
  13930. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13931. const void * next = processor.nextInGroup();
  13932. if (next)
  13933. processed++;
  13934. return next;
  13935. }
  13936. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  13937. {
  13938. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13939. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  13940. if (next)
  13941. processed++;
  13942. return next;
  13943. }
  13944. virtual IInputSteppingMeta * querySteppingMeta()
  13945. {
  13946. return processor.queryInputSteppingMeta();
  13947. }
  13948. protected:
  13949. IHThorNWayMergeJoinArg & helper;
  13950. CMergeJoinProcessor & processor;
  13951. };
  13952. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  13953. {
  13954. public:
  13955. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13956. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  13957. {
  13958. }
  13959. protected:
  13960. CAndMergeJoinProcessor andProcessor;
  13961. };
  13962. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  13963. {
  13964. public:
  13965. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13966. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  13967. {
  13968. }
  13969. protected:
  13970. CAndLeftMergeJoinProcessor andLeftProcessor;
  13971. };
  13972. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  13973. {
  13974. public:
  13975. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13976. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  13977. {
  13978. }
  13979. protected:
  13980. CMofNMergeJoinProcessor mofnProcessor;
  13981. };
  13982. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  13983. {
  13984. public:
  13985. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13986. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  13987. {
  13988. }
  13989. protected:
  13990. CProximityJoinProcessor proximityProcessor;
  13991. };
  13992. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  13993. {
  13994. unsigned flags;
  13995. public:
  13996. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13997. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13998. {
  13999. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14000. flags = helper->getJoinFlags();
  14001. }
  14002. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14003. {
  14004. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14005. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14006. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14007. {
  14008. case IHThorNWayMergeJoinArg::MJFinner:
  14009. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14010. case IHThorNWayMergeJoinArg::MJFleftonly:
  14011. case IHThorNWayMergeJoinArg::MJFleftouter:
  14012. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14013. case IHThorNWayMergeJoinArg::MJFmofn:
  14014. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14015. default:
  14016. throwUnexpected();
  14017. }
  14018. }
  14019. };
  14020. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14021. {
  14022. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14023. }
  14024. //=================================================================================
  14025. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14026. {
  14027. IHThorNWaySelectArg &helper;
  14028. public:
  14029. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14030. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14031. helper((IHThorNWaySelectArg &)basehelper)
  14032. {
  14033. }
  14034. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14035. {
  14036. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14037. unsigned whichInput = helper.getInputIndex();
  14038. selectedInput = NULL;
  14039. if (whichInput--)
  14040. {
  14041. for (unsigned i=0; i < numInputs; i++)
  14042. {
  14043. IRoxieInput * cur = inputArray[i];
  14044. unsigned numRealInputs = cur->numConcreteOutputs();
  14045. if (whichInput < numRealInputs)
  14046. {
  14047. selectedInput = cur->queryConcreteInput(whichInput);
  14048. break;
  14049. }
  14050. whichInput -= numRealInputs;
  14051. }
  14052. }
  14053. }
  14054. virtual void reset()
  14055. {
  14056. selectedInput = NULL;
  14057. CRoxieServerMultiInputActivity::reset();
  14058. }
  14059. const void * nextInGroup()
  14060. {
  14061. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14062. if (!selectedInput)
  14063. return NULL;
  14064. return selectedInput->nextInGroup();
  14065. }
  14066. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14067. {
  14068. if (!selectedInput)
  14069. return false;
  14070. return selectedInput->gatherConjunctions(collector);
  14071. }
  14072. virtual void resetEOF()
  14073. {
  14074. if (selectedInput)
  14075. selectedInput->resetEOF();
  14076. }
  14077. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14078. {
  14079. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14080. if (!selectedInput)
  14081. return NULL;
  14082. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14083. }
  14084. IInputSteppingMeta * querySteppingMeta()
  14085. {
  14086. if (selectedInput)
  14087. return selectedInput->querySteppingMeta();
  14088. return NULL;
  14089. }
  14090. protected:
  14091. IRoxieInput * selectedInput;
  14092. };
  14093. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14094. {
  14095. public:
  14096. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14097. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14098. {
  14099. }
  14100. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14101. {
  14102. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14103. }
  14104. };
  14105. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14106. {
  14107. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14108. }
  14109. //=================================================================================
  14110. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14111. {
  14112. protected:
  14113. IHThorRemoteArg &helper;
  14114. CRemoteResultAdaptor remote;
  14115. public:
  14116. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14117. : CRoxieServerActivity(_factory, _probeManager),
  14118. helper((IHThorRemoteArg &)basehelper),
  14119. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14120. {
  14121. }
  14122. virtual const IResolvedFile *queryVarFileInfo() const
  14123. {
  14124. return NULL;
  14125. }
  14126. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14127. {
  14128. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14129. remote.onCreate(this, this, _ctx, _colocalParent);
  14130. }
  14131. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14132. {
  14133. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14134. remote.onStart(parentExtractSize, parentExtract);
  14135. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14136. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14137. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14138. remote.flush();
  14139. remote.senddone();
  14140. }
  14141. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14142. {
  14143. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14144. }
  14145. virtual IRoxieInput *queryOutput(unsigned idx)
  14146. {
  14147. if (idx==(unsigned)-1)
  14148. idx = 0;
  14149. return idx ? NULL: &remote;
  14150. }
  14151. virtual void reset()
  14152. {
  14153. processed = remote.processed;
  14154. remote.processed = 0;
  14155. CRoxieServerActivity::reset();
  14156. }
  14157. virtual void onLimitExceeded(bool isKeyed)
  14158. {
  14159. if (traceLevel > 4)
  14160. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14161. helper.onLimitExceeded();
  14162. }
  14163. virtual const void *createLimitFailRow(bool isKeyed)
  14164. {
  14165. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14166. }
  14167. virtual const void *nextInGroup()
  14168. {
  14169. throwUnexpected(); // I am nobody's input
  14170. }
  14171. };
  14172. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14173. {
  14174. public:
  14175. RemoteActivityId remoteId;
  14176. bool isRoot;
  14177. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14178. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14179. {
  14180. }
  14181. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14182. {
  14183. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14184. }
  14185. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14186. {
  14187. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14188. }
  14189. virtual bool isSink() const
  14190. {
  14191. //I don't think the action version of this is implemented - but this would be the code
  14192. return isRoot && !meta.queryOriginal();
  14193. }
  14194. };
  14195. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14196. {
  14197. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14198. }
  14199. //=================================================================================
  14200. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14201. {
  14202. IHThorIterateArg &helper;
  14203. OwnedConstRoxieRow defaultRecord;
  14204. OwnedConstRoxieRow left;
  14205. OwnedConstRoxieRow right;
  14206. unsigned counter;
  14207. public:
  14208. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14209. : CRoxieServerActivity(_factory, _probeManager),
  14210. helper((IHThorIterateArg &)basehelper)
  14211. {
  14212. counter = 0;
  14213. }
  14214. virtual bool needsAllocator() const { return true; }
  14215. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14216. {
  14217. counter = 0;
  14218. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14219. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14220. size32_t thisSize = helper.createDefault(rowBuilder);
  14221. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14222. }
  14223. virtual void reset()
  14224. {
  14225. defaultRecord.clear();
  14226. right.clear();
  14227. left.clear();
  14228. CRoxieServerActivity::reset();
  14229. }
  14230. virtual const void * nextInGroup()
  14231. {
  14232. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14233. loop
  14234. {
  14235. right.setown(input->nextInGroup());
  14236. if (!right)
  14237. {
  14238. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14239. left.clear();
  14240. counter = 0;
  14241. if (skippedGroup) continue;
  14242. return NULL;
  14243. }
  14244. try
  14245. {
  14246. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14247. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14248. if (outSize)
  14249. {
  14250. left.setown(rowBuilder.finalizeRowClear(outSize));
  14251. processed++;
  14252. return left.getLink();
  14253. }
  14254. }
  14255. catch (IException *E)
  14256. {
  14257. throw makeWrappedException(E);
  14258. }
  14259. }
  14260. }
  14261. };
  14262. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14263. {
  14264. public:
  14265. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14266. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14267. {
  14268. }
  14269. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14270. {
  14271. return new CRoxieServerIterateActivity(this, _probeManager);
  14272. }
  14273. };
  14274. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14275. {
  14276. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14277. }
  14278. //=================================================================================
  14279. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14280. {
  14281. IHThorProcessArg &helper;
  14282. OwnedConstRoxieRow curRight;
  14283. OwnedConstRoxieRow initialRight;
  14284. unsigned counter;
  14285. Owned<IEngineRowAllocator> rightRowAllocator;
  14286. public:
  14287. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14288. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14289. {
  14290. counter = 0;
  14291. }
  14292. virtual bool needsAllocator() const { return true; }
  14293. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14294. {
  14295. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14296. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14297. }
  14298. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14299. {
  14300. counter = 0;
  14301. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14302. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14303. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14304. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14305. curRight.set(initialRight);
  14306. }
  14307. virtual const void * nextInGroup()
  14308. {
  14309. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14310. try
  14311. {
  14312. loop
  14313. {
  14314. const void * in = input->nextInGroup();
  14315. if (!in)
  14316. {
  14317. bool eog = (curRight != initialRight); // processed any records?
  14318. counter = 0;
  14319. curRight.set(initialRight);
  14320. if (eog)
  14321. return NULL;
  14322. in = input->nextInGroup();
  14323. if (!in)
  14324. return NULL;
  14325. }
  14326. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14327. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14328. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14329. ReleaseRoxieRow(in);
  14330. if (outSize)
  14331. {
  14332. //MORE: This should be returned...
  14333. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14334. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14335. processed++;
  14336. return rowBuilder.finalizeRowClear(outSize);
  14337. }
  14338. }
  14339. }
  14340. catch (IException *E)
  14341. {
  14342. throw makeWrappedException(E);
  14343. }
  14344. }
  14345. };
  14346. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14347. {
  14348. public:
  14349. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14350. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14351. {
  14352. }
  14353. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14354. {
  14355. return new CRoxieServerProcessActivity(this, _probeManager);
  14356. }
  14357. };
  14358. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14359. {
  14360. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14361. }
  14362. //=================================================================================
  14363. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14364. {
  14365. IHThorGroupArg &helper;
  14366. bool endPending;
  14367. bool eof;
  14368. bool first;
  14369. const void *next;
  14370. public:
  14371. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14372. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14373. {
  14374. next = NULL;
  14375. endPending = false;
  14376. eof = false;
  14377. first = true;
  14378. }
  14379. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14380. {
  14381. endPending = false;
  14382. eof = false;
  14383. first = true;
  14384. assertex(next == NULL);
  14385. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14386. }
  14387. virtual void reset()
  14388. {
  14389. ReleaseClearRoxieRow(next);
  14390. CRoxieServerActivity::reset();
  14391. }
  14392. virtual const void * nextInGroup()
  14393. {
  14394. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14395. if (first)
  14396. {
  14397. next = input->nextInGroup();
  14398. first = false;
  14399. }
  14400. if (eof || endPending)
  14401. {
  14402. endPending = false;
  14403. return NULL;
  14404. }
  14405. const void * prev = next;
  14406. next = input->nextInGroup();
  14407. if (!next)
  14408. next = input->nextInGroup();
  14409. if (next)
  14410. {
  14411. assertex(prev);
  14412. if (!helper.isSameGroup(prev, next))
  14413. endPending = true;
  14414. }
  14415. else
  14416. eof = true;
  14417. if (prev)
  14418. processed++;
  14419. return prev;
  14420. }
  14421. };
  14422. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14423. {
  14424. public:
  14425. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14426. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14427. {
  14428. }
  14429. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14430. {
  14431. return new CRoxieServerGroupActivity(this, _probeManager);
  14432. }
  14433. };
  14434. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14435. {
  14436. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14437. }
  14438. //=================================================================================
  14439. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14440. {
  14441. unsigned __int64 limit;
  14442. unsigned __int64 skip;
  14443. unsigned doneThisGroup;
  14444. IHThorFirstNArg &helper;
  14445. public:
  14446. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14447. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14448. {
  14449. doneThisGroup = 0;
  14450. limit = 0;
  14451. skip = 0;
  14452. }
  14453. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14454. {
  14455. doneThisGroup = 0;
  14456. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14457. limit = helper.getLimit();
  14458. skip = helper.numToSkip();
  14459. lateStart(parentExtractSize, parentExtract, limit > 0);
  14460. if (limit + skip >= limit)
  14461. limit += skip;
  14462. }
  14463. const void * nextInGroup()
  14464. {
  14465. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14466. if (eof)
  14467. return NULL;
  14468. const void *ret;
  14469. loop
  14470. {
  14471. ret = input->nextInGroup();
  14472. if (!ret)
  14473. {
  14474. if (meta.isGrouped())
  14475. {
  14476. if (doneThisGroup > skip)
  14477. {
  14478. doneThisGroup = 0;
  14479. return NULL;
  14480. }
  14481. doneThisGroup = 0;
  14482. }
  14483. ret = input->nextInGroup();
  14484. if (!ret)
  14485. {
  14486. eof = true;
  14487. return NULL;
  14488. }
  14489. }
  14490. doneThisGroup++;
  14491. if (doneThisGroup > skip)
  14492. break;
  14493. ReleaseRoxieRow(ret);
  14494. }
  14495. if (doneThisGroup <= limit)
  14496. {
  14497. processed++;
  14498. return ret;
  14499. }
  14500. ReleaseRoxieRow(ret);
  14501. if (meta.isGrouped())
  14502. {
  14503. while ((ret = input->nextInGroup()) != NULL)
  14504. ReleaseRoxieRow(ret);
  14505. doneThisGroup = 0;
  14506. }
  14507. else
  14508. eof = true;
  14509. return NULL;
  14510. }
  14511. };
  14512. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  14513. {
  14514. public:
  14515. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14516. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14517. {
  14518. }
  14519. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14520. {
  14521. return new CRoxieServerFirstNActivity(this, _probeManager);
  14522. }
  14523. };
  14524. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14525. {
  14526. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14527. }
  14528. //=================================================================================
  14529. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  14530. {
  14531. bool done;
  14532. IHThorSelectNArg &helper;
  14533. public:
  14534. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14535. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  14536. {
  14537. done = false;
  14538. }
  14539. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14540. {
  14541. done = false;
  14542. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14543. }
  14544. const void *defaultRow()
  14545. {
  14546. if (!rowAllocator)
  14547. createRowAllocator(); // We delay as often not needed...
  14548. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14549. size32_t thisSize = helper.createDefault(rowBuilder);
  14550. return rowBuilder.finalizeRowClear(thisSize);
  14551. }
  14552. virtual const void * nextInGroup()
  14553. {
  14554. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14555. if (done)
  14556. return NULL;
  14557. done = true;
  14558. processed++; // always going to return a row!
  14559. unsigned __int64 index = helper.getRowToSelect();
  14560. while (--index)
  14561. {
  14562. const void * next = input->nextInGroup();
  14563. if (!next)
  14564. next = input->nextInGroup();
  14565. if (!next)
  14566. return defaultRow();
  14567. ReleaseRoxieRow(next);
  14568. }
  14569. const void * next = input->nextInGroup();
  14570. if (!next)
  14571. next = input->nextInGroup();
  14572. if (!next)
  14573. next = defaultRow();
  14574. return next;
  14575. }
  14576. };
  14577. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  14578. {
  14579. public:
  14580. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14581. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14582. {
  14583. }
  14584. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14585. {
  14586. return new CRoxieServerSelectNActivity(this, _probeManager);
  14587. }
  14588. };
  14589. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14590. {
  14591. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14592. }
  14593. //=================================================================================
  14594. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  14595. {
  14596. IHThorJoinArg &helper;
  14597. ICompare *collate;
  14598. OwnedRowArray group;
  14599. bool matchedLeft;
  14600. BoolArray matchedRight;
  14601. bool eof;
  14602. bool first;
  14603. unsigned leftIndex;
  14604. unsigned rightIndex;
  14605. unsigned rightOuterIndex;
  14606. unsigned joinLimit;
  14607. unsigned atmostLimit;
  14608. unsigned atmostsTriggered;
  14609. unsigned abortLimit;
  14610. unsigned keepLimit;
  14611. bool leftOuterJoin;
  14612. bool rightOuterJoin;
  14613. bool exclude;
  14614. bool limitFail;
  14615. bool limitOnFail;
  14616. bool cloneLeft;
  14617. OwnedConstRoxieRow defaultLeft;
  14618. OwnedConstRoxieRow defaultRight;
  14619. OwnedConstRoxieRow lhs;
  14620. Owned<IException> failingLimit;
  14621. bool failingOuterAtmost;
  14622. Owned<IEngineRowAllocator> defaultAllocator;
  14623. Owned<IRHLimitedCompareHelper> limitedhelper;
  14624. Owned<CRHDualCache> dualcache;
  14625. IInputBase *dualCacheInput;
  14626. bool fillGroup()
  14627. {
  14628. group.clear();
  14629. matchedLeft = false;
  14630. matchedRight.kill();
  14631. failingOuterAtmost = false;
  14632. const void * next;
  14633. unsigned groupCount = 0;
  14634. while((next = input->nextInGroup()) != NULL)
  14635. {
  14636. if(groupCount==abortLimit)
  14637. {
  14638. if(limitFail)
  14639. failLimit(next);
  14640. if (ctx->queryDebugContext())
  14641. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  14642. if(limitOnFail)
  14643. {
  14644. assertex(!failingLimit);
  14645. try
  14646. {
  14647. failLimit(next);
  14648. }
  14649. catch(IException * except)
  14650. {
  14651. failingLimit.setown(except);
  14652. }
  14653. assertex(failingLimit != NULL);
  14654. group.append(next);
  14655. groupCount++;
  14656. break;
  14657. }
  14658. group.clear();
  14659. groupCount = 0;
  14660. while(next)
  14661. {
  14662. ReleaseRoxieRow(next);
  14663. next = input->nextInGroup();
  14664. }
  14665. }
  14666. else if(groupCount==atmostLimit)
  14667. {
  14668. atmostsTriggered++;
  14669. if(leftOuterJoin)
  14670. {
  14671. group.append(next);
  14672. groupCount++;
  14673. failingOuterAtmost = true;
  14674. break;
  14675. }
  14676. else
  14677. {
  14678. group.clear();
  14679. groupCount = 0;
  14680. while (next)
  14681. {
  14682. ReleaseRoxieRow(next);
  14683. next = input->nextInGroup();
  14684. }
  14685. }
  14686. }
  14687. else
  14688. {
  14689. group.append(next);
  14690. groupCount++;
  14691. }
  14692. }
  14693. if(group.ordinality()==0)
  14694. {
  14695. eof = true;
  14696. return false;
  14697. }
  14698. leftIndex = 0;
  14699. rightIndex = 0;
  14700. rightOuterIndex = 0;
  14701. joinLimit = keepLimit;
  14702. ForEachItemIn(idx, group)
  14703. matchedRight.append(false);
  14704. return true;
  14705. }
  14706. void failLimit(const void * next)
  14707. {
  14708. helper.onMatchAbortLimitExceeded();
  14709. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  14710. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  14711. {
  14712. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  14713. }
  14714. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  14715. }
  14716. virtual bool needsAllocator() const { return true; }
  14717. const void *joinRecords(const void * curLeft, const void * curRight, IException * except = NULL)
  14718. {
  14719. try
  14720. {
  14721. if (cloneLeft && !except)
  14722. {
  14723. LinkRoxieRow(curLeft);
  14724. return curLeft;
  14725. }
  14726. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14727. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight);
  14728. if (outsize)
  14729. return rowBuilder.finalizeRowClear(outsize);
  14730. else
  14731. return NULL;
  14732. }
  14733. catch (IException *E)
  14734. {
  14735. throw makeWrappedException(E);
  14736. }
  14737. }
  14738. void createDefaultLeft()
  14739. {
  14740. if (!defaultLeft)
  14741. {
  14742. if (!defaultAllocator)
  14743. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14744. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14745. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  14746. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  14747. }
  14748. }
  14749. void createDefaultRight()
  14750. {
  14751. if (!defaultRight)
  14752. {
  14753. if (!defaultAllocator)
  14754. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14755. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14756. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  14757. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14758. }
  14759. }
  14760. public:
  14761. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14762. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  14763. {
  14764. collate = helper.queryCompareLeftRight();
  14765. eof = false;
  14766. first = true;
  14767. keepLimit = 0;
  14768. atmostLimit = 0;
  14769. atmostsTriggered = 0;
  14770. unsigned joinFlags = helper.getJoinFlags();
  14771. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  14772. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  14773. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  14774. exclude = (joinFlags & JFexclude) != 0;
  14775. abortLimit = 0;
  14776. joinLimit = 0;
  14777. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  14778. getLimitType(joinFlags, limitFail, limitOnFail);
  14779. if((joinFlags & JFslidingmatch) != 0)
  14780. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  14781. failingOuterAtmost = false;
  14782. matchedLeft = false;
  14783. leftIndex = 0;
  14784. rightIndex = 0;
  14785. rightOuterIndex = 0;
  14786. dualCacheInput = NULL;
  14787. }
  14788. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14789. {
  14790. eof = false;
  14791. first = true;
  14792. failingLimit.clear();
  14793. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14794. keepLimit = helper.getKeepLimit();
  14795. if(keepLimit == 0)
  14796. keepLimit = (unsigned)-1;
  14797. atmostsTriggered = 0;
  14798. atmostLimit = helper.getJoinLimit();
  14799. if(atmostLimit == 0)
  14800. atmostLimit = (unsigned)-1;
  14801. else
  14802. assertex(!rightOuterJoin);
  14803. abortLimit = helper.getMatchAbortLimit();
  14804. if (abortLimit == 0)
  14805. abortLimit = (unsigned)-1;
  14806. if (rightOuterJoin)
  14807. createDefaultLeft();
  14808. if (leftOuterJoin || limitOnFail)
  14809. createDefaultRight();
  14810. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  14811. { //limited match join (s[1..n])
  14812. dualcache.setown(new CRHDualCache());
  14813. dualcache->init(CRoxieServerActivity::input);
  14814. dualCacheInput = dualcache->queryOut1();
  14815. failingOuterAtmost = false;
  14816. matchedLeft = false;
  14817. leftIndex = 0;
  14818. rightOuterIndex = 0;
  14819. limitedhelper.setown(createRHLimitedCompareHelper());
  14820. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  14821. }
  14822. }
  14823. virtual void reset()
  14824. {
  14825. if (atmostsTriggered)
  14826. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  14827. group.clear();
  14828. CRoxieServerActivity::reset();
  14829. defaultLeft.clear();
  14830. defaultRight.clear();
  14831. }
  14832. virtual const void * nextInGroup()
  14833. {
  14834. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14835. if (limitedhelper)
  14836. {
  14837. while(!eof) //limited match join
  14838. {
  14839. if (!group.isItem(rightIndex))
  14840. {
  14841. lhs.setown(dualCacheInput->nextInGroup());
  14842. if (lhs)
  14843. {
  14844. rightIndex = 0;
  14845. group.clear();
  14846. limitedhelper->getGroup(group,lhs);
  14847. }
  14848. else
  14849. {
  14850. eof = true;
  14851. }
  14852. }
  14853. if (group.isItem(rightIndex))
  14854. {
  14855. const void * rhs = group.item(rightIndex++);
  14856. if(helper.match(lhs, rhs))
  14857. {
  14858. const void * ret = joinRecords(lhs, rhs);
  14859. return ret;
  14860. }
  14861. }
  14862. }
  14863. return NULL;
  14864. }
  14865. else
  14866. {
  14867. if (first)
  14868. {
  14869. first = false;
  14870. fillGroup();
  14871. }
  14872. while(!eof)
  14873. {
  14874. if(failingOuterAtmost)
  14875. while(group.isItem(leftIndex))
  14876. {
  14877. const void * ret = joinRecords(group.item(leftIndex++), defaultRight);
  14878. if(ret)
  14879. {
  14880. processed++;
  14881. return ret;
  14882. }
  14883. }
  14884. if((joinLimit == 0) || !group.isItem(rightIndex))
  14885. {
  14886. if(leftOuterJoin && !matchedLeft && !failingLimit)
  14887. {
  14888. const void * ret = joinRecords(group.item(leftIndex), defaultRight);
  14889. if(ret)
  14890. {
  14891. matchedLeft = true;
  14892. processed++;
  14893. return ret;
  14894. }
  14895. }
  14896. leftIndex++;
  14897. matchedLeft = false;
  14898. rightIndex = 0;
  14899. joinLimit = keepLimit;
  14900. }
  14901. if(!group.isItem(leftIndex))
  14902. {
  14903. if(failingLimit || failingOuterAtmost)
  14904. {
  14905. const void * lhs;
  14906. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  14907. {
  14908. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  14909. ReleaseRoxieRow(lhs);
  14910. if(ret)
  14911. {
  14912. processed++;
  14913. return ret;
  14914. }
  14915. }
  14916. failingLimit.clear();
  14917. }
  14918. if(rightOuterJoin && !failingLimit)
  14919. while(group.isItem(rightOuterIndex))
  14920. if(!matchedRight.item(rightOuterIndex++))
  14921. {
  14922. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1));
  14923. if(ret)
  14924. {
  14925. processed++;
  14926. return ret;
  14927. }
  14928. }
  14929. if(!fillGroup())
  14930. return NULL;
  14931. continue;
  14932. }
  14933. const void * lhs = group.item(leftIndex);
  14934. if(failingLimit)
  14935. {
  14936. leftIndex++;
  14937. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  14938. if(ret)
  14939. {
  14940. processed++;
  14941. return ret;
  14942. }
  14943. }
  14944. else
  14945. {
  14946. const void * rhs = group.item(rightIndex++);
  14947. if(helper.match(lhs, rhs))
  14948. {
  14949. matchedLeft = true;
  14950. matchedRight.replace(true, rightIndex-1);
  14951. if(!exclude)
  14952. {
  14953. const void * ret = joinRecords(lhs, rhs);
  14954. if(ret)
  14955. {
  14956. processed++;
  14957. joinLimit--;
  14958. return ret;
  14959. }
  14960. }
  14961. }
  14962. }
  14963. }
  14964. return NULL;
  14965. }
  14966. }
  14967. };
  14968. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  14969. {
  14970. public:
  14971. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14972. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14973. {
  14974. }
  14975. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14976. {
  14977. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  14978. }
  14979. };
  14980. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14981. {
  14982. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14983. }
  14984. //=====================================================================================================
  14985. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  14986. {
  14987. private:
  14988. class LookupTable : public CInterface
  14989. {
  14990. public:
  14991. LookupTable(unsigned _size, ICompare * _leftRightCompare, ICompare * _rightCompare, IHash * _leftHash, IHash * _rightHash, bool _dedupOnAdd)
  14992. : leftRightCompare(_leftRightCompare), rightCompare(_rightCompare), leftHash(_leftHash), rightHash(_rightHash), dedupOnAdd(_dedupOnAdd)
  14993. {
  14994. unsigned minsize = (4*_size)/3;
  14995. size = 2;
  14996. while((minsize >>= 1) > 0)
  14997. size <<= 1;
  14998. mask = size - 1;
  14999. table = (const void * *)calloc(size, sizeof(void *));
  15000. findex = BadIndex;
  15001. }
  15002. ~LookupTable()
  15003. {
  15004. unsigned i;
  15005. for(i=0; i<size; i++)
  15006. ReleaseRoxieRow(table[i]);
  15007. free(table);
  15008. }
  15009. void add(const void * right)
  15010. {
  15011. findex = BadIndex;
  15012. unsigned start = rightHash->hash(right) & mask;
  15013. unsigned index = start;
  15014. while(table[index])
  15015. {
  15016. if(dedupOnAdd && (rightCompare->docompare(table[index], right) == 0))
  15017. {
  15018. ReleaseRoxieRow(right);
  15019. return;
  15020. }
  15021. index++;
  15022. if(index==size)
  15023. index = 0;
  15024. if(index==start)
  15025. throwUnexpected(); //table is full, should never happen
  15026. }
  15027. table[index] = right;
  15028. }
  15029. const void *find(const void * left) const
  15030. {
  15031. fstart = leftHash->hash(left) & mask;
  15032. findex = fstart;
  15033. return doFind(left);
  15034. }
  15035. const void *findNext(const void * left) const
  15036. {
  15037. if(findex == BadIndex)
  15038. return NULL;
  15039. advance();
  15040. return doFind(left);
  15041. }
  15042. void advance() const
  15043. {
  15044. findex++;
  15045. if(findex==size)
  15046. findex = 0;
  15047. if(findex==fstart)
  15048. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error hthor lookup join activity (hash table full on lookup)");
  15049. }
  15050. const void *doFind(const void * left) const
  15051. {
  15052. while(table[findex])
  15053. {
  15054. if(leftRightCompare->docompare(left, table[findex]) == 0)
  15055. return table[findex];
  15056. advance();
  15057. }
  15058. findex = BadIndex;
  15059. return NULL;
  15060. }
  15061. private:
  15062. ICompare * leftRightCompare;
  15063. ICompare * rightCompare;
  15064. IHash * leftHash;
  15065. IHash * rightHash;
  15066. unsigned size;
  15067. unsigned mask;
  15068. const void * * table;
  15069. bool dedupOnAdd;
  15070. unsigned mutable fstart;
  15071. unsigned mutable findex;
  15072. static unsigned const BadIndex;
  15073. };
  15074. IHThorHashJoinArg &helper;
  15075. bool leftOuterJoin;
  15076. bool exclude;
  15077. bool eog;
  15078. bool many;
  15079. bool dedupRHS;
  15080. bool matchedGroup;
  15081. const void *left;
  15082. OwnedConstRoxieRow defaultRight;
  15083. Owned<LookupTable> table;
  15084. unsigned keepLimit;
  15085. unsigned atmostLimit;
  15086. unsigned atmostsTriggered;
  15087. unsigned limitLimit;
  15088. bool limitFail;
  15089. bool limitOnFail;
  15090. bool hasGroupLimit;
  15091. unsigned keepCount;
  15092. bool gotMatch;
  15093. bool cloneLeft;
  15094. ConstPointerArray rightGroup;
  15095. aindex_t rightGroupIndex;
  15096. Owned<IException> failingLimit;
  15097. ConstPointerArray filteredRight;
  15098. ThorActivityKind activityKind;
  15099. Owned<IEngineRowAllocator> defaultRightAllocator;
  15100. void createDefaultRight()
  15101. {
  15102. if (!defaultRight)
  15103. {
  15104. if (!defaultRightAllocator)
  15105. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15106. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15107. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15108. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15109. }
  15110. }
  15111. public:
  15112. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15113. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper)
  15114. {
  15115. unsigned joinFlags = helper.getJoinFlags();
  15116. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15117. assertex((joinFlags & JFrightouter) == 0);
  15118. exclude = (joinFlags & JFexclude) != 0;
  15119. many = (joinFlags & JFmanylookup) != 0;
  15120. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15121. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15122. left = NULL;
  15123. activityKind = factory->getKind();
  15124. eog = false;
  15125. matchedGroup = false;
  15126. gotMatch = false;
  15127. keepLimit = 0;
  15128. keepCount = 0;
  15129. atmostLimit = 0;
  15130. atmostsTriggered = 0;
  15131. limitLimit = 0;
  15132. hasGroupLimit = false;
  15133. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15134. }
  15135. void loadRight()
  15136. {
  15137. ConstPointerArray rightset;
  15138. unsigned i = 0;
  15139. try
  15140. {
  15141. const void * next;
  15142. while(true)
  15143. {
  15144. next = input1->nextInGroup();
  15145. if(!next)
  15146. next = input1->nextInGroup();
  15147. if(!next)
  15148. break;
  15149. rightset.append(next);
  15150. }
  15151. unsigned rightord = rightset.ordinality();
  15152. table.setown(new LookupTable(rightord, helper.queryCompareLeftRight(), helper.queryCompareRight(), helper.queryHashLeft(), helper.queryHashRight(), dedupRHS));
  15153. for(i=0; i<rightord; i++)
  15154. table->add(rightset.item(i));
  15155. }
  15156. catch (...)
  15157. {
  15158. unsigned rightord = rightset.ordinality();
  15159. for ( ; i<rightord; i++)
  15160. ReleaseRoxieRow(rightset.item(i));
  15161. throw;
  15162. }
  15163. };
  15164. virtual void reset()
  15165. {
  15166. if (atmostsTriggered)
  15167. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15168. CRoxieServerTwoInputActivity::reset();
  15169. ReleaseClearRoxieRow(left);
  15170. defaultRight.clear();
  15171. table.clear();
  15172. }
  15173. virtual bool needsAllocator() const { return true; }
  15174. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15175. {
  15176. eog = false;
  15177. matchedGroup = false;
  15178. left = NULL;
  15179. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15180. keepLimit = helper.getKeepLimit();
  15181. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15182. atmostsTriggered = 0;
  15183. atmostLimit = helper.getJoinLimit();
  15184. limitLimit = helper.getMatchAbortLimit();
  15185. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15186. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15187. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15188. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15189. if (((activityKind==TAKlookupjoin || activityKind==TAKlookupdenormalizegroup) && leftOuterJoin) || limitOnFail)
  15190. createDefaultRight();
  15191. }
  15192. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15193. {
  15194. if (idx==1)
  15195. input1 = _in;
  15196. else
  15197. {
  15198. if ((helper.getJoinFlags() & JFparallel) != 0)
  15199. {
  15200. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15201. puller->setInput(0, _in);
  15202. _in = puller;
  15203. }
  15204. CRoxieServerActivity::setInput(idx, _in);
  15205. }
  15206. }
  15207. virtual const void * nextInGroup()
  15208. {
  15209. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15210. if(!table)
  15211. loadRight();
  15212. switch (activityKind)
  15213. {
  15214. case TAKlookupjoin:
  15215. return nextInGroupJoin();
  15216. case TAKlookupdenormalize:
  15217. case TAKlookupdenormalizegroup:
  15218. return nextInGroupDenormalize();
  15219. }
  15220. throwUnexpected();
  15221. }
  15222. private:
  15223. const void * nextInGroupJoin()
  15224. {
  15225. if(!table)
  15226. loadRight();
  15227. while(true)
  15228. {
  15229. const void * right = NULL;
  15230. if(!left)
  15231. {
  15232. left = input->nextInGroup();
  15233. keepCount = keepLimit;
  15234. if(!left)
  15235. {
  15236. if(matchedGroup || eog)
  15237. {
  15238. matchedGroup = false;
  15239. eog = true;
  15240. return NULL;
  15241. }
  15242. eog = true;
  15243. continue;
  15244. }
  15245. eog = false;
  15246. gotMatch = false;
  15247. right = getRightFirst();
  15248. }
  15249. else
  15250. right = getRightNext();
  15251. const void * ret = NULL;
  15252. if(failingLimit)
  15253. {
  15254. ret = joinException(left, failingLimit);
  15255. }
  15256. else
  15257. {
  15258. while(right)
  15259. {
  15260. if(helper.match(left, right))
  15261. {
  15262. gotMatch = true;
  15263. if(exclude)
  15264. break;
  15265. ret = joinRecords(left, right);
  15266. if(ret)
  15267. break;
  15268. }
  15269. right = getRightNext();
  15270. ret = NULL;
  15271. }
  15272. if(leftOuterJoin && !gotMatch)
  15273. {
  15274. ret = joinRecords(left, defaultRight);
  15275. gotMatch = true;
  15276. }
  15277. }
  15278. if(ret)
  15279. {
  15280. matchedGroup = true;
  15281. processed++;
  15282. if(!many || (--keepCount == 0) || failingLimit)
  15283. {
  15284. ReleaseClearRoxieRow(left);
  15285. failingLimit.clear();
  15286. }
  15287. return ret;
  15288. }
  15289. ReleaseClearRoxieRow(left);
  15290. }
  15291. }
  15292. const void * nextInGroupDenormalize()
  15293. {
  15294. while(true)
  15295. {
  15296. left = input->nextInGroup();
  15297. if(!left)
  15298. {
  15299. if (!matchedGroup)
  15300. left = input->nextInGroup();
  15301. if (!left)
  15302. {
  15303. matchedGroup = false;
  15304. return NULL;
  15305. }
  15306. }
  15307. gotMatch = false;
  15308. const void * right = getRightFirst();
  15309. const void * ret = NULL;
  15310. if (failingLimit)
  15311. ret = joinException(left, failingLimit);
  15312. else if (activityKind == TAKlookupdenormalize)
  15313. {
  15314. OwnedConstRoxieRow newLeft;
  15315. newLeft.set(left);
  15316. unsigned rowSize = 0;
  15317. unsigned leftCount = 0;
  15318. keepCount = keepLimit;
  15319. while (right)
  15320. {
  15321. try
  15322. {
  15323. if (helper.match(left, right))
  15324. {
  15325. gotMatch = true;
  15326. if (exclude)
  15327. break;
  15328. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15329. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15330. if (thisSize)
  15331. {
  15332. rowSize = thisSize;
  15333. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15334. }
  15335. if(!many || (--keepCount == 0))
  15336. break;
  15337. }
  15338. right = getRightNext();
  15339. }
  15340. catch (IException *E)
  15341. {
  15342. throw makeWrappedException(E);
  15343. }
  15344. }
  15345. if (rowSize)
  15346. ret = newLeft.getClear();
  15347. else if (leftOuterJoin && !gotMatch)
  15348. {
  15349. ret = left;
  15350. left = NULL;
  15351. }
  15352. }
  15353. else
  15354. {
  15355. filteredRight.kill();
  15356. keepCount = keepLimit;
  15357. while (right)
  15358. {
  15359. if (helper.match(left, right))
  15360. {
  15361. gotMatch = true;
  15362. if(exclude)
  15363. break;
  15364. filteredRight.append(right);
  15365. if(!many || (--keepCount == 0))
  15366. break;
  15367. }
  15368. right = getRightNext();
  15369. }
  15370. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  15371. ret = denormalizeRecords(left, filteredRight);
  15372. filteredRight.kill();
  15373. }
  15374. ReleaseRoxieRow(left);
  15375. left = NULL;
  15376. failingLimit.clear();
  15377. if(ret)
  15378. {
  15379. matchedGroup = true;
  15380. processed++;
  15381. return ret;
  15382. }
  15383. }
  15384. }
  15385. const void * joinRecords(const void * left, const void * right)
  15386. {
  15387. if (cloneLeft)
  15388. {
  15389. LinkRoxieRow(left);
  15390. return left;
  15391. }
  15392. try
  15393. {
  15394. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15395. unsigned outSize = helper.transform(rowBuilder, left, right);
  15396. if (outSize)
  15397. return rowBuilder.finalizeRowClear(outSize);
  15398. else
  15399. return NULL;
  15400. }
  15401. catch (IException *E)
  15402. {
  15403. throw makeWrappedException(E);
  15404. }
  15405. }
  15406. const void * joinException(const void * left, IException * except)
  15407. {
  15408. try
  15409. {
  15410. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15411. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  15412. if (outSize)
  15413. return rowBuilder.finalizeRowClear(outSize);
  15414. else
  15415. return NULL;
  15416. }
  15417. catch (IException *E)
  15418. {
  15419. throw makeWrappedException(E);
  15420. }
  15421. }
  15422. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  15423. {
  15424. try
  15425. {
  15426. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15427. unsigned numRows = rows.ordinality();
  15428. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15429. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  15430. if (outSize)
  15431. return rowBuilder.finalizeRowClear(outSize);
  15432. else
  15433. return NULL;
  15434. }
  15435. catch (IException *E)
  15436. {
  15437. throw makeWrappedException(E);
  15438. }
  15439. }
  15440. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  15441. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  15442. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  15443. const void *fillRightGroup()
  15444. {
  15445. rightGroup.kill();
  15446. for(const void * right = table->find(left); right; right = table->findNext(left))
  15447. {
  15448. rightGroup.append(right);
  15449. if(rightGroup.ordinality() > limitLimit)
  15450. {
  15451. if(limitFail)
  15452. failLimit();
  15453. gotMatch = true;
  15454. if (ctx->queryDebugContext())
  15455. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15456. if(limitOnFail)
  15457. {
  15458. assertex(!failingLimit);
  15459. try
  15460. {
  15461. failLimit();
  15462. }
  15463. catch(IException * e)
  15464. {
  15465. failingLimit.setown(e);
  15466. }
  15467. assertex(failingLimit != NULL);
  15468. }
  15469. else
  15470. {
  15471. rightGroup.kill();
  15472. }
  15473. break;
  15474. }
  15475. if(rightGroup.ordinality() > atmostLimit)
  15476. {
  15477. atmostsTriggered++;
  15478. rightGroup.kill();
  15479. break;
  15480. }
  15481. }
  15482. rightGroupIndex = 0;
  15483. return readRightGroup();
  15484. }
  15485. void failLimit()
  15486. {
  15487. helper.onMatchAbortLimitExceeded();
  15488. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15489. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15490. {
  15491. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  15492. }
  15493. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  15494. }
  15495. };
  15496. unsigned const CRoxieServerLookupJoinActivity::LookupTable::BadIndex(static_cast<unsigned>(-1));
  15497. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  15498. {
  15499. public:
  15500. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15501. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15502. {
  15503. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  15504. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  15505. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  15506. }
  15507. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15508. {
  15509. return new CRoxieServerLookupJoinActivity(this, _probeManager);
  15510. }
  15511. };
  15512. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15513. {
  15514. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15515. }
  15516. //=====================================================================================================
  15517. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  15518. {
  15519. private:
  15520. IHThorAllJoinArg &helper;
  15521. bool leftOuterJoin;
  15522. bool rightOuterJoin;
  15523. bool exclude;
  15524. OwnedConstRoxieRow defaultRight;
  15525. OwnedConstRoxieRow defaultLeft;
  15526. Owned<IEngineRowAllocator> defaultRightAllocator;
  15527. Owned<IEngineRowAllocator> defaultLeftAllocator;
  15528. const void *left;
  15529. unsigned countForLeft;
  15530. ConstPointerArray rightset;
  15531. BoolArray matchedRight; // MORE - could use a bitset...
  15532. unsigned keepLimit;
  15533. bool started;
  15534. bool eog;
  15535. bool eos;
  15536. bool matchedLeft;
  15537. bool matchedGroup;
  15538. bool leftIsGrouped;
  15539. bool cloneLeft;
  15540. unsigned rightIndex;
  15541. unsigned rightOrdinality;
  15542. ThorActivityKind activityKind;
  15543. ConstPointerArray filteredRight;
  15544. void createDefaultLeft()
  15545. {
  15546. if (!defaultLeft)
  15547. {
  15548. if (!defaultLeftAllocator)
  15549. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15550. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  15551. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15552. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15553. }
  15554. }
  15555. void createDefaultRight()
  15556. {
  15557. if (!defaultRight)
  15558. {
  15559. if (!defaultRightAllocator)
  15560. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15561. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15562. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15563. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15564. }
  15565. }
  15566. public:
  15567. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15568. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  15569. {
  15570. unsigned joinFlags = helper.getJoinFlags();
  15571. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15572. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15573. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15574. keepLimit = (unsigned) -1;
  15575. exclude = (joinFlags & JFexclude) != 0;
  15576. left = NULL;
  15577. started = true;
  15578. eog = false;
  15579. eos = false;
  15580. matchedLeft = false;
  15581. matchedGroup = false;
  15582. activityKind = factory->getKind();
  15583. rightIndex = 0;
  15584. rightOrdinality = 0;
  15585. leftIsGrouped = false;
  15586. countForLeft = 0;
  15587. }
  15588. virtual void reset()
  15589. {
  15590. defaultRight.clear();
  15591. defaultLeft.clear();
  15592. ReleaseRoxieRowSet(rightset);
  15593. matchedRight.kill();
  15594. CRoxieServerTwoInputActivity::reset();
  15595. }
  15596. virtual bool needsAllocator() const { return true; }
  15597. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15598. {
  15599. eog = false;
  15600. eos = false;
  15601. matchedLeft = false;
  15602. matchedGroup = false;
  15603. started = false;
  15604. left = NULL;
  15605. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15606. keepLimit = helper.getKeepLimit();
  15607. if(keepLimit==0)
  15608. keepLimit = (unsigned) -1;
  15609. countForLeft = keepLimit;
  15610. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  15611. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  15612. createDefaultRight();
  15613. if(rightOuterJoin)
  15614. createDefaultLeft();
  15615. }
  15616. void loadRight()
  15617. {
  15618. const void * next;
  15619. while(true)
  15620. {
  15621. next = input1->nextInGroup();
  15622. if(!next)
  15623. next = input1->nextInGroup();
  15624. if(!next)
  15625. break;
  15626. rightset.append(next);
  15627. matchedRight.append(false);
  15628. }
  15629. rightIndex = 0;
  15630. rightOrdinality = rightset.ordinality();
  15631. }
  15632. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15633. {
  15634. if (idx==1)
  15635. input1 = _in;
  15636. else
  15637. {
  15638. if ((helper.getJoinFlags() & JFparallel) != 0)
  15639. {
  15640. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15641. puller->setInput(0, _in);
  15642. _in = puller;
  15643. }
  15644. CRoxieServerActivity::setInput(idx, _in);
  15645. }
  15646. }
  15647. const void * joinRecords(const void * left, const void * right)
  15648. {
  15649. // MORE - could share some code with lookup join
  15650. if (cloneLeft)
  15651. {
  15652. LinkRoxieRow(left);
  15653. return left;
  15654. }
  15655. try
  15656. {
  15657. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15658. unsigned outSize = helper.transform(rowBuilder, left, right);
  15659. if (outSize)
  15660. return rowBuilder.finalizeRowClear(outSize);
  15661. else
  15662. return NULL;
  15663. }
  15664. catch (IException *E)
  15665. {
  15666. throw makeWrappedException(E);
  15667. }
  15668. }
  15669. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  15670. {
  15671. try
  15672. {
  15673. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15674. unsigned numRows = rows.ordinality();
  15675. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15676. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  15677. if (outSize)
  15678. return rowBuilder.finalizeRowClear(outSize);
  15679. else
  15680. return NULL;
  15681. }
  15682. catch (IException *E)
  15683. {
  15684. throw makeWrappedException(E);
  15685. }
  15686. }
  15687. virtual const void *nextInGroup()
  15688. {
  15689. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15690. if(!started)
  15691. {
  15692. started = true;
  15693. left = input->nextInGroup();
  15694. matchedLeft = false;
  15695. countForLeft = keepLimit;
  15696. if(left == NULL)
  15697. {
  15698. eos = true;
  15699. return NULL;
  15700. }
  15701. loadRight();
  15702. }
  15703. const void * ret;
  15704. const void * right;
  15705. if(eos)
  15706. return NULL;
  15707. while(true)
  15708. {
  15709. ret = NULL;
  15710. if((rightIndex == rightOrdinality) || (countForLeft==0))
  15711. {
  15712. if(leftOuterJoin && left && !matchedLeft)
  15713. {
  15714. switch(activityKind)
  15715. {
  15716. case TAKalljoin:
  15717. ret = joinRecords(left, defaultRight);
  15718. break;
  15719. case TAKalldenormalize:
  15720. ret = left;
  15721. left = NULL;
  15722. break;
  15723. case TAKalldenormalizegroup:
  15724. filteredRight.kill();
  15725. ret = denormalizeRecords(left, filteredRight);
  15726. break;
  15727. default:
  15728. throwUnexpected();
  15729. }
  15730. }
  15731. rightIndex = 0;
  15732. ReleaseRoxieRow(left);
  15733. left = NULL;
  15734. if(ret)
  15735. {
  15736. matchedGroup = true;
  15737. processed++;
  15738. return ret;
  15739. }
  15740. }
  15741. if(!left)
  15742. {
  15743. left = input->nextInGroup();
  15744. matchedLeft = false;
  15745. countForLeft = keepLimit;
  15746. }
  15747. if(!left)
  15748. {
  15749. if(eog)
  15750. {
  15751. eos = true;
  15752. matchedGroup = false;
  15753. return NULL;
  15754. }
  15755. eog = true;
  15756. if (matchedGroup && leftIsGrouped)
  15757. {
  15758. matchedGroup = false;
  15759. return NULL;
  15760. }
  15761. matchedGroup = false;
  15762. continue;
  15763. }
  15764. eog = false;
  15765. switch(activityKind)
  15766. {
  15767. case TAKalljoin:
  15768. while(rightIndex < rightOrdinality)
  15769. {
  15770. right = rightset.item(rightIndex);
  15771. if(helper.match(left, right))
  15772. {
  15773. matchedLeft = true;
  15774. matchedRight.replace(true, rightIndex);
  15775. if(!exclude)
  15776. ret = joinRecords(left, right);
  15777. }
  15778. rightIndex++;
  15779. if(ret)
  15780. {
  15781. countForLeft--;
  15782. matchedGroup = true;
  15783. processed++;
  15784. return ret;
  15785. }
  15786. }
  15787. break;
  15788. case TAKalldenormalize:
  15789. {
  15790. OwnedConstRoxieRow newLeft;
  15791. newLeft.set(left);
  15792. unsigned rowSize = 0;
  15793. unsigned leftCount = 0;
  15794. while((rightIndex < rightOrdinality) && countForLeft)
  15795. {
  15796. right = rightset.item(rightIndex);
  15797. if(helper.match(left, right))
  15798. {
  15799. matchedLeft = true;
  15800. matchedRight.replace(true, rightIndex);
  15801. if(!exclude)
  15802. {
  15803. try
  15804. {
  15805. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15806. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15807. if(thisSize)
  15808. {
  15809. rowSize = thisSize;
  15810. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15811. --countForLeft;
  15812. }
  15813. }
  15814. catch (IException *e)
  15815. {
  15816. throw makeWrappedException(e);
  15817. }
  15818. }
  15819. }
  15820. rightIndex++;
  15821. }
  15822. if(rowSize)
  15823. {
  15824. processed++;
  15825. return newLeft.getClear();
  15826. }
  15827. }
  15828. break;
  15829. case TAKalldenormalizegroup:
  15830. filteredRight.kill();
  15831. while((rightIndex < rightOrdinality) && countForLeft)
  15832. {
  15833. right = rightset.item(rightIndex);
  15834. if(helper.match(left, right))
  15835. {
  15836. matchedLeft = true;
  15837. matchedRight.replace(true, rightIndex);
  15838. filteredRight.append(right);
  15839. --countForLeft;
  15840. }
  15841. ++rightIndex;
  15842. }
  15843. if(!exclude && filteredRight.ordinality())
  15844. {
  15845. ret = denormalizeRecords(left, filteredRight);
  15846. filteredRight.kill();
  15847. if(ret)
  15848. {
  15849. processed++;
  15850. return ret;
  15851. }
  15852. }
  15853. break;
  15854. default:
  15855. throwUnexpected();
  15856. }
  15857. }
  15858. }
  15859. };
  15860. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  15861. {
  15862. public:
  15863. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15864. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15865. {
  15866. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  15867. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  15868. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  15869. }
  15870. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15871. {
  15872. return new CRoxieServerAllJoinActivity(this, _probeManager);
  15873. }
  15874. };
  15875. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15876. {
  15877. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15878. }
  15879. //=====================================================================================================
  15880. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  15881. {
  15882. unsigned limit;
  15883. bool hasBest;
  15884. bool eoi;
  15885. const void **sorted;
  15886. unsigned sortedCount;
  15887. unsigned curIndex;
  15888. IHThorTopNArg &helper;
  15889. ICompare &compare;
  15890. public:
  15891. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15892. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  15893. {
  15894. sorted = NULL;
  15895. sortedCount = 0;
  15896. curIndex = 0;
  15897. limit = 0;
  15898. eoi = false;
  15899. hasBest = false;
  15900. }
  15901. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15902. {
  15903. assertex(sorted == NULL);
  15904. sortedCount = 0;
  15905. curIndex = 0;
  15906. eoi = false;
  15907. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15908. limit = (unsigned) helper.getLimit();
  15909. hasBest = helper.hasBest();
  15910. lateStart(parentExtractSize, parentExtract, limit > 0);
  15911. // MORE - should we use an expanding array instead?
  15912. if (limit > 0)
  15913. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  15914. }
  15915. virtual void reset()
  15916. {
  15917. if (sorted)
  15918. {
  15919. while(curIndex < sortedCount)
  15920. ReleaseRoxieRow(sorted[curIndex++]);
  15921. ReleaseRoxieRow(sorted);
  15922. }
  15923. sorted = NULL;
  15924. CRoxieServerLateStartActivity::reset();
  15925. }
  15926. bool abortEarly()
  15927. {
  15928. if (hasBest && (sortedCount == limit))
  15929. {
  15930. int compare = helper.compareBest(sorted[sortedCount-1]);
  15931. if (compare == 0)
  15932. {
  15933. if (meta.isGrouped())
  15934. {
  15935. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  15936. const void * next;
  15937. while ((next = input->nextInGroup()) != NULL)
  15938. ReleaseRoxieRow(next);
  15939. }
  15940. else
  15941. eoi = true;
  15942. return true;
  15943. }
  15944. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  15945. if (compare < 0)
  15946. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  15947. }
  15948. return false;
  15949. }
  15950. void getSorted()
  15951. {
  15952. curIndex = 0;
  15953. sortedCount = 0;
  15954. if(eoi)
  15955. return;
  15956. const void * next;
  15957. while ((next = input->nextInGroup()) != NULL)
  15958. {
  15959. if (sortedCount < limit)
  15960. {
  15961. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  15962. sortedCount++;
  15963. if(abortEarly())
  15964. return;
  15965. }
  15966. else
  15967. {
  15968. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  15969. {
  15970. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  15971. ReleaseRoxieRow(sorted[sortedCount]);
  15972. if(abortEarly())
  15973. return;
  15974. }
  15975. else
  15976. {
  15977. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  15978. }
  15979. }
  15980. }
  15981. }
  15982. virtual const void * nextInGroup()
  15983. {
  15984. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15985. if (eof)
  15986. return NULL;
  15987. if (curIndex >= sortedCount)
  15988. {
  15989. bool eog = sortedCount != 0;
  15990. getSorted();
  15991. if(sortedCount == 0)
  15992. {
  15993. eof = true;
  15994. return NULL;
  15995. }
  15996. if (eog)
  15997. return NULL;
  15998. }
  15999. processed++;
  16000. return sorted[curIndex++];
  16001. }
  16002. };
  16003. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16004. {
  16005. public:
  16006. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16007. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16008. {
  16009. }
  16010. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16011. {
  16012. return new CRoxieServerTopNActivity(this, _probeManager);
  16013. }
  16014. };
  16015. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16016. {
  16017. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16018. }
  16019. //=================================================================================
  16020. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16021. {
  16022. protected:
  16023. unsigned __int64 rowLimit;
  16024. IHThorLimitArg &helper;
  16025. public:
  16026. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16027. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16028. {
  16029. rowLimit = 0;
  16030. }
  16031. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16032. {
  16033. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16034. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16035. }
  16036. virtual const void *nextInGroup()
  16037. {
  16038. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16039. const void * ret = input->nextInGroup();
  16040. if (ret)
  16041. {
  16042. processed++;
  16043. if (processed > rowLimit)
  16044. {
  16045. ReleaseRoxieRow(ret);
  16046. if (traceLevel > 4)
  16047. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16048. helper.onLimitExceeded();
  16049. }
  16050. }
  16051. return ret;
  16052. }
  16053. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16054. {
  16055. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16056. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16057. if (ret)
  16058. {
  16059. if (wasCompleteMatch)
  16060. processed++;
  16061. if (processed > rowLimit)
  16062. {
  16063. ReleaseRoxieRow(ret);
  16064. if (traceLevel > 4)
  16065. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16066. helper.onLimitExceeded();
  16067. }
  16068. }
  16069. return ret;
  16070. }
  16071. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16072. {
  16073. return input->gatherConjunctions(collector);
  16074. }
  16075. virtual void resetEOF()
  16076. {
  16077. //Do not reset the rowLimit
  16078. input->resetEOF();
  16079. }
  16080. IInputSteppingMeta * querySteppingMeta()
  16081. {
  16082. return input->querySteppingMeta();
  16083. }
  16084. };
  16085. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16086. {
  16087. public:
  16088. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16089. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16090. {
  16091. }
  16092. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16093. {
  16094. return new CRoxieServerLimitActivity(this, _probeManager);
  16095. }
  16096. };
  16097. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16098. {
  16099. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16100. }
  16101. //=====================================================================================================
  16102. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16103. {
  16104. ConstPointerArray buff;
  16105. bool started;
  16106. unsigned index;
  16107. IHThorLimitTransformExtra * transformExtra;
  16108. public:
  16109. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16110. : CRoxieServerLimitActivity(_factory, _probeManager)
  16111. {
  16112. transformExtra = NULL;
  16113. started = false;
  16114. index = 0;
  16115. if (_onFail)
  16116. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16117. }
  16118. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16119. {
  16120. started = false;
  16121. index = 0;
  16122. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16123. }
  16124. virtual void reset()
  16125. {
  16126. while (buff.isItem(index))
  16127. ReleaseRoxieRow(buff.item(index++));
  16128. buff.kill();
  16129. started = false;
  16130. CRoxieServerLimitActivity::reset();
  16131. }
  16132. virtual const void *nextInGroup()
  16133. {
  16134. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16135. if (!started)
  16136. pullInput();
  16137. if (buff.isItem(index))
  16138. {
  16139. const void * next = buff.item(index++);
  16140. if(next)
  16141. processed++;
  16142. return next;
  16143. }
  16144. return NULL;
  16145. }
  16146. protected:
  16147. void pullInput()
  16148. {
  16149. unsigned count = 0;
  16150. loop
  16151. {
  16152. const void * next = input->nextInGroup();
  16153. if (next == NULL)
  16154. {
  16155. next = input->nextInGroup();
  16156. if(next == NULL)
  16157. break;
  16158. buff.append(NULL);
  16159. }
  16160. count++;
  16161. if (count > rowLimit)
  16162. {
  16163. ReleaseRoxieRow(next);
  16164. ReleaseRoxieRowSet(buff);
  16165. if (ctx->queryDebugContext())
  16166. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16167. if (transformExtra)
  16168. {
  16169. createRowAllocator();
  16170. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16171. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16172. if (outSize)
  16173. buff.append(rowBuilder.finalizeRowClear(outSize));
  16174. }
  16175. break;
  16176. }
  16177. buff.append(next);
  16178. }
  16179. started = true;
  16180. }
  16181. };
  16182. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16183. {
  16184. public:
  16185. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16187. {
  16188. }
  16189. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16190. {
  16191. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16192. }
  16193. };
  16194. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16195. {
  16196. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16197. }
  16198. //=================================================================================
  16199. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16200. {
  16201. IHThorCatchArg &helper;
  16202. public:
  16203. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16204. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16205. {
  16206. }
  16207. virtual const void *nextInGroup()
  16208. {
  16209. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16210. try
  16211. {
  16212. const void *ret = input->nextInGroup();
  16213. if (ret)
  16214. processed++;
  16215. return ret;
  16216. }
  16217. catch (IException *E)
  16218. {
  16219. E->Release();
  16220. helper.onExceptionCaught();
  16221. }
  16222. catch (...)
  16223. {
  16224. helper.onExceptionCaught();
  16225. }
  16226. throwUnexpected(); // onExceptionCaught should have thrown something
  16227. }
  16228. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16229. {
  16230. try
  16231. {
  16232. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16233. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16234. if (ret && wasCompleteMatch)
  16235. processed++;
  16236. return ret;
  16237. }
  16238. catch (IException *E)
  16239. {
  16240. E->Release();
  16241. helper.onExceptionCaught();
  16242. }
  16243. catch (...)
  16244. {
  16245. helper.onExceptionCaught();
  16246. }
  16247. throwUnexpected(); // onExceptionCaught should have thrown something
  16248. }
  16249. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16250. {
  16251. return input->gatherConjunctions(collector);
  16252. }
  16253. virtual void resetEOF()
  16254. {
  16255. input->resetEOF(); // MORE - why not in base class?
  16256. }
  16257. IInputSteppingMeta * querySteppingMeta()
  16258. {
  16259. return input->querySteppingMeta();
  16260. }
  16261. };
  16262. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  16263. {
  16264. ConstPointerArray buff;
  16265. bool started;
  16266. unsigned index;
  16267. IHThorCatchArg &helper;
  16268. bool createRow;
  16269. public:
  16270. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  16271. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  16272. {
  16273. started = false;
  16274. index = 0;
  16275. }
  16276. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16277. {
  16278. started = false;
  16279. index = 0;
  16280. try
  16281. {
  16282. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16283. }
  16284. catch (IException *E)
  16285. {
  16286. onException(E);
  16287. started = true;
  16288. }
  16289. catch (...)
  16290. {
  16291. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16292. started = true;
  16293. }
  16294. }
  16295. virtual void reset()
  16296. {
  16297. while (buff.isItem(index))
  16298. ReleaseRoxieRow(buff.item(index++));
  16299. buff.kill();
  16300. started = false;
  16301. CRoxieServerActivity::reset();
  16302. }
  16303. virtual const void *nextInGroup()
  16304. {
  16305. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16306. if (!started)
  16307. pullInput();
  16308. if (buff.isItem(index))
  16309. {
  16310. const void * next = buff.item(index++);
  16311. if(next)
  16312. processed++;
  16313. return next;
  16314. }
  16315. return NULL;
  16316. }
  16317. protected:
  16318. void onException(IException *E)
  16319. {
  16320. input->stop(true);
  16321. ReleaseRoxieRowSet(buff);
  16322. if (createRow)
  16323. {
  16324. createRowAllocator();
  16325. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16326. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  16327. if (outSize)
  16328. buff.append(rowBuilder.finalizeRowClear(outSize));
  16329. }
  16330. E->Release();
  16331. }
  16332. void pullInput()
  16333. {
  16334. try
  16335. {
  16336. bool EOGseen = false;
  16337. loop
  16338. {
  16339. const void * next = input->nextInGroup();
  16340. buff.append(next);
  16341. if (next == NULL)
  16342. {
  16343. if (EOGseen)
  16344. break;
  16345. EOGseen = true;
  16346. }
  16347. else
  16348. EOGseen = false;
  16349. }
  16350. }
  16351. catch (IException *E)
  16352. {
  16353. onException(E);
  16354. }
  16355. catch (...)
  16356. {
  16357. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16358. }
  16359. started = true;
  16360. }
  16361. };
  16362. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  16363. {
  16364. public:
  16365. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16366. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16367. {
  16368. }
  16369. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16370. {
  16371. switch (kind)
  16372. {
  16373. case TAKcatch:
  16374. return new CRoxieServerCatchActivity(this, _probeManager);
  16375. case TAKskipcatch:
  16376. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  16377. case TAKcreaterowcatch:
  16378. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  16379. default:
  16380. throwUnexpected();
  16381. }
  16382. }
  16383. };
  16384. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16385. {
  16386. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16387. }
  16388. //=================================================================================
  16389. class CRoxieServerCaseActivity : public CRoxieServerActivity
  16390. {
  16391. IHThorCaseArg &helper;
  16392. IRoxieInput **inputs;
  16393. unsigned cond;
  16394. bool unusedStopped;
  16395. IRoxieInput *in;
  16396. unsigned numInputs;
  16397. public:
  16398. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  16399. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  16400. {
  16401. unusedStopped = false;
  16402. cond = 0;
  16403. inputs = new IRoxieInput*[numInputs];
  16404. for (unsigned i = 0; i < numInputs; i++)
  16405. inputs[i] = NULL;
  16406. in = NULL;
  16407. }
  16408. ~CRoxieServerCaseActivity()
  16409. {
  16410. delete [] inputs;
  16411. }
  16412. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16413. {
  16414. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16415. cond = helper.getBranch();
  16416. //CHOOSE defaults to the last argument if out of range.
  16417. if (cond >= numInputs)
  16418. cond = numInputs - 1;
  16419. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  16420. for (unsigned idx = 0; idx < numInputs; idx++)
  16421. {
  16422. if (idx!=cond)
  16423. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16424. }
  16425. in = inputs[cond];
  16426. unusedStopped = true;
  16427. }
  16428. virtual void stop(bool aborting)
  16429. {
  16430. for (unsigned idx = 0; idx < numInputs; idx++)
  16431. {
  16432. if (idx==cond || !unusedStopped)
  16433. inputs[idx]->stop(aborting);
  16434. }
  16435. CRoxieServerActivity::stop(aborting);
  16436. }
  16437. virtual void reset()
  16438. {
  16439. for (unsigned idx = 0; idx < numInputs; idx++)
  16440. {
  16441. inputs[idx]->reset();
  16442. }
  16443. unusedStopped = false;
  16444. in = NULL;
  16445. CRoxieServerActivity::reset();
  16446. }
  16447. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16448. {
  16449. assertex(idx < numInputs);
  16450. inputs[idx] = _in;
  16451. }
  16452. virtual const void *nextInGroup()
  16453. {
  16454. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16455. if (in)
  16456. {
  16457. const void *ret = in->nextInGroup();
  16458. if (ret)
  16459. processed++;
  16460. return ret;
  16461. }
  16462. return NULL;
  16463. }
  16464. };
  16465. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  16466. {
  16467. bool graphInvariant;
  16468. public:
  16469. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16470. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16471. {
  16472. graphInvariant = _graphInvariant;
  16473. }
  16474. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16475. {
  16476. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  16477. }
  16478. virtual bool isGraphInvariant() const
  16479. {
  16480. return graphInvariant;
  16481. }
  16482. };
  16483. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16484. {
  16485. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16486. }
  16487. //=================================================================================
  16488. class CRoxieServerIfActivity : public CRoxieServerActivity
  16489. {
  16490. IHThorIfArg &helper;
  16491. IRoxieInput *inputTrue;
  16492. IRoxieInput *inputFalse;
  16493. bool cond;
  16494. bool unusedStopped;
  16495. public:
  16496. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16497. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16498. {
  16499. inputFalse = NULL;
  16500. inputTrue = NULL;
  16501. unusedStopped = false;
  16502. cond = false;
  16503. }
  16504. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16505. {
  16506. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16507. cond = helper.getCondition();
  16508. if (cond)
  16509. {
  16510. inputTrue->start(parentExtractSize, parentExtract, paused);
  16511. if (inputFalse)
  16512. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16513. }
  16514. else
  16515. {
  16516. if (inputFalse)
  16517. inputFalse->start(parentExtractSize, parentExtract, paused);
  16518. inputTrue->stop(false);
  16519. }
  16520. unusedStopped = true;
  16521. }
  16522. virtual void stop(bool aborting)
  16523. {
  16524. if (!unusedStopped || cond)
  16525. inputTrue->stop(aborting);
  16526. if (inputFalse && (!unusedStopped || !cond))
  16527. inputFalse->stop(aborting);
  16528. CRoxieServerActivity::stop(aborting);
  16529. }
  16530. virtual unsigned __int64 queryLocalCycles() const
  16531. {
  16532. __int64 localCycles = totalCycles;
  16533. localCycles -= inputTrue->queryTotalCycles();
  16534. if (inputFalse)
  16535. localCycles -= inputFalse->queryTotalCycles();
  16536. if (localCycles < 0)
  16537. localCycles = 0;
  16538. return localCycles;
  16539. }
  16540. virtual IRoxieInput *queryInput(unsigned idx) const
  16541. {
  16542. switch (idx)
  16543. {
  16544. case 0:
  16545. return inputTrue;
  16546. case 1:
  16547. return inputFalse;
  16548. default:
  16549. return NULL;
  16550. }
  16551. }
  16552. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  16553. {
  16554. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16555. if (in)
  16556. return in->queryIndexReadActivity();
  16557. return NULL;
  16558. }
  16559. virtual void reset()
  16560. {
  16561. CRoxieServerActivity::reset();
  16562. inputTrue->reset();
  16563. if (inputFalse)
  16564. inputFalse->reset();
  16565. unusedStopped = false;
  16566. }
  16567. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16568. {
  16569. if (idx==1)
  16570. inputFalse = _in;
  16571. else
  16572. {
  16573. assertex(!idx);
  16574. inputTrue = _in;
  16575. }
  16576. }
  16577. virtual const void *nextInGroup()
  16578. {
  16579. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16580. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16581. if (in)
  16582. {
  16583. const void * ret;
  16584. if ((ret = in->nextInGroup()) != NULL)
  16585. processed++;
  16586. return ret;
  16587. }
  16588. return NULL;
  16589. }
  16590. };
  16591. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  16592. {
  16593. unsigned input2;
  16594. unsigned input2idx;
  16595. bool graphInvariant;
  16596. public:
  16597. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16598. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16599. {
  16600. graphInvariant = _graphInvariant;
  16601. input2 = (unsigned)-1;
  16602. input2idx = (unsigned)-1;
  16603. }
  16604. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16605. {
  16606. return new CRoxieServerIfActivity(this, _probeManager);
  16607. }
  16608. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  16609. {
  16610. if (idx==1)
  16611. {
  16612. input2 = source;
  16613. input2idx = sourceidx;
  16614. }
  16615. else
  16616. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  16617. }
  16618. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  16619. {
  16620. switch (idx)
  16621. {
  16622. case 1:
  16623. sourceidx = input2idx;
  16624. return input2;
  16625. case 0:
  16626. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  16627. default:
  16628. return (unsigned) -1;
  16629. }
  16630. }
  16631. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  16632. virtual bool isGraphInvariant() const
  16633. {
  16634. return graphInvariant;
  16635. }
  16636. };
  16637. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16638. {
  16639. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16640. }
  16641. //=================================================================================
  16642. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  16643. {
  16644. CriticalSection ecrit;
  16645. Owned<IException> exception;
  16646. bool executed;
  16647. public:
  16648. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16649. : CRoxieServerActivity(_factory, _probeManager)
  16650. {
  16651. executed = false;
  16652. }
  16653. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  16654. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  16655. {
  16656. CriticalBlock b(ecrit);
  16657. if (exception)
  16658. throw(exception.getLink());
  16659. if (!executed)
  16660. {
  16661. try
  16662. {
  16663. executed = true;
  16664. start(parentExtractSize, parentExtract, false);
  16665. doExecuteAction(parentExtractSize, parentExtract);
  16666. stop(false);
  16667. }
  16668. catch (IException * E)
  16669. {
  16670. ctx->notifyAbort(E);
  16671. stop(true);
  16672. exception.set(E);
  16673. throw;
  16674. }
  16675. }
  16676. }
  16677. virtual void reset()
  16678. {
  16679. executed = false;
  16680. exception.clear();
  16681. CRoxieServerActivity::reset();
  16682. }
  16683. virtual unsigned __int64 queryLocalCycles() const
  16684. {
  16685. return totalCycles;
  16686. }
  16687. virtual const void *nextInGroup()
  16688. {
  16689. throwUnexpected(); // I am nobody's input
  16690. }
  16691. virtual IRoxieInput *queryInput(unsigned idx) const
  16692. {
  16693. throwUnexpected(); // I am nobody's input
  16694. }
  16695. };
  16696. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  16697. {
  16698. IHThorIfArg &helper;
  16699. public:
  16700. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16701. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16702. {
  16703. }
  16704. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16705. {
  16706. int controlId;
  16707. {
  16708. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16709. controlId = helper.getCondition() ? 1 : 2;
  16710. }
  16711. executeDependencies(parentExtractSize, parentExtract, controlId);
  16712. }
  16713. };
  16714. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  16715. {
  16716. bool isRoot;
  16717. public:
  16718. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16719. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16720. {
  16721. }
  16722. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16723. {
  16724. return new CRoxieServerIfActionActivity(this, _probeManager);
  16725. }
  16726. virtual bool isSink() const
  16727. {
  16728. return isRoot;
  16729. }
  16730. };
  16731. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16732. {
  16733. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16734. }
  16735. //=================================================================================
  16736. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  16737. {
  16738. public:
  16739. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16740. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  16741. {
  16742. }
  16743. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16744. {
  16745. #ifdef PARALLEL_EXECUTE
  16746. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  16747. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  16748. #else
  16749. ForEachItemIn(idx, dependencies)
  16750. {
  16751. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  16752. }
  16753. #endif
  16754. }
  16755. };
  16756. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  16757. {
  16758. bool isRoot;
  16759. public:
  16760. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16761. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16762. {
  16763. assertex(!isRoot); // non-internal should be expanded out..
  16764. }
  16765. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16766. {
  16767. return new CRoxieServerParallelActionActivity(this, _probeManager);
  16768. }
  16769. virtual bool isSink() const
  16770. {
  16771. return isRoot;
  16772. }
  16773. };
  16774. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16775. {
  16776. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16777. }
  16778. //=================================================================================
  16779. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  16780. {
  16781. IHThorSequentialArg &helper;
  16782. public:
  16783. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16784. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  16785. {
  16786. }
  16787. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16788. {
  16789. unsigned numBranches = helper.numBranches();
  16790. for (unsigned branch=1; branch <= numBranches; branch++)
  16791. executeDependencies(parentExtractSize, parentExtract, branch);
  16792. }
  16793. };
  16794. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  16795. {
  16796. bool isRoot;
  16797. public:
  16798. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16799. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16800. {
  16801. }
  16802. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16803. {
  16804. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  16805. }
  16806. virtual bool isSink() const
  16807. {
  16808. return isRoot;
  16809. }
  16810. };
  16811. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16812. {
  16813. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16814. }
  16815. //=================================================================================
  16816. class CRoxieServerWhenActivity : public CRoxieServerActivity
  16817. {
  16818. public:
  16819. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16820. : CRoxieServerActivity(_factory, _probeManager)
  16821. {
  16822. savedExtractSize = 0;
  16823. savedExtract = NULL;
  16824. }
  16825. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16826. {
  16827. savedExtractSize = parentExtractSize;
  16828. savedExtract = parentExtract;
  16829. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16830. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  16831. }
  16832. virtual void stop(bool aborting)
  16833. {
  16834. if (state != STATEstopped)
  16835. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  16836. CRoxieServerActivity::stop(aborting);
  16837. }
  16838. virtual const void *nextInGroup()
  16839. {
  16840. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // bit of a waste of time....
  16841. return input->nextInGroup();
  16842. }
  16843. protected:
  16844. unsigned savedExtractSize;
  16845. const byte *savedExtract;
  16846. };
  16847. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  16848. {
  16849. public:
  16850. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16851. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16852. {
  16853. }
  16854. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16855. {
  16856. return new CRoxieServerWhenActivity(this, _probeManager);
  16857. }
  16858. };
  16859. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16860. {
  16861. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16862. }
  16863. //=================================================================================
  16864. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  16865. {
  16866. public:
  16867. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16868. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  16869. {
  16870. savedExtractSize = 0;
  16871. savedExtract = NULL;
  16872. }
  16873. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16874. {
  16875. savedExtractSize = parentExtractSize;
  16876. savedExtract = parentExtract;
  16877. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  16878. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  16879. }
  16880. virtual void stop(bool aborting)
  16881. {
  16882. if (state != STATEstopped)
  16883. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  16884. CRoxieServerActionBaseActivity::stop(aborting);
  16885. }
  16886. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16887. {
  16888. executeDependencies(parentExtractSize, parentExtract, 1);
  16889. }
  16890. protected:
  16891. unsigned savedExtractSize;
  16892. const byte *savedExtract;
  16893. };
  16894. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  16895. {
  16896. public:
  16897. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16898. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16899. {
  16900. }
  16901. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16902. {
  16903. return new CRoxieServerWhenActionActivity(this, _probeManager);
  16904. }
  16905. virtual bool isSink() const
  16906. {
  16907. return isRoot;
  16908. }
  16909. private:
  16910. bool isRoot;
  16911. };
  16912. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16913. {
  16914. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16915. }
  16916. //=================================================================================
  16917. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  16918. {
  16919. IHThorParseArg &helper;
  16920. INlpParser * parser;
  16921. INlpResultIterator * rowIter;
  16922. const void * in;
  16923. char * curSearchText;
  16924. INlpParseAlgorithm * algorithm;
  16925. size32_t curSearchTextLen;
  16926. bool anyThisGroup;
  16927. bool processRecord(const void * inRec)
  16928. {
  16929. if (helper.searchTextNeedsFree())
  16930. rtlFree(curSearchText);
  16931. curSearchTextLen = 0;
  16932. curSearchText = NULL;
  16933. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  16934. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  16935. }
  16936. public:
  16937. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  16938. : CRoxieServerActivity(_factory, _probeManager),
  16939. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  16940. {
  16941. parser = NULL;
  16942. rowIter = NULL;
  16943. in = NULL;
  16944. curSearchText = NULL;
  16945. anyThisGroup = false;
  16946. curSearchTextLen = 0;
  16947. }
  16948. ~CRoxieServerParseActivity()
  16949. {
  16950. ::Release(parser);
  16951. }
  16952. virtual bool needsAllocator() const { return true; }
  16953. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  16954. {
  16955. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  16956. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  16957. rowIter = parser->queryResultIter();
  16958. }
  16959. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16960. {
  16961. anyThisGroup = false;
  16962. curSearchTextLen = 0;
  16963. curSearchText = NULL;
  16964. in = NULL;
  16965. parser->reset();
  16966. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16967. }
  16968. virtual void reset()
  16969. {
  16970. if (helper.searchTextNeedsFree())
  16971. rtlFree(curSearchText);
  16972. curSearchText = NULL;
  16973. ReleaseClearRoxieRow(in);
  16974. CRoxieServerActivity::reset();
  16975. }
  16976. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  16977. {
  16978. try
  16979. {
  16980. return helper.transform(self, curRecord, results, walker);
  16981. }
  16982. catch (IException *E)
  16983. {
  16984. throw makeWrappedException(E);
  16985. }
  16986. }
  16987. virtual const void * nextInGroup()
  16988. {
  16989. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16990. loop
  16991. {
  16992. if (rowIter->isValid())
  16993. {
  16994. anyThisGroup = true;
  16995. OwnedConstRoxieRow out = rowIter->getRow();
  16996. rowIter->next();
  16997. processed++;
  16998. return out.getClear();
  16999. }
  17000. ReleaseClearRoxieRow(in);
  17001. in = input->nextInGroup();
  17002. if (!in)
  17003. {
  17004. if (anyThisGroup)
  17005. {
  17006. anyThisGroup = false;
  17007. return NULL;
  17008. }
  17009. in = input->nextInGroup();
  17010. if (!in)
  17011. return NULL;
  17012. }
  17013. processRecord(in);
  17014. rowIter->first();
  17015. }
  17016. }
  17017. };
  17018. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17019. {
  17020. Owned<INlpParseAlgorithm> algorithm;
  17021. Owned<IHThorParseArg> helper;
  17022. public:
  17023. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17024. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17025. {
  17026. helper.setown((IHThorParseArg *) helperFactory());
  17027. algorithm.setown(createThorParser(rc, *helper));
  17028. }
  17029. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17030. {
  17031. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17032. }
  17033. };
  17034. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17035. {
  17036. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17037. }
  17038. //=====================================================================================================
  17039. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17040. {
  17041. IHThorWorkUnitWriteArg &helper;
  17042. bool isReread;
  17043. bool grouped;
  17044. IRoxieServerContext *serverContext;
  17045. public:
  17046. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread)
  17047. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17048. {
  17049. grouped = (helper.getFlags() & POFgrouped) != 0;
  17050. serverContext = NULL;
  17051. }
  17052. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17053. {
  17054. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17055. serverContext = ctx->queryServerContext();
  17056. if (!serverContext)
  17057. {
  17058. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17059. }
  17060. }
  17061. virtual bool needsAllocator() const { return true; }
  17062. virtual void onExecute()
  17063. {
  17064. int sequence = helper.getSequence();
  17065. const char *storedName = helper.queryName();
  17066. if (!storedName)
  17067. storedName = "Dataset";
  17068. MemoryBuffer result;
  17069. FlushingStringBuffer *response = NULL;
  17070. bool saveInContext = (int) sequence < 0 || isReread;
  17071. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17072. meta.set(input->queryOutputMeta());
  17073. Owned<IOutputRowSerializer> rowSerializer;
  17074. Owned<IXmlWriter> writer;
  17075. if ((int) sequence >= 0)
  17076. {
  17077. response = serverContext->queryResult(sequence);
  17078. if (response)
  17079. {
  17080. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0);
  17081. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17082. {
  17083. writer.setown(createIXmlWriter(serverContext->getXmlFlags(), 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17084. writer->outputBeginArray("Row");
  17085. }
  17086. }
  17087. }
  17088. if (serverContext->outputResultsToWorkUnit()||(response && response->isRaw))
  17089. {
  17090. createRowAllocator();
  17091. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17092. }
  17093. __int64 initialProcessed = processed;
  17094. RtlLinkedDatasetBuilder builder(rowAllocator);
  17095. loop
  17096. {
  17097. const void *row = input->nextInGroup();
  17098. if (saveInContext)
  17099. {
  17100. if (row || grouped)
  17101. builder.append(row);
  17102. }
  17103. if (grouped && (processed != initialProcessed))
  17104. {
  17105. if (serverContext->outputResultsToWorkUnit())
  17106. result.append(row == NULL);
  17107. if (response)
  17108. {
  17109. if (response->isRaw)
  17110. response->append(row == NULL);
  17111. else
  17112. {
  17113. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17114. }
  17115. }
  17116. }
  17117. if (!row)
  17118. {
  17119. row = input->nextInGroup();
  17120. if (!row)
  17121. break;
  17122. if (saveInContext)
  17123. builder.append(row);
  17124. }
  17125. processed++;
  17126. if (serverContext->outputResultsToWorkUnit())
  17127. {
  17128. CThorDemoRowSerializer serializerTarget(result);
  17129. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17130. }
  17131. if (response)
  17132. {
  17133. if (response->isRaw)
  17134. {
  17135. // MORE - should be able to serialize straight to the response...
  17136. MemoryBuffer rowbuff;
  17137. CThorDemoRowSerializer serializerTarget(rowbuff);
  17138. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17139. response->append(rowbuff.length(), rowbuff.toByteArray());
  17140. }
  17141. else if (writer)
  17142. {
  17143. writer->outputBeginNested("Row", false);
  17144. helper.serializeXml((byte *) row, *writer);
  17145. writer->outputEndNested("Row");
  17146. }
  17147. else
  17148. {
  17149. SimpleOutputWriter x;
  17150. helper.serializeXml((byte *) row, x);
  17151. x.newline();
  17152. response->append(x.str());
  17153. }
  17154. response->incrementRowCount();
  17155. response->flush(false);
  17156. }
  17157. ReleaseRoxieRow(row);
  17158. }
  17159. if (writer)
  17160. writer->outputEndArray("Row");
  17161. if (saveInContext)
  17162. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17163. if (serverContext->outputResultsToWorkUnit())
  17164. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17165. }
  17166. };
  17167. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17168. {
  17169. bool isReread;
  17170. public:
  17171. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17172. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17173. {
  17174. isReread = usageCount > 0;
  17175. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17176. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17177. }
  17178. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17179. {
  17180. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread);
  17181. }
  17182. };
  17183. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17184. {
  17185. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17186. }
  17187. //=====================================================================================================
  17188. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17189. {
  17190. IHThorDictionaryWorkUnitWriteArg &helper;
  17191. IRoxieServerContext *serverContext;
  17192. public:
  17193. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17194. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17195. {
  17196. serverContext = NULL;
  17197. }
  17198. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17199. {
  17200. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17201. serverContext = ctx->queryServerContext();
  17202. if (!serverContext)
  17203. {
  17204. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17205. }
  17206. }
  17207. virtual bool needsAllocator() const { return true; }
  17208. virtual void onExecute()
  17209. {
  17210. int sequence = helper.getSequence();
  17211. const char *storedName = helper.queryName();
  17212. assertex(storedName && *storedName);
  17213. assertex(sequence < 0);
  17214. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  17215. loop
  17216. {
  17217. const void *row = input->nextInGroup();
  17218. if (!row)
  17219. {
  17220. row = input->nextInGroup();
  17221. if (!row)
  17222. break;
  17223. }
  17224. builder.appendOwn(row);
  17225. processed++;
  17226. }
  17227. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17228. }
  17229. };
  17230. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  17231. {
  17232. public:
  17233. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17234. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17235. {
  17236. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  17237. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17238. }
  17239. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17240. {
  17241. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager);
  17242. }
  17243. };
  17244. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17245. {
  17246. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17247. }
  17248. //=================================================================================
  17249. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  17250. {
  17251. IHThorRemoteResultArg &helper;
  17252. public:
  17253. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17254. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorRemoteResultArg &)basehelper)
  17255. {
  17256. }
  17257. virtual void onExecute()
  17258. {
  17259. OwnedConstRoxieRow row = input->nextInGroup();
  17260. helper.sendResult(row); // should be only one row or something has gone wrong!
  17261. }
  17262. };
  17263. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  17264. {
  17265. public:
  17266. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17267. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17268. {
  17269. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  17270. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17271. }
  17272. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17273. {
  17274. return new CRoxieServerRemoteResultActivity(this, _probeManager);
  17275. }
  17276. };
  17277. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17278. {
  17279. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17280. }
  17281. //=================================================================================
  17282. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  17283. {
  17284. IHThorXmlParseArg &helper;
  17285. Owned<IXMLParse> xmlParser;
  17286. const void * in;
  17287. char * srchStr;
  17288. unsigned numProcessedLastGroup;
  17289. bool srchStrNeedsFree;
  17290. Owned<IColumnProvider> lastMatch;
  17291. public:
  17292. IMPLEMENT_IINTERFACE;
  17293. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17294. : CRoxieServerActivity(_factory, _probeManager),
  17295. helper((IHThorXmlParseArg &)basehelper)
  17296. {
  17297. srchStrNeedsFree = helper.searchTextNeedsFree();
  17298. numProcessedLastGroup = 0;
  17299. srchStr = NULL;
  17300. in = NULL;
  17301. }
  17302. ~CRoxieServerXmlParseActivity()
  17303. {
  17304. }
  17305. virtual bool needsAllocator() const { return true; }
  17306. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17307. {
  17308. numProcessedLastGroup = 0;
  17309. srchStr = NULL;
  17310. in = NULL;
  17311. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17312. }
  17313. virtual void reset()
  17314. {
  17315. if (helper.searchTextNeedsFree())
  17316. rtlFree(srchStr);
  17317. srchStr = NULL;
  17318. ReleaseClearRoxieRow(in);
  17319. xmlParser.clear();
  17320. CRoxieServerActivity::reset();
  17321. }
  17322. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17323. {
  17324. lastMatch.set(&entry);
  17325. }
  17326. virtual const void *nextInGroup()
  17327. {
  17328. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17329. loop
  17330. {
  17331. if(xmlParser)
  17332. {
  17333. loop
  17334. {
  17335. if(!xmlParser->next())
  17336. {
  17337. if (srchStrNeedsFree)
  17338. {
  17339. rtlFree(srchStr);
  17340. srchStr = NULL;
  17341. }
  17342. xmlParser.clear();
  17343. break;
  17344. }
  17345. if(lastMatch)
  17346. {
  17347. try
  17348. {
  17349. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17350. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  17351. lastMatch.clear();
  17352. if (outSize)
  17353. {
  17354. processed++;
  17355. return rowBuilder.finalizeRowClear(outSize);
  17356. }
  17357. }
  17358. catch (IException *E)
  17359. {
  17360. throw makeWrappedException(E);
  17361. }
  17362. }
  17363. }
  17364. }
  17365. ReleaseClearRoxieRow(in);
  17366. in = input->nextInGroup();
  17367. if(!in)
  17368. {
  17369. if(numProcessedLastGroup == processed)
  17370. in = input->nextInGroup();
  17371. if(!in)
  17372. {
  17373. numProcessedLastGroup = processed;
  17374. return NULL;
  17375. }
  17376. }
  17377. size32_t srchLen;
  17378. helper.getSearchText(srchLen, srchStr, in);
  17379. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  17380. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  17381. }
  17382. }
  17383. };
  17384. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  17385. {
  17386. public:
  17387. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17388. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17389. {
  17390. }
  17391. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17392. {
  17393. return new CRoxieServerXmlParseActivity(this, _probeManager);
  17394. }
  17395. };
  17396. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17397. {
  17398. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17399. }
  17400. //=====================================================================================================
  17401. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  17402. {
  17403. protected:
  17404. IHThorDiskReadBaseArg &helper;
  17405. IHThorCompoundExtra * compoundHelper;
  17406. RemoteActivityId remoteId; // Note we copy it rather than reference
  17407. Owned<CSkippableRemoteResultAdaptor> remote;
  17408. unsigned numParts;
  17409. unsigned __int64 rowLimit;
  17410. unsigned __int64 stopAfter;
  17411. Linked<IInMemoryIndexManager> manager;
  17412. Owned<IInMemoryIndexCursor> cursor;
  17413. Owned<IDirectReader> reader;
  17414. CThorContiguousRowBuffer deserializeSource;
  17415. Owned<ISourceRowPrefetcher> prefetcher;
  17416. bool eof;
  17417. bool isKeyed;
  17418. bool variableFileName;
  17419. bool isOpt;
  17420. bool sorted;
  17421. bool maySkip;
  17422. bool isLocal;
  17423. CachedOutputMetaData diskSize;
  17424. Owned<const IResolvedFile> varFileInfo;
  17425. Owned<IFileIOArray> varFiles;
  17426. inline bool useRemote()
  17427. {
  17428. return remote != NULL && numParts > 1;
  17429. }
  17430. public:
  17431. IMPLEMENT_IINTERFACE;
  17432. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17433. : CRoxieServerActivity(_factory, _probeManager),
  17434. helper((IHThorDiskReadBaseArg &)basehelper),
  17435. numParts(_numParts),
  17436. remoteId(_remoteId),
  17437. manager(_manager),
  17438. isLocal(_isLocal),
  17439. sorted(_sorted),
  17440. maySkip(_maySkip),
  17441. deserializeSource(NULL)
  17442. {
  17443. if (numParts != 1 && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  17444. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  17445. compoundHelper = NULL;
  17446. eof = false;
  17447. rowLimit = (unsigned __int64) -1;
  17448. isKeyed = false;
  17449. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  17450. diskSize.set(helper.queryDiskRecordSize());
  17451. variableFileName = allFilesDynamic || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  17452. isOpt = (helper.getFlags() & TDRoptional) != 0;
  17453. }
  17454. virtual const IResolvedFile *queryVarFileInfo() const
  17455. {
  17456. return varFileInfo;
  17457. }
  17458. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17459. {
  17460. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17461. if (remote)
  17462. remote->onCreate(this, this, _ctx, _colocalParent);
  17463. }
  17464. virtual bool needsAllocator() const { return true; }
  17465. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17466. {
  17467. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17468. if (compoundHelper)
  17469. {
  17470. rowLimit = compoundHelper->getRowLimit();
  17471. stopAfter = compoundHelper->getChooseNLimit();
  17472. }
  17473. if (!helper.canMatchAny())
  17474. eof = true;
  17475. else
  17476. {
  17477. if (variableFileName)
  17478. {
  17479. OwnedRoxieString fileName(helper.getFileName());
  17480. varFileInfo.setown(resolveLFN(fileName, isOpt));
  17481. numParts = 0;
  17482. if (varFileInfo)
  17483. {
  17484. Owned<IFilePartMap> map = varFileInfo->getFileMap();
  17485. if (map)
  17486. numParts = map->getNumParts();
  17487. }
  17488. }
  17489. if (!numParts)
  17490. {
  17491. eof = true;
  17492. }
  17493. else if (useRemote())
  17494. {
  17495. remote->onStart(parentExtractSize, parentExtract);
  17496. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  17497. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  17498. // Translation into a message per channel done elsewhere....
  17499. remote->getMem(0, fileNo, 0);
  17500. remote->flush();
  17501. remote->senddone();
  17502. }
  17503. else
  17504. {
  17505. if (variableFileName)
  17506. {
  17507. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  17508. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  17509. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  17510. }
  17511. assertex(manager != NULL);
  17512. helper.createSegmentMonitors(this);
  17513. if (cursor)
  17514. {
  17515. isKeyed = cursor->selectKey();
  17516. cursor->reset();
  17517. }
  17518. if (!isKeyed)
  17519. {
  17520. reader.setown(manager->createReader(0, 0, 1));
  17521. deserializeSource.setStream(reader);
  17522. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  17523. }
  17524. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  17525. }
  17526. }
  17527. }
  17528. virtual void append(IKeySegmentMonitor *segment)
  17529. {
  17530. if (!segment->isWild())
  17531. {
  17532. if (!cursor)
  17533. cursor.setown(manager->createCursor());
  17534. cursor->append(segment);
  17535. }
  17536. }
  17537. virtual unsigned ordinality() const
  17538. {
  17539. return cursor ? cursor->ordinality() : 0;
  17540. }
  17541. virtual IKeySegmentMonitor *item(unsigned idx) const
  17542. {
  17543. return cursor ? cursor->item(idx) : 0;
  17544. }
  17545. virtual void setMergeBarrier(unsigned barrierOffset)
  17546. {
  17547. // no merging so no issue...
  17548. }
  17549. virtual void stop(bool aborting)
  17550. {
  17551. if (useRemote())
  17552. remote->onStop(aborting);
  17553. CRoxieServerActivity::stop(aborting);
  17554. }
  17555. virtual void reset()
  17556. {
  17557. if (useRemote())
  17558. {
  17559. processed = remote->processed;
  17560. remote->processed = 0;
  17561. remote->onReset();
  17562. }
  17563. varFileInfo.clear();
  17564. eof = false;
  17565. if (cursor)
  17566. cursor->reset();
  17567. deserializeSource.clearStream();
  17568. CRoxieServerActivity::reset();
  17569. }
  17570. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17571. {
  17572. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  17573. }
  17574. virtual void onLimitExceeded(bool isKeyed)
  17575. {
  17576. if (traceLevel > 4)
  17577. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17578. assertex(compoundHelper);
  17579. if (isKeyed) // MORE does this exist for diskread? should it?
  17580. {
  17581. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  17582. {
  17583. if (ctx->queryDebugContext())
  17584. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17585. throw makeLimitSkipException(true);
  17586. }
  17587. else
  17588. {
  17589. UNIMPLEMENTED;
  17590. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  17591. }
  17592. }
  17593. else
  17594. {
  17595. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  17596. {
  17597. if (ctx->queryDebugContext())
  17598. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17599. throw makeLimitSkipException(false);
  17600. }
  17601. else
  17602. compoundHelper->onLimitExceeded();
  17603. }
  17604. }
  17605. virtual const void * createLimitFailRow(bool isKeyed)
  17606. {
  17607. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17608. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  17609. assertex(limitTransformExtra);
  17610. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  17611. if (outSize)
  17612. return rowBuilder.finalizeRowClear(outSize);
  17613. return NULL;
  17614. }
  17615. };
  17616. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  17617. {
  17618. IHThorCompoundReadExtra * readHelper;
  17619. ConstPointerArray readrows;
  17620. bool readAheadDone;
  17621. unsigned readIndex;
  17622. public:
  17623. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17624. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17625. {
  17626. compoundHelper = (IHThorDiskReadArg *)&helper;
  17627. readHelper = (IHThorDiskReadArg *)&helper;
  17628. readAheadDone = false;
  17629. readIndex = 0;
  17630. }
  17631. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17632. {
  17633. rowLimit = compoundHelper->getRowLimit();
  17634. stopAfter = compoundHelper->getChooseNLimit();
  17635. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17636. readAheadDone = false;
  17637. readIndex = 0;
  17638. }
  17639. virtual void reset()
  17640. {
  17641. while (readrows.isItem(readIndex))
  17642. ReleaseRoxieRow(readrows.item(readIndex++));
  17643. readrows.kill();
  17644. readAheadDone = false;
  17645. readIndex = 0;
  17646. CRoxieServerDiskReadBaseActivity::reset();
  17647. }
  17648. virtual const void *nextInGroup()
  17649. {
  17650. if (eof)
  17651. return NULL;
  17652. else if (useRemote())
  17653. return remote->nextInGroup();
  17654. else if (maySkip)
  17655. {
  17656. if (!readAheadDone)
  17657. {
  17658. unsigned preprocessed = 0;
  17659. while (!eof)
  17660. {
  17661. const void *row = _nextInGroup();
  17662. if (row)
  17663. preprocessed++;
  17664. if (preprocessed > rowLimit)
  17665. {
  17666. ReleaseRoxieRow(row);
  17667. while (readrows.isItem(readIndex))
  17668. ReleaseRoxieRow(readrows.item(readIndex++));
  17669. readrows.kill();
  17670. eof = true;
  17671. if (ctx->queryDebugContext())
  17672. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17673. if (helper.getFlags() & TDRlimitskips)
  17674. return NULL;
  17675. else if (helper.getFlags() & TDRlimitcreates)
  17676. return createLimitFailRow(false);
  17677. else
  17678. throwUnexpected();
  17679. }
  17680. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  17681. {
  17682. eof = true;
  17683. ReleaseRoxieRow(row);
  17684. break;
  17685. }
  17686. readrows.append(row);
  17687. }
  17688. readAheadDone = true;
  17689. }
  17690. if (readrows.isItem(readIndex))
  17691. {
  17692. const void *ret = readrows.item(readIndex++);
  17693. if (ret)
  17694. processed++;
  17695. return ret;
  17696. }
  17697. else
  17698. {
  17699. eof = true;
  17700. return NULL;
  17701. }
  17702. }
  17703. else
  17704. {
  17705. const void *ret = _nextInGroup();
  17706. if (ret)
  17707. {
  17708. processed++;
  17709. if (processed > rowLimit)
  17710. {
  17711. if (traceLevel > 4)
  17712. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17713. ReleaseRoxieRow(ret);
  17714. compoundHelper->onLimitExceeded();
  17715. throwUnexpected(); // onLimitExceeded is not supposed to return
  17716. }
  17717. if (processed > stopAfter) // MORE - bit of a strange place to check
  17718. {
  17719. eof = true;
  17720. ReleaseRoxieRow(ret);
  17721. return NULL;
  17722. }
  17723. }
  17724. return ret;
  17725. }
  17726. }
  17727. const void *_nextInGroup()
  17728. {
  17729. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17730. unsigned transformedSize = 0;
  17731. if (isKeyed)
  17732. {
  17733. loop
  17734. {
  17735. const void *nextCandidate = cursor->nextMatch();
  17736. if (!nextCandidate)
  17737. {
  17738. eof = true;
  17739. return NULL;
  17740. }
  17741. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  17742. if (transformedSize)
  17743. break;
  17744. }
  17745. }
  17746. else // use reader...
  17747. {
  17748. assertex(reader != NULL);
  17749. loop
  17750. {
  17751. if (deserializeSource.eos())
  17752. {
  17753. eof = true;
  17754. return NULL;
  17755. }
  17756. prefetcher->readAhead(deserializeSource);
  17757. const byte *nextRec = deserializeSource.queryRow();
  17758. if (cursor && cursor->isFiltered(nextRec))
  17759. transformedSize = 0;
  17760. else
  17761. transformedSize = readHelper->transform(rowBuilder, nextRec);
  17762. deserializeSource.finishedRow();
  17763. if (transformedSize)
  17764. break;
  17765. }
  17766. }
  17767. return rowBuilder.finalizeRowClear(transformedSize);
  17768. }
  17769. };
  17770. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  17771. {
  17772. IHThorXmlReadArg * readHelper;
  17773. Owned<IXmlToRowTransformer> rowTransformer;
  17774. Owned<IXMLParse> xmlParser;
  17775. Owned<IColumnProvider> lastMatch;
  17776. unsigned __int64 localOffset;
  17777. public:
  17778. IMPLEMENT_IINTERFACE;
  17779. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17780. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17781. {
  17782. compoundHelper = NULL;
  17783. readHelper = (IHThorXmlReadArg *)&helper;
  17784. localOffset = 0;
  17785. }
  17786. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17787. {
  17788. rowLimit = readHelper->getRowLimit();
  17789. stopAfter = readHelper->getChooseNLimit();
  17790. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17791. if (!useRemote())
  17792. {
  17793. rowTransformer.set(readHelper->queryTransformer());
  17794. assertex(reader != NULL);
  17795. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  17796. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  17797. }
  17798. }
  17799. virtual void reset()
  17800. {
  17801. CRoxieServerDiskReadBaseActivity::reset();
  17802. rowTransformer.clear();
  17803. xmlParser.clear();
  17804. }
  17805. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17806. {
  17807. localOffset = startOffset;
  17808. lastMatch.set(&entry);
  17809. }
  17810. virtual const void *nextInGroup()
  17811. {
  17812. if (eof)
  17813. return NULL;
  17814. else if (useRemote())
  17815. return remote->nextInGroup();
  17816. assertex(xmlParser != NULL);
  17817. try
  17818. {
  17819. while (!eof)
  17820. {
  17821. //call to next() will callback on the IXmlSelect interface
  17822. bool gotNext = false;
  17823. gotNext = xmlParser->next();
  17824. if(!gotNext)
  17825. eof = true;
  17826. else if (lastMatch)
  17827. {
  17828. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17829. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  17830. lastMatch.clear();
  17831. localOffset = 0;
  17832. if (sizeGot)
  17833. {
  17834. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  17835. if (processed > rowLimit)
  17836. {
  17837. if (traceLevel > 4)
  17838. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17839. readHelper->onLimitExceeded();
  17840. throwUnexpected(); // onLimitExceeded is not supposed to return
  17841. }
  17842. processed++;
  17843. if (processed > stopAfter) // MORE - bit of a strange place to check
  17844. {
  17845. eof = true;
  17846. return NULL;
  17847. }
  17848. return ret.getClear();
  17849. }
  17850. }
  17851. }
  17852. return NULL;
  17853. }
  17854. catch(IException *E)
  17855. {
  17856. throw makeWrappedException(E);
  17857. }
  17858. }
  17859. };
  17860. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  17861. {
  17862. IHThorCsvReadArg *readHelper;
  17863. ICsvParameters * csvInfo;
  17864. unsigned headerLines;
  17865. unsigned maxDiskSize;
  17866. CSVSplitter csvSplitter;
  17867. unsigned __int64 localOffset;
  17868. const char *quotes;
  17869. const char *separators;
  17870. const char *terminators;
  17871. const char *escapes;
  17872. public:
  17873. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  17874. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  17875. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes)
  17876. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  17877. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes)
  17878. {
  17879. compoundHelper = NULL;
  17880. readHelper = (IHThorCsvReadArg *)&helper;
  17881. rowLimit = readHelper->getRowLimit();
  17882. stopAfter = readHelper->getChooseNLimit();
  17883. csvInfo = readHelper->queryCsvParameters();
  17884. maxDiskSize = csvInfo->queryMaxSize();
  17885. localOffset = 0;
  17886. headerLines = 0;
  17887. }
  17888. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17889. {
  17890. rowLimit = readHelper->getRowLimit();
  17891. stopAfter = readHelper->getChooseNLimit();
  17892. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17893. if (!useRemote())
  17894. {
  17895. headerLines = csvInfo->queryHeaderLen();
  17896. if (headerLines && isLocal && reader->queryFilePart() != 1)
  17897. 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...
  17898. if (!eof)
  17899. {
  17900. if (varFileInfo)
  17901. {
  17902. const IPropertyTree *options = varFileInfo->queryProperties();
  17903. if (options)
  17904. {
  17905. quotes = options->queryProp("@csvQuote");
  17906. separators = options->queryProp("@csvSeparate");
  17907. terminators = options->queryProp("@csvTerminate");
  17908. escapes = options->queryProp("@csvEscape");
  17909. }
  17910. }
  17911. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  17912. }
  17913. }
  17914. }
  17915. virtual const void *nextInGroup()
  17916. {
  17917. if (eof)
  17918. return NULL;
  17919. else if (useRemote())
  17920. return remote->nextInGroup();
  17921. try
  17922. {
  17923. while (!eof)
  17924. {
  17925. if (reader->eos())
  17926. {
  17927. eof = true;
  17928. break;
  17929. }
  17930. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  17931. size32_t rowSize = 4096; // MORE - make configurable
  17932. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  17933. size32_t thisLineLength;
  17934. loop
  17935. {
  17936. size32_t avail;
  17937. const void *peek = reader->peek(rowSize, avail);
  17938. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  17939. if (thisLineLength < rowSize || avail < rowSize)
  17940. break;
  17941. if (rowSize == maxRowSize)
  17942. throw MakeStringException(0, "Row too big");
  17943. if (rowSize >= maxRowSize/2)
  17944. rowSize = maxRowSize;
  17945. else
  17946. rowSize += rowSize;
  17947. }
  17948. if (headerLines)
  17949. {
  17950. headerLines--;
  17951. reader->skip(thisLineLength);
  17952. }
  17953. else
  17954. {
  17955. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17956. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  17957. reader->skip(thisLineLength);
  17958. if (transformedSize)
  17959. {
  17960. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  17961. if (processed > rowLimit)
  17962. {
  17963. readHelper->onLimitExceeded();
  17964. throwUnexpected(); // onLimitExceeded is not supposed to return
  17965. }
  17966. processed++;
  17967. if (processed > stopAfter) // MORE - bit of a strange place to check
  17968. {
  17969. eof = true;
  17970. return NULL;
  17971. }
  17972. return ret.getClear();
  17973. }
  17974. }
  17975. }
  17976. return NULL;
  17977. }
  17978. catch(IException *E)
  17979. {
  17980. throw makeWrappedException(E);
  17981. }
  17982. }
  17983. virtual void reset()
  17984. {
  17985. CRoxieServerDiskReadBaseActivity::reset();
  17986. csvSplitter.reset();
  17987. localOffset = 0;
  17988. }
  17989. virtual unsigned __int64 getFilePosition(const void * row)
  17990. {
  17991. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  17992. }
  17993. virtual unsigned __int64 getLocalFilePosition(const void * row)
  17994. {
  17995. UNIMPLEMENTED;
  17996. }
  17997. };
  17998. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  17999. {
  18000. IHThorDiskNormalizeArg *normalizeHelper;
  18001. bool firstPending;
  18002. public:
  18003. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18004. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18005. {
  18006. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18007. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18008. firstPending = true;
  18009. }
  18010. virtual void reset()
  18011. {
  18012. firstPending = true;
  18013. CRoxieServerDiskReadBaseActivity::reset();
  18014. }
  18015. virtual const void *nextInGroup()
  18016. {
  18017. if (eof)
  18018. return NULL;
  18019. else if (useRemote())
  18020. return remote->nextInGroup();
  18021. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18022. unsigned transformedSize = 0;
  18023. if (isKeyed)
  18024. {
  18025. loop
  18026. {
  18027. while (firstPending)
  18028. {
  18029. const void *nextCandidate = cursor->nextMatch();
  18030. if (!nextCandidate)
  18031. {
  18032. eof = true;
  18033. return NULL;
  18034. }
  18035. if (normalizeHelper->first(nextCandidate))
  18036. {
  18037. firstPending = false;
  18038. break;
  18039. }
  18040. }
  18041. transformedSize = normalizeHelper->transform(rowBuilder);
  18042. firstPending = !normalizeHelper->next();
  18043. if (transformedSize)
  18044. break;
  18045. }
  18046. }
  18047. else
  18048. {
  18049. assertex(reader != NULL);
  18050. loop
  18051. {
  18052. while (firstPending)
  18053. {
  18054. if (deserializeSource.eos())
  18055. {
  18056. eof = true;
  18057. return NULL;
  18058. }
  18059. prefetcher->readAhead(deserializeSource);
  18060. const byte *nextRec = deserializeSource.queryRow();
  18061. if (!cursor || !cursor->isFiltered(nextRec))
  18062. {
  18063. if (normalizeHelper->first(nextRec))
  18064. firstPending = false;
  18065. }
  18066. deserializeSource.finishedRow();
  18067. }
  18068. transformedSize = normalizeHelper->transform(rowBuilder);
  18069. firstPending = !normalizeHelper->next();
  18070. if (transformedSize)
  18071. break;
  18072. }
  18073. }
  18074. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18075. processed++;
  18076. if (processed > rowLimit)
  18077. {
  18078. compoundHelper->onLimitExceeded();
  18079. throwUnexpected(); // onLimitExceeded is not supposed to return
  18080. }
  18081. if (processed > stopAfter) // MORE - bit of a strange place to check
  18082. {
  18083. eof = true;
  18084. return NULL;
  18085. }
  18086. return recBuffer.getClear();
  18087. }
  18088. };
  18089. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18090. {
  18091. protected:
  18092. bool done;
  18093. public:
  18094. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18095. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18096. done(false)
  18097. {
  18098. }
  18099. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18100. {
  18101. done = false;
  18102. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18103. }
  18104. virtual IRoxieInput *queryOutput(unsigned idx)
  18105. {
  18106. if (idx==(unsigned)-1)
  18107. idx = 0;
  18108. return idx ? NULL: this;
  18109. }
  18110. };
  18111. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18112. {
  18113. IHThorDiskCountArg & countHelper;
  18114. unsigned __int64 choosenLimit;
  18115. IHThorSourceCountLimit *limitHelper;
  18116. unsigned __int64 getSkippedCount()
  18117. {
  18118. unsigned flags = countHelper.getFlags();
  18119. if (flags & TDRlimitskips)
  18120. return 0;
  18121. else if (flags & TDRlimitcreates)
  18122. return 1;
  18123. else
  18124. {
  18125. assertex(limitHelper);
  18126. if (traceLevel > 4)
  18127. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18128. limitHelper->onLimitExceeded();
  18129. throwUnexpected(); // onLimitExceeded should always throw exception
  18130. }
  18131. }
  18132. public:
  18133. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18134. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18135. countHelper((IHThorDiskCountArg &)basehelper)
  18136. {
  18137. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18138. choosenLimit = 0;
  18139. }
  18140. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18141. {
  18142. choosenLimit = countHelper.getChooseNLimit();
  18143. if (limitHelper)
  18144. {
  18145. rowLimit = limitHelper->getRowLimit();
  18146. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18147. }
  18148. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18149. }
  18150. virtual const void *nextInGroup()
  18151. {
  18152. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18153. if (done) return NULL;
  18154. done = true;
  18155. unsigned __int64 totalCount = 0;
  18156. if (helper.canMatchAny() && !eof)
  18157. {
  18158. if (useRemote())
  18159. {
  18160. loop
  18161. {
  18162. const void * next = remote->nextInGroup();
  18163. if (!next)
  18164. break;
  18165. if (meta.getFixedSize() == 1)
  18166. totalCount += *(byte *)next;
  18167. else
  18168. totalCount += *(unsigned __int64 *)next;
  18169. ReleaseRoxieRow(next);
  18170. if (totalCount > rowLimit)
  18171. {
  18172. totalCount = getSkippedCount();
  18173. break;
  18174. }
  18175. else if (totalCount >= choosenLimit)
  18176. {
  18177. totalCount = choosenLimit;
  18178. break;
  18179. }
  18180. }
  18181. }
  18182. else
  18183. {
  18184. if (isKeyed)
  18185. {
  18186. loop
  18187. {
  18188. const void *nextCandidate = cursor->nextMatch();
  18189. if (!nextCandidate)
  18190. break;
  18191. totalCount += countHelper.numValid(nextCandidate);
  18192. if (totalCount > rowLimit)
  18193. {
  18194. totalCount = getSkippedCount();
  18195. break;
  18196. }
  18197. else if (totalCount >= choosenLimit)
  18198. {
  18199. totalCount = choosenLimit;
  18200. break;
  18201. }
  18202. }
  18203. }
  18204. else
  18205. {
  18206. assertex(reader != NULL);
  18207. while (!deserializeSource.eos())
  18208. {
  18209. prefetcher->readAhead(deserializeSource);
  18210. const byte *nextRec = deserializeSource.queryRow();
  18211. if (!cursor || !cursor->isFiltered(nextRec))
  18212. {
  18213. totalCount += countHelper.numValid(nextRec);
  18214. }
  18215. deserializeSource.finishedRow();
  18216. if (totalCount > rowLimit)
  18217. {
  18218. totalCount = getSkippedCount();
  18219. break;
  18220. }
  18221. else if (totalCount >= choosenLimit)
  18222. {
  18223. totalCount = choosenLimit;
  18224. break;
  18225. }
  18226. }
  18227. }
  18228. }
  18229. }
  18230. size32_t rowSize = meta.getFixedSize();
  18231. void * result = rowAllocator->createRow();
  18232. if (rowSize == 1)
  18233. *(byte *)result = (byte)totalCount;
  18234. else
  18235. {
  18236. assertex(rowSize == sizeof(unsigned __int64));
  18237. *(unsigned __int64 *)result = totalCount;
  18238. }
  18239. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  18240. }
  18241. };
  18242. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18243. {
  18244. IHThorCompoundAggregateExtra & aggregateHelper;
  18245. public:
  18246. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18247. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18248. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18249. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  18250. {
  18251. }
  18252. const void * gatherMerged()
  18253. {
  18254. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  18255. size32_t finalSize = 0;
  18256. if (useRemote())
  18257. {
  18258. const void * firstRow = remote->nextInGroup();
  18259. if (!firstRow)
  18260. {
  18261. rowBuilder.ensureRow();
  18262. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  18263. }
  18264. else
  18265. {
  18266. // NOTE need to clone this because going to modify below, could special case 1 row only
  18267. finalSize = cloneRow(rowBuilder, firstRow, meta);
  18268. ReleaseRoxieRow(firstRow);
  18269. }
  18270. loop
  18271. {
  18272. const void * next = remote->nextInGroup();
  18273. if (!next)
  18274. break;
  18275. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  18276. ReleaseRoxieRow(next);
  18277. }
  18278. }
  18279. else
  18280. {
  18281. aggregateHelper.clearAggregate(rowBuilder);
  18282. if (helper.canMatchAny() && !eof)
  18283. {
  18284. if (isKeyed)
  18285. {
  18286. loop
  18287. {
  18288. const void *next = cursor->nextMatch();
  18289. if (!next)
  18290. break;
  18291. aggregateHelper.processRow(rowBuilder, next);
  18292. }
  18293. }
  18294. else
  18295. {
  18296. assertex(reader != NULL);
  18297. while (!deserializeSource.eos())
  18298. {
  18299. prefetcher->readAhead(deserializeSource);
  18300. const byte *nextRec = deserializeSource.queryRow();
  18301. if (!cursor || !cursor->isFiltered(nextRec))
  18302. {
  18303. aggregateHelper.processRow(rowBuilder, nextRec);
  18304. }
  18305. deserializeSource.finishedRow();
  18306. }
  18307. }
  18308. }
  18309. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  18310. }
  18311. return rowBuilder.finalizeRowClear(finalSize);
  18312. }
  18313. virtual const void *nextInGroup()
  18314. {
  18315. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18316. if (done) return NULL;
  18317. const void * ret = gatherMerged();
  18318. done = true;
  18319. return ret;
  18320. }
  18321. };
  18322. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18323. {
  18324. IHThorDiskGroupAggregateArg & aggregateHelper;
  18325. RowAggregator resultAggregator;
  18326. bool gathered;
  18327. public:
  18328. IMPLEMENT_IINTERFACE;
  18329. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18330. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18331. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  18332. resultAggregator(aggregateHelper, aggregateHelper),
  18333. gathered(false)
  18334. {
  18335. }
  18336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18337. {
  18338. gathered= false;
  18339. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18340. resultAggregator.start(rowAllocator);
  18341. }
  18342. virtual void reset()
  18343. {
  18344. resultAggregator.reset();
  18345. CRoxieServerDiskAggregateBaseActivity::reset();
  18346. }
  18347. void gatherMerged()
  18348. {
  18349. if (useRemote())
  18350. {
  18351. loop
  18352. {
  18353. const void * next = remote->nextInGroup();
  18354. if (!next)
  18355. break;
  18356. resultAggregator.mergeElement(next);
  18357. ReleaseRoxieRow(next);
  18358. }
  18359. }
  18360. else
  18361. {
  18362. if (helper.canMatchAny() && !eof)
  18363. {
  18364. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  18365. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  18366. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  18367. ctx->queryCodeContext(), activityId);
  18368. processor->doQuery(NULL, 0, 0, 0);
  18369. }
  18370. }
  18371. gathered = true;
  18372. }
  18373. virtual const void *nextInGroup()
  18374. {
  18375. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18376. if (done)
  18377. return NULL;
  18378. if (!gathered)
  18379. gatherMerged();
  18380. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  18381. if (next)
  18382. {
  18383. processed++;
  18384. return next->finalizeRowClear();
  18385. }
  18386. done = true;
  18387. return NULL;
  18388. }
  18389. };
  18390. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  18391. {
  18392. public:
  18393. RemoteActivityId remoteId;
  18394. bool isLocal;
  18395. bool sorted;
  18396. bool maySkip;
  18397. bool variableFileName;
  18398. Owned<IFilePartMap> map;
  18399. Owned<IFileIOArray> files;
  18400. Owned<IInMemoryIndexManager> manager;
  18401. Owned<const IResolvedFile> datafile;
  18402. const char *quotes;
  18403. const char *separators;
  18404. const char *terminators;
  18405. const char *escapes;
  18406. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18407. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  18408. {
  18409. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  18410. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  18411. sorted = (helper->getFlags() & TDRunsorted) == 0;
  18412. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18413. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  18414. quotes = separators = terminators = escapes = NULL;
  18415. if (!variableFileName)
  18416. {
  18417. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  18418. OwnedRoxieString fileName(helper->getFileName());
  18419. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, _queryFactory.queryWorkUnit()));
  18420. if (datafile)
  18421. map.setown(datafile->getFileMap());
  18422. bool isSimple = (map && map->getNumParts()==1 && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false));
  18423. if (isLocal || isSimple)
  18424. {
  18425. if (datafile)
  18426. {
  18427. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  18428. files.setown(datafile->getIFileIOArray(isOpt, channel));
  18429. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  18430. const IPropertyTree *options = datafile->queryProperties();
  18431. if (options)
  18432. {
  18433. quotes = options->queryProp("@csvQuote");
  18434. separators = options->queryProp("@csvSeparate");
  18435. terminators = options->queryProp("@csvTerminate");
  18436. escapes = options->queryProp("@csvEscape");
  18437. }
  18438. }
  18439. else
  18440. manager.setown(getEmptyIndexManager());
  18441. }
  18442. }
  18443. }
  18444. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18445. {
  18446. unsigned numParts = map ? map->getNumParts() : 0;
  18447. switch (kind)
  18448. {
  18449. case TAKcsvread:
  18450. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  18451. quotes, separators, terminators, escapes);
  18452. case TAKxmlread:
  18453. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18454. case TAKdiskread:
  18455. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18456. case TAKdisknormalize:
  18457. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  18458. case TAKdiskcount:
  18459. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18460. case TAKdiskaggregate:
  18461. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18462. case TAKdiskgroupaggregate:
  18463. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18464. }
  18465. throwUnexpected();
  18466. }
  18467. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18468. {
  18469. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  18470. }
  18471. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  18472. {
  18473. if (datafile)
  18474. addXrefFileInfo(reply, datafile);
  18475. }
  18476. };
  18477. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18478. {
  18479. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  18480. }
  18481. //=================================================================================
  18482. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  18483. {
  18484. protected:
  18485. IHThorIndexReadBaseArg &indexHelper;
  18486. IHThorSteppedSourceExtra * steppedExtra;
  18487. Linked<IKeyArray> keySet;
  18488. Linked<TranslatorArray> translators;
  18489. CSkippableRemoteResultAdaptor remote;
  18490. CIndexTransformCallback callback;
  18491. bool sorted;
  18492. bool variableFileName;
  18493. bool variableInfoPending;
  18494. bool isOpt;
  18495. bool isLocal;
  18496. unsigned __int64 rowLimit;
  18497. unsigned __int64 keyedLimit;
  18498. unsigned __int64 choosenLimit;
  18499. unsigned accepted;
  18500. unsigned rejected;
  18501. unsigned seekGEOffset;
  18502. Owned<IKeyManager> tlk;
  18503. Owned<const IResolvedFile> varFileInfo;
  18504. const RemoteActivityId &remoteId;
  18505. void setVariableFileInfo()
  18506. {
  18507. OwnedRoxieString indexName(indexHelper.getFileName());
  18508. varFileInfo.setown(resolveLFN(indexName, isOpt));
  18509. if (varFileInfo)
  18510. {
  18511. translators.setown(new TranslatorArray) ;
  18512. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  18513. }
  18514. variableInfoPending = false;
  18515. }
  18516. public:
  18517. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18518. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18519. : CRoxieServerActivity(_factory, _probeManager),
  18520. keySet(_keySet),
  18521. translators(_translators),
  18522. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  18523. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  18524. remoteId(_remoteId),
  18525. sorted(_sorted),
  18526. isLocal(_isLocal)
  18527. {
  18528. indexHelper.setCallback(&callback);
  18529. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  18530. variableFileName = allFilesDynamic || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  18531. variableInfoPending = false;
  18532. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  18533. seekGEOffset = 0;
  18534. // started = false;
  18535. rejected = accepted = 0;
  18536. rowLimit = choosenLimit = keyedLimit = 0;
  18537. }
  18538. virtual const IResolvedFile *queryVarFileInfo() const
  18539. {
  18540. return varFileInfo;
  18541. }
  18542. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18543. {
  18544. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18545. remote.onCreate(this, this, _ctx, _colocalParent);
  18546. }
  18547. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18548. {
  18549. accepted = 0;
  18550. rejected = 0;
  18551. rowLimit = (unsigned __int64) -1;
  18552. keyedLimit = (unsigned __int64 ) -1;
  18553. choosenLimit = I64C(0x7fffffffffffffff);
  18554. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18555. remote.onStart(parentExtractSize, parentExtract);
  18556. variableInfoPending = variableFileName;
  18557. }
  18558. void processAllKeys()
  18559. {
  18560. try
  18561. {
  18562. if (indexHelper.canMatchAny())
  18563. {
  18564. if (variableInfoPending)
  18565. setVariableFileInfo();
  18566. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  18567. if (keySet)
  18568. {
  18569. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  18570. // 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
  18571. // However order is probably better to iterate fileno's inside partnos
  18572. // MORE - also not properly supporting STEPPED I fear.
  18573. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  18574. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  18575. {
  18576. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  18577. if (thisBase)
  18578. {
  18579. unsigned fileNo = 0;
  18580. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  18581. if (seekGEOffset && !thisKey->isTopLevelKey())
  18582. {
  18583. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  18584. }
  18585. else
  18586. {
  18587. tlk.setown(createKeyManager(thisKey, 0, this));
  18588. tlk->setLayoutTranslator(translators->item(fileNo));
  18589. }
  18590. createSegmentMonitors(tlk);
  18591. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  18592. {
  18593. StringBuffer out;
  18594. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  18595. CTXLOG("Using filter %s", out.str());
  18596. if (ctx->queryProbeManager())
  18597. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  18598. }
  18599. tlk->reset();
  18600. loop // for each file part
  18601. {
  18602. //block for TransformCallbackAssociation
  18603. {
  18604. TransformCallbackAssociation associate(callback, tlk);
  18605. if (thisKey->isTopLevelKey())
  18606. {
  18607. if (thisKey->isFullySorted())
  18608. {
  18609. while (tlk->lookup(false))
  18610. {
  18611. unsigned slavePart = (unsigned) tlk->queryFpos();
  18612. if (slavePart)
  18613. {
  18614. accepted++;
  18615. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  18616. if (sorted && numChannels>1)
  18617. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  18618. }
  18619. }
  18620. }
  18621. else
  18622. {
  18623. // MORE - we could check whether there are any matching parts if we wanted.
  18624. // If people are in the habit of sending null values that would be worthwhile
  18625. remote.getMem(0, fileNo, 0);
  18626. }
  18627. }
  18628. else
  18629. {
  18630. if (keyedLimit != (unsigned __int64) -1)
  18631. {
  18632. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  18633. {
  18634. unsigned __int64 count = tlk->checkCount(keyedLimit);
  18635. if (count > keyedLimit)
  18636. {
  18637. if (traceLevel > 4)
  18638. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  18639. onLimitExceeded(true);
  18640. }
  18641. tlk->reset();
  18642. }
  18643. }
  18644. if (processSingleKey(thisKey, translators->item(fileNo)))
  18645. break;
  18646. }
  18647. }
  18648. if (++fileNo < thisBase->numParts())
  18649. {
  18650. thisKey = thisBase->queryPart(fileNo);
  18651. tlk->setKey(thisKey);
  18652. tlk->setLayoutTranslator(translators->item(fileNo));
  18653. tlk->reset();
  18654. }
  18655. else
  18656. break;
  18657. }
  18658. tlk->releaseSegmentMonitors();
  18659. tlk->setKey(NULL);
  18660. }
  18661. }
  18662. }
  18663. }
  18664. remote.flush();
  18665. remote.senddone();
  18666. }
  18667. catch (IException *E)
  18668. {
  18669. remote.setException(E);
  18670. }
  18671. }
  18672. virtual void createSegmentMonitors(IKeyManager *key)
  18673. {
  18674. indexHelper.createSegmentMonitors(key);
  18675. key->finishSegmentMonitors();
  18676. }
  18677. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  18678. virtual void reset()
  18679. {
  18680. if (accepted)
  18681. noteStatistic(STATS_ACCEPTED, accepted, 1);
  18682. if (rejected)
  18683. noteStatistic(STATS_REJECTED, rejected, 1);
  18684. remote.onReset();
  18685. CRoxieServerActivity::reset();
  18686. if (varFileInfo)
  18687. {
  18688. keySet.clear();
  18689. varFileInfo.clear();
  18690. }
  18691. variableInfoPending = false;
  18692. }
  18693. virtual void stop(bool aborting)
  18694. {
  18695. remote.onStop(aborting);
  18696. CRoxieServerActivity::stop(aborting);
  18697. }
  18698. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18699. {
  18700. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18701. }
  18702. };
  18703. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  18704. {
  18705. IHThorSourceLimitTransformExtra * limitTransformExtra;
  18706. public:
  18707. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18708. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18709. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  18710. {
  18711. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  18712. }
  18713. virtual void reset()
  18714. {
  18715. remote.onReset();
  18716. CRoxieServerIndexActivity::reset();
  18717. }
  18718. virtual const void *nextInGroup()
  18719. {
  18720. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18721. try
  18722. {
  18723. const void *ret = remote.nextInGroup();
  18724. if (ret)
  18725. processed++;
  18726. return ret;
  18727. }
  18728. catch (IException *E)
  18729. {
  18730. throw makeWrappedException(E);
  18731. }
  18732. }
  18733. protected:
  18734. virtual const void * createLimitFailRow(bool isKeyed)
  18735. {
  18736. createRowAllocator();
  18737. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18738. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18739. if (outSize)
  18740. return rowBuilder.finalizeRowClear(outSize);
  18741. return NULL;
  18742. }
  18743. };
  18744. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  18745. {
  18746. protected:
  18747. IHThorCompoundReadExtra & readHelper;
  18748. ISteppingMeta *rawMeta;
  18749. CSteppingMeta steppingMeta;
  18750. unsigned * seekSizes;
  18751. bool optimizeSteppedPostFilter;
  18752. ISteppingMeta * projectedMeta;
  18753. unsigned maxSeekLookahead;
  18754. public:
  18755. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18756. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  18757. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  18758. readHelper((IHThorIndexReadArg &)basehelper)
  18759. {
  18760. rawMeta = readHelper.queryRawSteppingMeta();
  18761. unsigned flags = indexHelper.getFlags();
  18762. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  18763. seekSizes = NULL;
  18764. maxSeekLookahead = _maxSeekLookahead;
  18765. if (rawMeta)
  18766. {
  18767. const CFieldOffsetSize * fields = rawMeta->queryFields();
  18768. unsigned maxFields = rawMeta->getNumFields();
  18769. seekGEOffset = fields[0].offset;
  18770. seekSizes = new unsigned[maxFields];
  18771. seekSizes[0] = fields[0].size;
  18772. for (unsigned i=1; i < maxFields; i++)
  18773. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  18774. projectedMeta = readHelper.queryProjectedSteppingMeta();
  18775. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  18776. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  18777. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  18778. steppingMeta.init(useMeta, hasPostFilter);
  18779. }
  18780. }
  18781. ~CRoxieServerIndexReadActivity()
  18782. {
  18783. delete [] seekSizes;
  18784. }
  18785. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18786. {
  18787. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18788. steppingMeta.setDistributed();
  18789. if (steppedExtra)
  18790. steppingMeta.setExtra(steppedExtra);
  18791. rowLimit = readHelper.getRowLimit();
  18792. keyedLimit = readHelper.getKeyedLimit();
  18793. choosenLimit = readHelper.getChooseNLimit();
  18794. if (!paused)
  18795. processAllKeys();
  18796. }
  18797. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  18798. {
  18799. public:
  18800. IMPLEMENT_IINTERFACE;
  18801. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  18802. {
  18803. Link();
  18804. return const_cast<LazyLocalKeyReader*> (this);
  18805. }
  18806. virtual const void *getMessageHeader(unsigned &length) const
  18807. {
  18808. length = 0;
  18809. return NULL;
  18810. }
  18811. virtual const void *getMessageMetadata(unsigned &length) const
  18812. {
  18813. length = 0;
  18814. return NULL;
  18815. }
  18816. virtual void discard() const
  18817. {
  18818. // nothing to do.
  18819. }
  18820. unsigned keyedCount;
  18821. unsigned matched;
  18822. bool EOFseen;
  18823. Owned<IKeyIndexSet> keySet;
  18824. Owned<IKeyManager> tlk;
  18825. CRoxieServerIndexReadActivity &owner;
  18826. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  18827. : owner(_owner)
  18828. {
  18829. keyedCount = 0;
  18830. matched = 0;
  18831. EOFseen = false;
  18832. keySet.setown(createKeyIndexSet());
  18833. keySet->addIndex(LINK(key));
  18834. if (owner.seekGEOffset)
  18835. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  18836. else
  18837. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  18838. tlk->setLayoutTranslator(trans);
  18839. owner.indexHelper.createSegmentMonitors(tlk);
  18840. tlk->finishSegmentMonitors();
  18841. tlk->reset();
  18842. }
  18843. virtual const void *getNext(int length)
  18844. {
  18845. TransformCallbackAssociation associate(owner.callback, tlk);
  18846. while (tlk->lookup(true))
  18847. {
  18848. keyedCount++;
  18849. if (keyedCount > owner.keyedLimit)
  18850. {
  18851. owner.onLimitExceeded(true); // Should throw exception
  18852. throwUnexpected();
  18853. }
  18854. size32_t transformedSize;
  18855. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  18856. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  18857. try
  18858. {
  18859. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  18860. owner.callback.finishedRow();
  18861. }
  18862. catch (IException *E)
  18863. {
  18864. throw owner.makeWrappedException(E);
  18865. }
  18866. if (transformedSize)
  18867. {
  18868. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  18869. matched++;
  18870. if (matched > owner.rowLimit)
  18871. {
  18872. owner.onLimitExceeded(false); // Should throw exception
  18873. throwUnexpected();
  18874. }
  18875. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  18876. {
  18877. break;
  18878. }
  18879. owner.accepted++;
  18880. return result.getClear();
  18881. }
  18882. else
  18883. owner.rejected++;
  18884. }
  18885. EOFseen = true;
  18886. return NULL;
  18887. }
  18888. virtual bool atEOF() const
  18889. {
  18890. return EOFseen;
  18891. }
  18892. virtual bool isSerialized() const
  18893. {
  18894. return false;
  18895. }
  18896. };
  18897. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  18898. {
  18899. createRowAllocator();
  18900. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  18901. return false;
  18902. }
  18903. virtual void onLimitExceeded(bool isKeyed)
  18904. {
  18905. if (traceLevel > 4)
  18906. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18907. if (isKeyed)
  18908. {
  18909. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  18910. {
  18911. if (ctx->queryDebugContext())
  18912. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18913. throw makeLimitSkipException(true);
  18914. }
  18915. else
  18916. readHelper.onKeyedLimitExceeded();
  18917. }
  18918. else
  18919. {
  18920. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  18921. {
  18922. if (ctx->queryDebugContext())
  18923. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18924. throw makeLimitSkipException(false);
  18925. }
  18926. else
  18927. readHelper.onLimitExceeded();
  18928. }
  18929. }
  18930. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  18931. {
  18932. out.append((unsigned short) numFields);
  18933. out.append((unsigned short) seekLen);
  18934. out.append((unsigned short) stepExtra.queryFlags());
  18935. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  18936. if (seeks)
  18937. {
  18938. unsigned lookahead = 40000/seekLen;
  18939. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  18940. lookahead = maxSeekLookahead;
  18941. seeks->ensureFilled(seek, numFields, lookahead);
  18942. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  18943. unsigned serialized = 1; // rawseek is always serialized...
  18944. unsigned patchLength = out.length();
  18945. out.append(serialized); // NOTE - we come back and patch with the actual value...
  18946. out.append(seekLen, rawSeek);
  18947. if (seeks->ordinality())
  18948. {
  18949. const void *lastSeek = rawSeek;
  18950. byte *nextSeek = NULL;
  18951. if (projectedMeta)
  18952. nextSeek = (byte *) alloca(seekLen);
  18953. for (unsigned i = 0; i < seeks->ordinality(); i++)
  18954. {
  18955. if (projectedMeta)
  18956. {
  18957. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  18958. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  18959. }
  18960. else
  18961. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  18962. int diff = memcmp(nextSeek, lastSeek, seekLen);
  18963. if (diff > 0)
  18964. {
  18965. serialized++;
  18966. out.append(seekLen, nextSeek);
  18967. lastSeek = (const byte *) out.reserve(0) - seekLen;
  18968. }
  18969. }
  18970. unsigned length = out.length();
  18971. out.setWritePos(patchLength);
  18972. out.append(serialized);
  18973. out.setWritePos(length);
  18974. }
  18975. }
  18976. else
  18977. {
  18978. out.append(false);
  18979. out.append(1);
  18980. out.append(seekLen, rawSeek);
  18981. }
  18982. }
  18983. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18984. {
  18985. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18986. try
  18987. {
  18988. unsigned seeklen = 0;
  18989. const void *rawSeek = NULL;
  18990. if (seek && numFields)
  18991. {
  18992. seeklen = seekSizes[numFields-1];
  18993. rawSeek = (const byte *)seek + seekGEOffset;
  18994. if (projectedMeta)
  18995. {
  18996. byte * temp = (byte *) alloca(seeklen);
  18997. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  18998. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  18999. rawSeek = (byte *)temp;
  19000. }
  19001. }
  19002. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19003. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19004. processed++;
  19005. return ret;
  19006. }
  19007. catch (IException *E)
  19008. {
  19009. throw makeWrappedException(E);
  19010. }
  19011. }
  19012. virtual IInputSteppingMeta * querySteppingMeta()
  19013. {
  19014. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19015. return &steppingMeta;
  19016. return NULL;
  19017. }
  19018. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19019. {
  19020. if (variableInfoPending)
  19021. setVariableFileInfo();
  19022. return this;
  19023. }
  19024. virtual IKeyArray *getKeySet() const
  19025. {
  19026. return keySet.getLink();
  19027. }
  19028. virtual const IResolvedFile *getVarFileInfo() const
  19029. {
  19030. return varFileInfo.getLink();
  19031. }
  19032. virtual TranslatorArray *getTranslators() const
  19033. {
  19034. return translators.getLink();
  19035. }
  19036. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19037. {
  19038. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19039. }
  19040. virtual IRoxieServerActivity *queryActivity() { return this; }
  19041. virtual const RemoteActivityId& queryRemoteId() const
  19042. {
  19043. return remoteId;
  19044. }
  19045. };
  19046. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19047. {
  19048. IHThorCompoundReadExtra & readHelper;
  19049. IHThorIndexReadBaseArg & indexHelper;
  19050. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19051. IHThorSteppedSourceExtra * steppedExtra;
  19052. bool eof;
  19053. Linked<IKeyArray>keySet;
  19054. Owned<IKeyIndexSet>keyIndexSet;
  19055. Owned<IKeyManager> tlk;
  19056. Linked<TranslatorArray> translators;
  19057. CIndexTransformCallback callback;
  19058. unsigned __int64 keyedLimit;
  19059. unsigned rowLimit;
  19060. unsigned chooseNLimit;
  19061. unsigned accepted;
  19062. unsigned rejected;
  19063. unsigned keyedCount;
  19064. ISteppingMeta * rawMeta;
  19065. ISteppingMeta * projectedMeta;
  19066. size32_t seekGEOffset;
  19067. unsigned * seekSizes;
  19068. CSteppingMeta steppingMeta;
  19069. Owned<const IResolvedFile> varFileInfo;
  19070. const RemoteActivityId &remoteId;
  19071. bool firstRead;
  19072. bool variableFileName;
  19073. bool variableInfoPending;
  19074. bool isOpt;
  19075. bool isLocal;
  19076. bool optimizeSteppedPostFilter;
  19077. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19078. void initKeySet()
  19079. {
  19080. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19081. {
  19082. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19083. }
  19084. keyIndexSet.setown(createKeyIndexSet());
  19085. for (unsigned part = 0; part < keySet->length(); part++)
  19086. {
  19087. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19088. if (kib)
  19089. {
  19090. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19091. {
  19092. IKeyIndex *k = kib->queryPart(subpart);
  19093. if (k)
  19094. {
  19095. assertex(!k->isTopLevelKey());
  19096. keyIndexSet->addIndex(LINK(k));
  19097. }
  19098. }
  19099. }
  19100. }
  19101. }
  19102. void setVariableFileInfo()
  19103. {
  19104. OwnedRoxieString indexName(indexHelper.getFileName());
  19105. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19106. translators.setown(new TranslatorArray) ;
  19107. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  19108. initKeySet();
  19109. variableInfoPending = false;
  19110. }
  19111. void onEOF()
  19112. {
  19113. callback.setManager(NULL);
  19114. eof = true;
  19115. tlk.clear();
  19116. }
  19117. public:
  19118. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19119. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19120. : CRoxieServerActivity(_factory, _probeManager),
  19121. readHelper((IHThorIndexReadArg &)basehelper),
  19122. indexHelper((IHThorIndexReadArg &)basehelper),
  19123. translators(_translatorArray),
  19124. keySet(_keyArray),
  19125. isLocal(_isLocal),
  19126. remoteId(_remoteId)
  19127. {
  19128. rowLimit = 0;
  19129. keyedLimit = 0;
  19130. chooseNLimit = 0;
  19131. indexHelper.setCallback(&callback);
  19132. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19133. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19134. unsigned flags = indexHelper.getFlags();
  19135. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19136. variableInfoPending = false;
  19137. isOpt = (flags & TIRoptional) != 0;
  19138. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19139. firstRead = true;
  19140. accepted = 0;
  19141. rejected = 0;
  19142. keyedCount = 0;
  19143. eof = false;
  19144. rawMeta = readHelper.queryRawSteppingMeta();
  19145. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19146. seekGEOffset = 0;
  19147. seekSizes = NULL;
  19148. if (rawMeta)
  19149. {
  19150. // MORE - should check all keys in maxFields list can actually be keyed.
  19151. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19152. unsigned maxFields = rawMeta->getNumFields();
  19153. seekGEOffset = fields[0].offset;
  19154. seekSizes = new unsigned[maxFields];
  19155. seekSizes[0] = fields[0].size;
  19156. for (unsigned i=1; i < maxFields; i++)
  19157. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19158. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19159. if (projectedMeta)
  19160. steppingMeta.init(projectedMeta, hasPostFilter);
  19161. else
  19162. steppingMeta.init(rawMeta, hasPostFilter);
  19163. }
  19164. }
  19165. virtual const IResolvedFile *queryVarFileInfo() const
  19166. {
  19167. return varFileInfo;
  19168. }
  19169. ~CRoxieServerSimpleIndexReadActivity()
  19170. {
  19171. delete [] seekSizes;
  19172. }
  19173. virtual bool needsAllocator() const { return true; }
  19174. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19175. {
  19176. firstRead = true;
  19177. accepted = 0;
  19178. rejected = 0;
  19179. keyedCount = 0;
  19180. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19181. if (steppedExtra)
  19182. steppingMeta.setExtra(steppedExtra);
  19183. eof = !indexHelper.canMatchAny();
  19184. if (variableFileName)
  19185. variableInfoPending = true;
  19186. else
  19187. {
  19188. variableInfoPending = false;
  19189. if (!keyIndexSet)
  19190. initKeySet();
  19191. }
  19192. }
  19193. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19194. {
  19195. if (variableInfoPending)
  19196. setVariableFileInfo();
  19197. return this;
  19198. }
  19199. virtual IKeyArray *getKeySet() const
  19200. {
  19201. return keySet.getLink();
  19202. }
  19203. virtual const IResolvedFile *getVarFileInfo() const
  19204. {
  19205. return varFileInfo.getLink();
  19206. }
  19207. virtual TranslatorArray *getTranslators() const
  19208. {
  19209. return translators.getLink();
  19210. }
  19211. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19212. {
  19213. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19214. }
  19215. virtual IRoxieServerActivity *queryActivity() { return this; }
  19216. virtual const RemoteActivityId& queryRemoteId() const
  19217. {
  19218. return remoteId;
  19219. }
  19220. const void *nextInGroup()
  19221. {
  19222. bool matched = true;
  19223. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  19224. }
  19225. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19226. {
  19227. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19228. if (eof)
  19229. return NULL;
  19230. if (firstRead)
  19231. {
  19232. if (variableInfoPending)
  19233. setVariableFileInfo();
  19234. rowLimit = (unsigned) readHelper.getRowLimit();
  19235. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  19236. unsigned numParts = keyIndexSet->numParts();
  19237. if (!numParts)
  19238. {
  19239. onEOF();
  19240. return NULL;
  19241. }
  19242. if (numParts > 1 || seekGEOffset)
  19243. {
  19244. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  19245. // note that we don't set up translator because we don't support it. If that ever changes...
  19246. }
  19247. else
  19248. {
  19249. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  19250. tlk->setLayoutTranslator(translators->item(0));
  19251. }
  19252. indexHelper.createSegmentMonitors(tlk);
  19253. tlk->finishSegmentMonitors();
  19254. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19255. {
  19256. StringBuffer out;
  19257. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19258. CTXLOG("Using filter %s", out.str());
  19259. if (ctx->queryProbeManager())
  19260. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19261. }
  19262. tlk->reset();
  19263. callback.setManager(tlk);
  19264. keyedLimit = readHelper.getKeyedLimit();
  19265. if (keyedLimit != (unsigned __int64) -1)
  19266. {
  19267. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19268. {
  19269. unsigned __int64 count = tlk->checkCount(keyedLimit);
  19270. if (count > keyedLimit)
  19271. {
  19272. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  19273. readHelper.onKeyedLimitExceeded();
  19274. const void * ret = NULL;
  19275. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  19276. ret = createKeyedLimitOnFailRow();
  19277. onEOF();
  19278. return ret;
  19279. }
  19280. tlk->reset();
  19281. keyedLimit = (unsigned __int64) -1;
  19282. }
  19283. }
  19284. firstRead = false;
  19285. }
  19286. if (accepted == chooseNLimit)
  19287. {
  19288. onEOF();
  19289. return NULL;
  19290. }
  19291. const byte * rawSeek = NULL;
  19292. unsigned seekSize = 0;
  19293. if (seek)
  19294. {
  19295. seekSize = seekSizes[numFields-1];
  19296. rawSeek = (const byte *)seek + seekGEOffset;
  19297. if (projectedMeta)
  19298. {
  19299. byte *temp = (byte *) alloca(seekSize);
  19300. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  19301. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19302. rawSeek = (byte *)temp;
  19303. }
  19304. #ifdef _DEBUG
  19305. // StringBuffer seekStr;
  19306. // for (unsigned i = 0; i < seekSize; i++)
  19307. // {
  19308. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  19309. // }
  19310. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  19311. #endif
  19312. }
  19313. const byte * originalRawSeek = rawSeek;
  19314. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19315. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  19316. {
  19317. checkAbort();
  19318. keyedCount++;
  19319. if (keyedCount > keyedLimit)
  19320. {
  19321. readHelper.onKeyedLimitExceeded();
  19322. break;
  19323. }
  19324. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  19325. #ifdef _DEBUG
  19326. // StringBuffer recstr;
  19327. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  19328. // for (unsigned i = 0; i < size; i++)
  19329. // {
  19330. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  19331. // }
  19332. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  19333. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  19334. assertex(!"smart seek failure");
  19335. #endif
  19336. size32_t transformedSize;
  19337. rowBuilder.ensureRow();
  19338. try
  19339. {
  19340. transformedSize = readHelper.transform(rowBuilder, keyRow);
  19341. //if the post filter causes a mismatch, and the stepping condition no longer matches
  19342. //then return a mismatch record - so the join code can start seeking on the other input.
  19343. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  19344. {
  19345. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  19346. {
  19347. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  19348. if (transformedSize != 0)
  19349. wasCompleteMatch = false;
  19350. }
  19351. }
  19352. callback.finishedRow();
  19353. }
  19354. catch (IException *E)
  19355. {
  19356. throw makeWrappedException(E);
  19357. }
  19358. if (transformedSize)
  19359. {
  19360. accepted++;
  19361. if (accepted > rowLimit)
  19362. {
  19363. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  19364. {
  19365. throwUnexpected(); // should not have used simple variant if maySkip set...
  19366. }
  19367. if (traceLevel > 4)
  19368. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19369. readHelper.onLimitExceeded();
  19370. break;
  19371. }
  19372. processed++;
  19373. #ifdef _DEBUG
  19374. // const byte *ret = (const byte *) out.get();
  19375. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  19376. // queryOutputMeta()->toXML(ret, xmlwrite);
  19377. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  19378. #endif
  19379. return rowBuilder.finalizeRowClear(transformedSize);
  19380. }
  19381. else
  19382. rejected++;
  19383. rawSeek = NULL;
  19384. }
  19385. onEOF();
  19386. return NULL;
  19387. }
  19388. virtual void reset()
  19389. {
  19390. onEOF();
  19391. if (accepted)
  19392. noteStatistic(STATS_ACCEPTED, accepted, 1);
  19393. if (rejected)
  19394. noteStatistic(STATS_REJECTED, rejected, 1);
  19395. if (variableFileName)
  19396. {
  19397. varFileInfo.clear();
  19398. translators.clear();
  19399. }
  19400. variableInfoPending = false;
  19401. CRoxieServerActivity::reset();
  19402. }
  19403. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19404. {
  19405. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19406. }
  19407. virtual IInputSteppingMeta * querySteppingMeta()
  19408. {
  19409. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19410. return &steppingMeta;
  19411. return NULL;
  19412. }
  19413. protected:
  19414. const void * createKeyedLimitOnFailRow()
  19415. {
  19416. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19417. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  19418. if (outSize)
  19419. return rowBuilder.finalizeRowClear(outSize);
  19420. return NULL;
  19421. }
  19422. };
  19423. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  19424. {
  19425. public:
  19426. Owned<IKeyArray> keySet;
  19427. Owned<TranslatorArray> translatorArray;
  19428. Owned<IDefRecordMeta> activityMeta;
  19429. RemoteActivityId remoteId;
  19430. bool isSimple;
  19431. bool isLocal;
  19432. bool maySkip;
  19433. bool sorted;
  19434. bool variableFileName;
  19435. bool enableFieldTranslation;
  19436. unsigned maxSeekLookahead;
  19437. Owned<const IResolvedFile> indexfile;
  19438. CRoxieServerSideCache *cache;
  19439. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19440. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19441. {
  19442. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  19443. unsigned flags = indexHelper->getFlags();
  19444. sorted = (flags & TIRunordered) == 0;
  19445. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19446. rtlDataAttr indexLayoutMeta;
  19447. size32_t indexLayoutSize;
  19448. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  19449. assertex(indexLayoutSize==0);
  19450. MemoryBuffer m;
  19451. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  19452. activityMeta.setown(deserializeRecordMeta(m, true));
  19453. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  19454. translatorArray.setown(new TranslatorArray);
  19455. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19456. if (!variableFileName)
  19457. {
  19458. bool isOpt = (flags & TIRoptional) != 0;
  19459. OwnedRoxieString indexName(indexHelper->getFileName());
  19460. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, queryFactory.queryWorkUnit()));
  19461. if (indexfile)
  19462. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  19463. }
  19464. isSimple = isLocal;
  19465. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  19466. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  19467. {
  19468. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  19469. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  19470. isSimple = true;
  19471. }
  19472. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  19473. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  19474. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  19475. }
  19476. ~CRoxieServerBaseIndexActivityFactory()
  19477. {
  19478. delete cache;
  19479. }
  19480. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19481. {
  19482. if (indexfile)
  19483. addXrefFileInfo(reply, indexfile);
  19484. }
  19485. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19486. {
  19487. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  19488. }
  19489. virtual IRoxieServerSideCache *queryServerSideCache() const
  19490. {
  19491. return cache;
  19492. }
  19493. virtual bool getEnableFieldTranslation() const
  19494. {
  19495. return enableFieldTranslation;
  19496. }
  19497. virtual IDefRecordMeta *queryActivityMeta() const
  19498. {
  19499. return activityMeta;
  19500. }
  19501. };
  19502. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19503. {
  19504. public:
  19505. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19506. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19507. {
  19508. }
  19509. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19510. {
  19511. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19512. return new CRoxieServerNullActivity(this, _probeManager);
  19513. else if (isSimple && !maySkip)
  19514. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19515. else
  19516. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  19517. }
  19518. };
  19519. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19520. {
  19521. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19522. }
  19523. //--------------------------------------------------------------------------------------------------------------------------
  19524. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  19525. {
  19526. bool done;
  19527. public:
  19528. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19529. : CRoxieServerActivity(_factory, _probeManager)
  19530. {
  19531. done = false;
  19532. }
  19533. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19534. {
  19535. done = false;
  19536. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19537. }
  19538. virtual bool needsAllocator() const { return true; }
  19539. virtual const void *nextInGroup()
  19540. {
  19541. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19542. if (done) return NULL;
  19543. done = true;
  19544. size32_t rowSize = meta.getFixedSize();
  19545. void * nullRow = rowAllocator->createRow();
  19546. if (rowSize == 1)
  19547. *(byte *)nullRow = 0;
  19548. else
  19549. {
  19550. assertex(rowSize == sizeof(unsigned __int64));
  19551. *(unsigned __int64 *)nullRow = 0;
  19552. }
  19553. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  19554. }
  19555. };
  19556. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  19557. {
  19558. IHThorCompoundCountExtra & countHelper;
  19559. IHThorSourceCountLimit * limitHelper;
  19560. bool done;
  19561. public:
  19562. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19563. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19564. countHelper((IHThorIndexCountArg &)basehelper),
  19565. done(false)
  19566. {
  19567. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19568. }
  19569. virtual bool needsAllocator() const { return true; }
  19570. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19571. {
  19572. done = false;
  19573. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19574. choosenLimit = countHelper.getChooseNLimit();
  19575. if (limitHelper)
  19576. {
  19577. rowLimit = limitHelper->getRowLimit();
  19578. keyedLimit = limitHelper->getKeyedLimit();
  19579. }
  19580. if (!paused)
  19581. processAllKeys();
  19582. }
  19583. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19584. {
  19585. unsigned __int64 count = 0;
  19586. if (countHelper.hasFilter())
  19587. {
  19588. while (tlk->lookup(true))
  19589. {
  19590. try
  19591. {
  19592. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  19593. callback.finishedRow();
  19594. }
  19595. catch (IException *E)
  19596. {
  19597. throw makeWrappedException(E);
  19598. }
  19599. accepted++;
  19600. if (count >= choosenLimit) // MORE - what about limit?
  19601. break;
  19602. }
  19603. }
  19604. else
  19605. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  19606. if (count)
  19607. {
  19608. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  19609. if (count > choosenLimit)
  19610. count = choosenLimit;
  19611. void * recBuffer = rowAllocator->createRow();
  19612. if (meta.getFixedSize() == 1)
  19613. *(byte *)recBuffer = (byte)count;
  19614. else
  19615. {
  19616. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19617. *(unsigned __int64 *)recBuffer = count;
  19618. }
  19619. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  19620. result->append(recBuffer);
  19621. remote.injectResult(result.getClear());
  19622. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  19623. if (count >= choosenLimit)
  19624. return true;
  19625. }
  19626. return false;
  19627. }
  19628. virtual void onLimitExceeded(bool isKeyed)
  19629. {
  19630. if (traceLevel > 4)
  19631. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19632. if (isKeyed)
  19633. {
  19634. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19635. {
  19636. if (ctx->queryDebugContext())
  19637. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19638. throw makeLimitSkipException(true);
  19639. }
  19640. else
  19641. {
  19642. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  19643. limitHelper->onKeyedLimitExceeded();
  19644. }
  19645. }
  19646. else
  19647. {
  19648. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19649. {
  19650. if (ctx->queryDebugContext())
  19651. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19652. throw makeLimitSkipException(false);
  19653. }
  19654. else
  19655. {
  19656. assertex(limitHelper);
  19657. limitHelper->onLimitExceeded();
  19658. }
  19659. }
  19660. }
  19661. virtual const void *createLimitFailRow(bool isKeyed)
  19662. {
  19663. throwUnexpected();
  19664. }
  19665. virtual const void *nextInGroup()
  19666. {
  19667. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19668. if (done) return NULL;
  19669. done = true;
  19670. unsigned __int64 totalCount = 0;
  19671. bool hasLimit = rowLimit != (unsigned __int64) -1;
  19672. try
  19673. {
  19674. loop
  19675. {
  19676. const void * next = remote.nextInGroup();
  19677. if (!next)
  19678. break;
  19679. if (meta.getFixedSize() == 1)
  19680. totalCount += *(byte *)next;
  19681. else
  19682. totalCount += *(unsigned __int64 *) next;
  19683. ReleaseRoxieRow(next);
  19684. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  19685. break;
  19686. }
  19687. if (totalCount > rowLimit)
  19688. {
  19689. unsigned flags = indexHelper.getFlags();
  19690. if (flags & TIRlimitskips)
  19691. totalCount = 0;
  19692. else if (flags & TIRlimitcreates)
  19693. totalCount = 1;
  19694. else
  19695. {
  19696. assertex(limitHelper);
  19697. limitHelper->onLimitExceeded();
  19698. }
  19699. }
  19700. else if (totalCount > choosenLimit)
  19701. totalCount = choosenLimit;
  19702. }
  19703. catch (IException *E)
  19704. {
  19705. if (QUERYINTERFACE(E, LimitSkipException))
  19706. {
  19707. totalCount = 0;
  19708. unsigned flags = indexHelper.getFlags();
  19709. if (E->errorCode() == KeyedLimitSkipErrorCode)
  19710. {
  19711. if (flags & TIRkeyedlimitcreates)
  19712. totalCount++;
  19713. }
  19714. else
  19715. {
  19716. if (flags & TIRlimitcreates)
  19717. totalCount++;
  19718. }
  19719. if (totalCount > choosenLimit)
  19720. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  19721. E->Release();
  19722. }
  19723. else
  19724. throw ;
  19725. }
  19726. void * result = rowAllocator->createRow();
  19727. if (meta.getFixedSize() == 1)
  19728. *(byte *)result = (byte)totalCount;
  19729. else
  19730. {
  19731. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19732. *(unsigned __int64 *)result = totalCount;
  19733. }
  19734. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  19735. }
  19736. };
  19737. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19738. {
  19739. public:
  19740. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19741. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19742. {
  19743. }
  19744. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19745. {
  19746. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19747. return new CRoxieServerNullCountActivity(this, _probeManager);
  19748. // else if (isSimple)
  19749. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  19750. else
  19751. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19752. }
  19753. };
  19754. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19755. {
  19756. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19757. }
  19758. //--------------------------------------------------------------------------------------------------------------------------
  19759. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  19760. {
  19761. IHThorIndexAggregateArg &aggregateHelper;
  19762. bool done;
  19763. public:
  19764. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19765. : CRoxieServerActivity(_factory, _probeManager),
  19766. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  19767. {
  19768. done = false;
  19769. }
  19770. virtual bool needsAllocator() const { return true; }
  19771. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19772. {
  19773. done = false;
  19774. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19775. }
  19776. virtual const void *nextInGroup()
  19777. {
  19778. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19779. if (done) return NULL;
  19780. done = true;
  19781. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19782. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  19783. return rowBuilder.finalizeRowClear(thisSize);
  19784. }
  19785. };
  19786. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  19787. {
  19788. IHThorCompoundAggregateExtra & aggregateHelper;
  19789. bool done;
  19790. public:
  19791. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19792. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19793. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19794. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  19795. done(false)
  19796. {
  19797. }
  19798. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19799. {
  19800. done = false;
  19801. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19802. if (!paused)
  19803. processAllKeys();
  19804. }
  19805. virtual bool needsAllocator() const { return true; }
  19806. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19807. {
  19808. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19809. while (tlk->lookup(true))
  19810. {
  19811. if (!rowBuilder.exists())
  19812. {
  19813. rowBuilder.ensureRow();
  19814. aggregateHelper.clearAggregate(rowBuilder);
  19815. }
  19816. try
  19817. {
  19818. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  19819. callback.finishedRow();
  19820. }
  19821. catch (IException *E)
  19822. {
  19823. throw makeWrappedException(E);
  19824. }
  19825. accepted++;
  19826. }
  19827. if (aggregateHelper.processedAnyRows())
  19828. {
  19829. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  19830. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  19831. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  19832. result->append(recBuffer);
  19833. remote.injectResult(result.getClear());
  19834. }
  19835. return false;
  19836. }
  19837. virtual void onLimitExceeded(bool isKeyed)
  19838. {
  19839. if (traceLevel > 4)
  19840. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19841. throwUnexpected();
  19842. }
  19843. virtual const void *createLimitFailRow(bool isKeyed)
  19844. {
  19845. throwUnexpected();
  19846. }
  19847. const void * gatherMerged()
  19848. {
  19849. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19850. const void * firstRow = remote.nextInGroup();
  19851. size32_t finalSize = 0;
  19852. if (!firstRow)
  19853. {
  19854. rowBuilder.ensureRow();
  19855. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19856. }
  19857. else
  19858. {
  19859. // NOTE need to clone this because going to modify below, could special case 1 row only
  19860. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19861. ReleaseRoxieRow(firstRow);
  19862. }
  19863. loop
  19864. {
  19865. const void * next = remote.nextInGroup();
  19866. if (!next)
  19867. break;
  19868. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19869. ReleaseRoxieRow(next);
  19870. }
  19871. return rowBuilder.finalizeRowClear(finalSize);
  19872. }
  19873. virtual const void *nextInGroup()
  19874. {
  19875. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19876. if (done) return NULL;
  19877. const void * ret = gatherMerged();
  19878. done = true;
  19879. return ret;
  19880. }
  19881. };
  19882. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19883. {
  19884. public:
  19885. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19886. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19887. {
  19888. }
  19889. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19890. {
  19891. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19892. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  19893. // else if (isSimple)
  19894. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  19895. else
  19896. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19897. }
  19898. };
  19899. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19900. {
  19901. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19902. }
  19903. //--------------------------------------------------------------------------------------------------------------------------
  19904. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  19905. {
  19906. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  19907. RowAggregator singleAggregator;
  19908. RowAggregator resultAggregator;
  19909. unsigned groupSegCount;
  19910. bool gathered;
  19911. bool eof;
  19912. public:
  19913. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19914. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19915. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19916. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  19917. singleAggregator(aggregateHelper, aggregateHelper),
  19918. resultAggregator(aggregateHelper, aggregateHelper),
  19919. gathered(false), eof(true)
  19920. {
  19921. groupSegCount = 0;
  19922. }
  19923. IMPLEMENT_IINTERFACE
  19924. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19925. {
  19926. eof = false;
  19927. gathered= false;
  19928. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19929. groupSegCount = 0;
  19930. if (!paused)
  19931. processAllKeys();
  19932. resultAggregator.start(rowAllocator);
  19933. }
  19934. virtual bool needsAllocator() const { return true; }
  19935. virtual void reset()
  19936. {
  19937. resultAggregator.reset();
  19938. CRoxieServerIndexActivity::reset();
  19939. }
  19940. virtual void processRow(const void * next)
  19941. {
  19942. singleAggregator.addRow(next);
  19943. }
  19944. virtual void createSegmentMonitors(IKeyManager *key)
  19945. {
  19946. unsigned groupSegSize;
  19947. ThorActivityKind kind = factory->getKind();
  19948. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  19949. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  19950. else
  19951. groupSegSize = 0;
  19952. if (groupSegSize)
  19953. {
  19954. key->setMergeBarrier(groupSegSize);
  19955. CRoxieServerIndexActivity::createSegmentMonitors(key);
  19956. unsigned numSegs = tlk->ordinality();
  19957. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  19958. {
  19959. IKeySegmentMonitor *seg = tlk->item(segNo);
  19960. if (seg->getOffset()+seg->getSize()==groupSegSize)
  19961. {
  19962. groupSegCount = segNo+1;
  19963. break;
  19964. }
  19965. }
  19966. assertex(groupSegCount);
  19967. }
  19968. else
  19969. CRoxieServerIndexActivity::createSegmentMonitors(key);
  19970. }
  19971. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19972. {
  19973. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  19974. singleAggregator.start(rowAllocator);
  19975. ThorActivityKind kind = factory->getKind();
  19976. while (tlk->lookup(true))
  19977. {
  19978. try
  19979. {
  19980. if (groupSegCount && !trans)
  19981. {
  19982. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  19983. callback.finishedRow();
  19984. if (kind==TAKindexgroupcount)
  19985. {
  19986. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  19987. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  19988. }
  19989. if (!tlk->nextRange(groupSegCount))
  19990. break;
  19991. }
  19992. else
  19993. {
  19994. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  19995. callback.finishedRow();
  19996. }
  19997. }
  19998. catch (IException *E)
  19999. {
  20000. throw makeWrappedException(E);
  20001. }
  20002. accepted++;
  20003. }
  20004. loop
  20005. {
  20006. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20007. if (!next)
  20008. break;
  20009. size32_t size = next->querySize();
  20010. result->append(next->finalizeRowClear());
  20011. }
  20012. remote.injectResult(result.getClear());
  20013. singleAggregator.reset();
  20014. return false;
  20015. }
  20016. virtual void onLimitExceeded(bool isKeyed)
  20017. {
  20018. if (traceLevel > 4)
  20019. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20020. throwUnexpected();
  20021. }
  20022. virtual const void *createLimitFailRow(bool isKeyed)
  20023. {
  20024. throwUnexpected();
  20025. }
  20026. void gatherMerged()
  20027. {
  20028. gathered = true;
  20029. loop
  20030. {
  20031. const void * next = remote.nextInGroup();
  20032. if (!next)
  20033. break;
  20034. resultAggregator.mergeElement(next);
  20035. ReleaseRoxieRow(next);
  20036. }
  20037. }
  20038. virtual const void *nextInGroup()
  20039. {
  20040. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20041. if (eof)
  20042. return NULL;
  20043. if (!gathered)
  20044. gatherMerged();
  20045. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20046. if (next)
  20047. {
  20048. processed++;
  20049. return next->finalizeRowClear();
  20050. }
  20051. eof = true;
  20052. return NULL;
  20053. }
  20054. };
  20055. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20056. {
  20057. public:
  20058. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20059. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20060. {
  20061. }
  20062. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20063. {
  20064. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20065. return new CRoxieServerNullActivity(this, _probeManager);
  20066. // else if (isSimple)
  20067. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20068. else
  20069. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20070. }
  20071. };
  20072. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20073. {
  20074. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20075. }
  20076. //--------------------------------------------------------------------------------------------------------------------------
  20077. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20078. {
  20079. IHThorCompoundNormalizeExtra & readHelper;
  20080. public:
  20081. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20082. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20083. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20084. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20085. {
  20086. }
  20087. virtual bool needsAllocator() const { return true; }
  20088. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20089. {
  20090. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20091. rowLimit = readHelper.getRowLimit();
  20092. keyedLimit = readHelper.getKeyedLimit();
  20093. if (!paused)
  20094. processAllKeys();
  20095. }
  20096. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20097. {
  20098. unsigned keyedCount = 0;
  20099. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20100. while (tlk->lookup(true))
  20101. {
  20102. keyedCount++;
  20103. if (keyedCount > keyedLimit)
  20104. {
  20105. if (traceLevel > 4)
  20106. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20107. onLimitExceeded(true);
  20108. break;
  20109. }
  20110. size32_t transformedSize;
  20111. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20112. {
  20113. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20114. do
  20115. {
  20116. rowBuilder.ensureRow();
  20117. try
  20118. {
  20119. transformedSize = readHelper.transform(rowBuilder);
  20120. }
  20121. catch (IException *E)
  20122. {
  20123. throw makeWrappedException(E);
  20124. }
  20125. if (transformedSize)
  20126. {
  20127. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20128. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20129. accepted++;
  20130. }
  20131. else
  20132. rejected++;
  20133. } while (readHelper.next());
  20134. remote.injectResult(result.getClear());
  20135. callback.finishedRow();
  20136. }
  20137. }
  20138. return false;
  20139. }
  20140. virtual void onLimitExceeded(bool isKeyed)
  20141. {
  20142. if (traceLevel > 4)
  20143. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20144. if (isKeyed)
  20145. {
  20146. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20147. {
  20148. if (ctx->queryDebugContext())
  20149. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20150. throw makeLimitSkipException(true);
  20151. }
  20152. else
  20153. readHelper.onKeyedLimitExceeded();
  20154. }
  20155. else
  20156. {
  20157. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  20158. {
  20159. if (ctx->queryDebugContext())
  20160. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20161. throw makeLimitSkipException(false);
  20162. }
  20163. else
  20164. readHelper.onLimitExceeded();
  20165. }
  20166. }
  20167. virtual const void *createLimitFailRow(bool isKeyed)
  20168. {
  20169. UNIMPLEMENTED;
  20170. }
  20171. };
  20172. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20173. {
  20174. public:
  20175. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20176. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20177. {
  20178. }
  20179. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20180. {
  20181. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20182. return new CRoxieServerNullActivity(this, _probeManager);
  20183. else
  20184. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  20185. }
  20186. };
  20187. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20188. {
  20189. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20190. }
  20191. //=================================================================================
  20192. class CRoxieServerCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20193. {
  20194. unsigned __int64 answer;
  20195. public:
  20196. CRoxieServerCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned __int64 _answer)
  20197. : CRoxieServerActivity(_factory, _probeManager),
  20198. answer(_answer)
  20199. {
  20200. }
  20201. virtual const void *nextInGroup()
  20202. {
  20203. throwUnexpected();
  20204. }
  20205. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20206. {
  20207. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20208. }
  20209. virtual __int64 evaluate()
  20210. {
  20211. return answer;
  20212. }
  20213. virtual void onLimitExceeded(bool isKeyed)
  20214. {
  20215. if (traceLevel > 4)
  20216. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20217. throwUnexpected();
  20218. }
  20219. virtual const void *createLimitFailRow(bool isKeyed)
  20220. {
  20221. throwUnexpected();
  20222. }
  20223. };
  20224. class CRoxieServerVariableCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20225. {
  20226. public:
  20227. CRoxieServerVariableCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20228. : CRoxieServerActivity(_factory, _probeManager)
  20229. {
  20230. }
  20231. virtual const void *nextInGroup()
  20232. {
  20233. throwUnexpected();
  20234. }
  20235. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20236. {
  20237. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20238. }
  20239. virtual __int64 evaluate()
  20240. {
  20241. IHThorCountFileArg &helper = (IHThorCountFileArg &) basehelper;
  20242. bool isOpt = (helper.getFlags() & TDRoptional) != 0;
  20243. unsigned recsize = helper.queryRecordSize()->getFixedSize();
  20244. assertex(recsize);
  20245. OwnedRoxieString fname(helper.getFileName());
  20246. Owned<const IResolvedFile> varFileInfo = resolveLFN(fname, isOpt);
  20247. return varFileInfo->getFileSize() / recsize;
  20248. }
  20249. virtual void onLimitExceeded(bool isKeyed)
  20250. {
  20251. if (traceLevel > 4)
  20252. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20253. throwUnexpected();
  20254. }
  20255. virtual const void *createLimitFailRow(bool isKeyed)
  20256. {
  20257. throwUnexpected();
  20258. }
  20259. };
  20260. class CRoxieServerCountDiskActivityFactory : public CRoxieServerActivityFactory
  20261. {
  20262. public:
  20263. unsigned __int64 answer;
  20264. bool variableFileName;
  20265. Owned<const IResolvedFile> datafile;
  20266. CRoxieServerCountDiskActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20267. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20268. {
  20269. Owned<IHThorCountFileArg> helper = (IHThorCountFileArg *) helperFactory();
  20270. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20271. assertex(helper->queryRecordSize()->isFixedSize());
  20272. if (!variableFileName)
  20273. {
  20274. unsigned recsize = helper->queryRecordSize()->getFixedSize();
  20275. assertex(recsize);
  20276. OwnedRoxieString fileName(helper->getFileName());
  20277. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20278. datafile.setown(queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, queryFactory.queryWorkUnit()));
  20279. offset_t filesize = datafile ? datafile->getFileSize() : 0;
  20280. if (filesize % recsize != 0)
  20281. throw MakeStringException(ROXIE_MISMATCH, "Record size mismatch for file %s - %"I64F"d is not a multiple of fixed record size %d", fileName.get(), filesize, recsize);
  20282. answer = filesize / recsize;
  20283. }
  20284. else
  20285. answer = 0;
  20286. }
  20287. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20288. {
  20289. if (datafile)
  20290. addXrefFileInfo(reply, datafile);
  20291. }
  20292. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  20293. {
  20294. arg.Release();
  20295. if (variableFileName)
  20296. return new CRoxieServerVariableCountDiskActivity(this, _probeManager);
  20297. else
  20298. return new CRoxieServerCountDiskActivity(this, _probeManager, answer);
  20299. }
  20300. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20301. {
  20302. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for CountDisk activity");
  20303. }
  20304. virtual bool isFunction() const
  20305. {
  20306. return true;
  20307. }
  20308. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20309. {
  20310. return NULL;
  20311. }
  20312. };
  20313. IRoxieServerActivityFactory *createRoxieServerDiskCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20314. {
  20315. return new CRoxieServerCountDiskActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  20316. }
  20317. //=================================================================================
  20318. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  20319. {
  20320. IHThorFetchBaseArg &helper;
  20321. IHThorFetchContext * fetchContext;
  20322. Linked<IFilePartMap> map;
  20323. CRemoteResultAdaptor remote;
  20324. RecordPullerThread puller;
  20325. bool needsRHS;
  20326. bool variableFileName;
  20327. bool isOpt;
  20328. Owned<const IResolvedFile> varFileInfo;
  20329. public:
  20330. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  20331. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  20332. {
  20333. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  20334. needsRHS = helper.transformNeedsRhs();
  20335. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20336. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  20337. }
  20338. virtual const IResolvedFile *queryVarFileInfo() const
  20339. {
  20340. return varFileInfo;
  20341. }
  20342. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  20343. {
  20344. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  20345. remote.onCreate(this, this, _ctx, _colocalParent);
  20346. }
  20347. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20348. {
  20349. if (idx)
  20350. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  20351. puller.setInput(this, _in);
  20352. }
  20353. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20354. {
  20355. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20356. remote.onStart(parentExtractSize, parentExtract);
  20357. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  20358. if (variableFileName)
  20359. {
  20360. OwnedRoxieString fname(fetchContext->getFileName());
  20361. varFileInfo.setown(resolveLFN(fname, isOpt));
  20362. if (varFileInfo)
  20363. map.setown(varFileInfo->getFileMap());
  20364. }
  20365. puller.start(parentExtractSize, parentExtract, paused, ctx->fetchPreload(), false, ctx);
  20366. }
  20367. virtual void stop(bool aborting)
  20368. {
  20369. // Called from remote, so no need to call back to it....
  20370. puller.stop(aborting);
  20371. CRoxieServerActivity::stop(aborting);
  20372. }
  20373. virtual void reset()
  20374. {
  20375. processed = remote.processed;
  20376. remote.processed = 0;
  20377. puller.reset();
  20378. if (variableFileName)
  20379. {
  20380. varFileInfo.clear();
  20381. map.clear();
  20382. }
  20383. CRoxieServerActivity::reset();
  20384. }
  20385. virtual IRoxieInput *queryOutput(unsigned idx)
  20386. {
  20387. if (idx==(unsigned)-1)
  20388. idx = 0;
  20389. return idx ? NULL : &remote;
  20390. }
  20391. virtual void processRow(const void *row)
  20392. {
  20393. // called from puller thread
  20394. offset_t rp = fetchContext->extractPosition(row);
  20395. unsigned partNo;
  20396. if (isLocalFpos(rp))
  20397. partNo = getLocalFposPart(rp) + 1;
  20398. else
  20399. partNo = map->mapOffset(rp);
  20400. if (needsRHS)
  20401. {
  20402. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  20403. RtlDynamicRowBuilder rb(extractAllocator, true);
  20404. unsigned rhsSize = helper.extractJoinFields(rb, row);
  20405. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  20406. *(offset_t *) block = rp;
  20407. block += sizeof(rp);
  20408. *(unsigned *) block = rhsSize;
  20409. block += sizeof(rhsSize);
  20410. memcpy(block, rb.row(), rhsSize);
  20411. }
  20412. else
  20413. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  20414. ReleaseRoxieRow(row);
  20415. }
  20416. void processEOG()
  20417. {
  20418. #ifdef FETCH_PRESERVES_GROUPING
  20419. UNIMPLEMENTED;
  20420. #endif
  20421. // else discard is correct
  20422. }
  20423. void processGroup(const ConstPointerArray &)
  20424. {
  20425. throwUnexpected();
  20426. }
  20427. void processDone()
  20428. {
  20429. // called from puller thread
  20430. remote.flush();
  20431. remote.senddone();
  20432. }
  20433. virtual bool fireException(IException *e)
  20434. {
  20435. return remote.fireException(e);
  20436. }
  20437. virtual void onLimitExceeded(bool isKeyed)
  20438. {
  20439. if (traceLevel > 4)
  20440. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20441. if (isKeyed)
  20442. throwUnexpected();
  20443. helper.onLimitExceeded();
  20444. }
  20445. virtual const void *createLimitFailRow(bool isKeyed)
  20446. {
  20447. UNIMPLEMENTED;
  20448. }
  20449. virtual const void *nextInGroup()
  20450. {
  20451. throwUnexpected(); // I am nobody's input
  20452. }
  20453. };
  20454. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  20455. {
  20456. RemoteActivityId remoteId;
  20457. Owned<IFilePartMap> map;
  20458. bool variableFileName;
  20459. Owned<const IResolvedFile> datafile;
  20460. public:
  20461. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20462. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20463. {
  20464. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  20465. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  20466. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20467. if (!variableFileName)
  20468. {
  20469. OwnedRoxieString fname(fetchContext->getFileName());
  20470. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  20471. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  20472. true,
  20473. _queryFactory.queryWorkUnit()));
  20474. if (datafile)
  20475. map.setown(datafile->getFileMap());
  20476. }
  20477. }
  20478. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20479. {
  20480. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  20481. }
  20482. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20483. {
  20484. if (datafile)
  20485. addXrefFileInfo(reply, datafile);
  20486. }
  20487. };
  20488. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20489. {
  20490. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20491. }
  20492. // MORE - is there any point keeping this now?
  20493. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  20494. {
  20495. public:
  20496. Owned<const IResolvedFile> indexfile;
  20497. Owned<const IResolvedFile> datafile;
  20498. Owned<IKeyArray> keySet;
  20499. Owned<IFileIOArray> files;
  20500. Owned<IFilePartMap> map;
  20501. TranslatorArray layoutTranslators;
  20502. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20503. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20504. {
  20505. try // does not want any missing file errors to be fatal, or throw traps - just log it
  20506. {
  20507. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  20508. return; // ignore 'spills'
  20509. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20510. bool isOpt = _graphNode.getPropBool("att[@name='_isOpt']/@value") || pretendAllOpt;
  20511. if (queryNodeIndexName(_graphNode))
  20512. {
  20513. indexfile.setown(queryFactory.queryPackage().lookupFileName(queryNodeIndexName(_graphNode), isOpt, true, queryFactory.queryWorkUnit()));
  20514. if (indexfile)
  20515. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  20516. }
  20517. if (queryNodeFileName(_graphNode))
  20518. {
  20519. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isOpt, true, queryFactory.queryWorkUnit()));
  20520. if (datafile)
  20521. {
  20522. if (isLocal)
  20523. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  20524. else
  20525. map.setown(datafile->getFileMap());
  20526. }
  20527. }
  20528. }
  20529. catch(IException *E)
  20530. {
  20531. StringBuffer errors;
  20532. E->errorMessage(errors);
  20533. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  20534. E->Release();
  20535. }
  20536. }
  20537. 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__); }
  20538. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20539. {
  20540. if (datafile)
  20541. addXrefFileInfo(reply, datafile);
  20542. if (indexfile)
  20543. addXrefFileInfo(reply, indexfile);
  20544. }
  20545. };
  20546. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20547. {
  20548. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  20549. }
  20550. //=====================================================================================================
  20551. // Keyed joins...
  20552. //
  20553. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  20554. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  20555. // 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
  20556. // the transform and returns rows that are created.
  20557. // 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)
  20558. //
  20559. //=====================================================================================================
  20560. class CJoinGroup;
  20561. interface IJoinProcessor
  20562. {
  20563. virtual void processEOG() = 0;
  20564. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  20565. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  20566. virtual bool fireException(IException *E) = 0;
  20567. virtual void processCompletedGroups() = 0;
  20568. };
  20569. //------------------------------------------------------------------------------------------------------
  20570. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  20571. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  20572. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  20573. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  20574. // per-query limits etc (Note that the pointer array block is not though).
  20575. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  20576. //
  20577. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  20578. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  20579. // initial count when created.
  20580. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  20581. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  20582. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  20583. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  20584. // remaining reference and the JoinGroup will be processed and destroyed.
  20585. //
  20586. //------------------------------------------------------------------------------------------------------
  20587. class CJoinGroup : public CInterface, implements IInterface
  20588. {
  20589. protected:
  20590. const void *left; // LHS row
  20591. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  20592. atomic_t endMarkersPending; // How many slave responses still waiting for
  20593. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  20594. unsigned lastPartNo;
  20595. unsigned pos;
  20596. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  20597. public:
  20598. #undef new
  20599. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  20600. {
  20601. return a->allocate(size, activityId);
  20602. }
  20603. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  20604. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  20605. #endif
  20606. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  20607. {
  20608. ReleaseRoxieRow(ptr);
  20609. }
  20610. void operator delete(void *ptr)
  20611. {
  20612. ReleaseRoxieRow(ptr);
  20613. }
  20614. public:
  20615. IMPLEMENT_IINTERFACE;
  20616. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  20617. {
  20618. #ifdef TRACE_JOINGROUPS
  20619. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  20620. #endif
  20621. candidates = 0;
  20622. lastPartNo = 0;
  20623. pos = 0;
  20624. left = _left;
  20625. groupStart = _groupStart;
  20626. if (_groupStart)
  20627. {
  20628. atomic_inc(&_groupStart->endMarkersPending);
  20629. }
  20630. atomic_set(&endMarkersPending, 1);
  20631. }
  20632. ~CJoinGroup()
  20633. {
  20634. #ifdef TRACE_JOINGROUPS
  20635. DBGLOG("Destroying joinGroup %p", this);
  20636. #endif
  20637. if (left)
  20638. {
  20639. ReleaseRoxieRow(left);
  20640. ForEachItemIn(idx, rows)
  20641. ReleaseRoxieRow(rows.item(idx));
  20642. rows.kill();
  20643. }
  20644. }
  20645. inline bool isHeadRecord() const
  20646. {
  20647. return left==NULL;
  20648. }
  20649. inline bool complete() const
  20650. {
  20651. return atomic_read(&endMarkersPending) == 0;
  20652. }
  20653. #ifdef TRACE_JOINGROUPS
  20654. inline void notePending(unsigned lineNo)
  20655. #else
  20656. inline void notePending()
  20657. #endif
  20658. {
  20659. assert(!complete());
  20660. atomic_inc(&endMarkersPending);
  20661. #ifdef TRACE_JOINGROUPS
  20662. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  20663. #endif
  20664. }
  20665. inline bool inGroup(CJoinGroup *leader) const
  20666. {
  20667. return groupStart==leader;
  20668. }
  20669. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  20670. {
  20671. // Single threaded by now
  20672. assert(complete());
  20673. return rows.item(idx);
  20674. }
  20675. #ifdef TRACE_JOINGROUPS
  20676. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  20677. #else
  20678. bool noteEndReceived(unsigned candidateCount)
  20679. #endif
  20680. {
  20681. assert(!complete());
  20682. if (candidateCount)
  20683. {
  20684. candidates += candidateCount;
  20685. }
  20686. #ifdef TRACE_JOINGROUPS
  20687. 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);
  20688. #endif
  20689. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  20690. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  20691. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  20692. CJoinGroup *localGroupStart = groupStart;
  20693. if (atomic_dec_and_test(&endMarkersPending))
  20694. {
  20695. if (localGroupStart)
  20696. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  20697. else
  20698. return true;
  20699. }
  20700. else
  20701. return false;
  20702. }
  20703. inline const void *queryLeft() const
  20704. {
  20705. return left;
  20706. }
  20707. void addRightMatch(KeyedJoinHeader *right)
  20708. {
  20709. assert(!complete());
  20710. unsigned short partNo = right->partNo;
  20711. if (partNo != lastPartNo)
  20712. {
  20713. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  20714. if (partNo > lastPartNo)
  20715. pos = rows.length();
  20716. while (pos>0)
  20717. {
  20718. if (rows.item(pos-1)->partNo <= partNo)
  20719. break;
  20720. pos--;
  20721. }
  20722. lastPartNo = partNo;
  20723. }
  20724. rows.add(right, pos);
  20725. pos++;
  20726. }
  20727. inline unsigned rowsSeen() const
  20728. {
  20729. assert(complete());
  20730. return rows.length();
  20731. }
  20732. inline unsigned candidateCount() const
  20733. {
  20734. assert(complete());
  20735. return candidates;
  20736. }
  20737. };
  20738. #ifdef TRACE_JOINGROUPS
  20739. #define notePending() notePending(__LINE__)
  20740. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  20741. #endif
  20742. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  20743. {
  20744. private:
  20745. SafeQueueOf<const void, true> ready;
  20746. public:
  20747. IHThorKeyedJoinArg &helper;
  20748. unsigned joinProcessed;
  20749. bool isFullKey;
  20750. bool eof;
  20751. bool isSimple;
  20752. bool allPulled;
  20753. unsigned __int64 totalCycles;
  20754. unsigned activityId;
  20755. RecordPullerThread &puller;
  20756. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  20757. Owned<IEngineRowAllocator> ccdRecordAllocator;
  20758. IJoinProcessor &processor;
  20759. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  20760. RecordPullerThread &_puller, IJoinProcessor &_processor)
  20761. : helper(_helper),
  20762. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  20763. isFullKey(_isFullKey),
  20764. isSimple(_isSimple),
  20765. puller(_puller),
  20766. processor(_processor),
  20767. activityId(_activity.queryId())
  20768. {
  20769. joinProcessed = 0;
  20770. totalCycles = 0;
  20771. allPulled = false;
  20772. eof = false;
  20773. }
  20774. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  20775. {
  20776. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  20777. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  20778. }
  20779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20780. {
  20781. eof = false;
  20782. joinProcessed = 0;
  20783. totalCycles = 0;
  20784. allPulled = false;
  20785. assertex(ready.ordinality()==0);
  20786. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  20787. }
  20788. virtual void reset()
  20789. {
  20790. CRemoteResultAdaptor::reset();
  20791. while (ready.ordinality())
  20792. {
  20793. const void *goer = ready.dequeue();
  20794. if (goer)
  20795. ReleaseRoxieRow(goer);
  20796. }
  20797. while (injected.ordinality())
  20798. {
  20799. const void *goer = injected.dequeue();
  20800. if (goer)
  20801. ReleaseRoxieRow(goer);
  20802. }
  20803. }
  20804. inline void addResult(const void *row)
  20805. {
  20806. ready.enqueue(row);
  20807. }
  20808. virtual unsigned __int64 queryTotalCycles() const
  20809. {
  20810. return totalCycles;
  20811. }
  20812. virtual IOutputMetaData * queryOutputMeta() const
  20813. {
  20814. return owner->queryOutputMeta();
  20815. }
  20816. virtual const void *nextInGroup()
  20817. {
  20818. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20819. loop
  20820. {
  20821. if (eof)
  20822. return NULL;
  20823. processSlaveResults();
  20824. if (ready.ordinality())
  20825. {
  20826. const void *result = ready.dequeue();
  20827. if (result)
  20828. joinProcessed++;
  20829. return result;
  20830. }
  20831. else
  20832. eof = true;
  20833. }
  20834. }
  20835. private:
  20836. void processSlaveResults()
  20837. {
  20838. while (!ready.ordinality())
  20839. {
  20840. KeyedJoinHeader *fetchedData;
  20841. if (isSimple)
  20842. {
  20843. while (!allPulled && !injected.ordinality())
  20844. {
  20845. if (!puller.pullRecords(1))
  20846. {
  20847. puller.done();
  20848. allPulled = true;
  20849. }
  20850. }
  20851. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  20852. }
  20853. else
  20854. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  20855. if (fetchedData)
  20856. {
  20857. CJoinGroup *thisGroup = fetchedData->thisGroup;
  20858. if (fetchedData->partNo == (unsigned short) -1)
  20859. {
  20860. #ifdef TRACE_JOINGROUPS
  20861. CTXLOG("Got end for group %p", thisGroup);
  20862. #endif
  20863. unsigned candidateCount = (unsigned) fetchedData->fpos;
  20864. ReleaseRoxieRow(fetchedData);
  20865. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  20866. }
  20867. else
  20868. {
  20869. #ifdef TRACE_JOINGROUPS
  20870. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  20871. #endif
  20872. thisGroup->addRightMatch(fetchedData);
  20873. if (isFullKey)
  20874. {
  20875. #ifdef TRACE_JOINGROUPS
  20876. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  20877. #endif
  20878. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  20879. }
  20880. }
  20881. }
  20882. else
  20883. break;
  20884. }
  20885. }
  20886. };
  20887. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  20888. {
  20889. IHThorKeyedJoinArg &helper;
  20890. Owned<IKeyManager> tlk;
  20891. Linked<IKeyArray> keySet;
  20892. Linked<TranslatorArray> translators;
  20893. CRemoteResultAdaptor remote;
  20894. RecordPullerThread puller;
  20895. IOutputMetaData *indexReadMeta;
  20896. IJoinProcessor *joinHandler;
  20897. bool variableIndexFileName;
  20898. bool indexReadInputRecordVariable;
  20899. bool isLocal;
  20900. Owned<IEngineRowAllocator> indexReadAllocator;
  20901. Owned<const IResolvedFile> varFileInfo;
  20902. IRoxieInput *indexReadInput;
  20903. IIndexReadActivityInfo *rootIndex;
  20904. public:
  20905. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  20906. : CRoxieServerActivity(_factory, _probeManager),
  20907. helper((IHThorKeyedJoinArg &)basehelper),
  20908. tlk(createKeyManager(NULL, 0, this)),
  20909. translators(_translators),
  20910. keySet(_keySet),
  20911. remote(_remoteId, 0, helper, *this, true, true),
  20912. indexReadMeta(_indexReadMeta),
  20913. joinHandler(_joinHandler),
  20914. puller(false),
  20915. isLocal(_isLocal)
  20916. {
  20917. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  20918. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  20919. indexReadInput = NULL;
  20920. rootIndex = NULL;
  20921. }
  20922. virtual const IResolvedFile *queryVarFileInfo() const
  20923. {
  20924. return varFileInfo;
  20925. }
  20926. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  20927. {
  20928. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  20929. remote.onCreate(this, this, _ctx, _colocalParent);
  20930. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  20931. }
  20932. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20933. {
  20934. if (!idx)
  20935. puller.setInput(this, _in);
  20936. else if (idx==1)
  20937. indexReadInput = _in;
  20938. else
  20939. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  20940. }
  20941. virtual void serializeExtra(MemoryBuffer &out)
  20942. {
  20943. if (helper.getJoinFlags() & JFindexfromactivity)
  20944. {
  20945. assertex(rootIndex);
  20946. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  20947. indexId.serialize(out);
  20948. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  20949. MemoryBuffer tmp;
  20950. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  20951. if (rootIndex->queryActivity()->queryVarFileInfo())
  20952. {
  20953. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  20954. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  20955. }
  20956. unsigned ctxlen = tmp.length();
  20957. out.append(ctxlen).append(tmp);
  20958. }
  20959. }
  20960. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20961. {
  20962. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20963. if (indexReadInput)
  20964. {
  20965. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  20966. rootIndex = indexReadInput->queryIndexReadActivity();
  20967. if (!rootIndex)
  20968. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  20969. }
  20970. remote.onStart(parentExtractSize, parentExtract);
  20971. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  20972. if (rootIndex)
  20973. {
  20974. varFileInfo.setown(rootIndex->getVarFileInfo());
  20975. translators.setown(rootIndex->getTranslators());
  20976. keySet.setown(rootIndex->getKeySet());
  20977. }
  20978. else if (variableIndexFileName)
  20979. {
  20980. OwnedRoxieString indexFileName(helper.getIndexFileName());
  20981. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  20982. if (varFileInfo)
  20983. {
  20984. translators.setown(new TranslatorArray);
  20985. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation())); // MORE - isLocal?
  20986. }
  20987. }
  20988. puller.start(parentExtractSize, parentExtract, paused, ctx->fullKeyedJoinPreload(), false, ctx);
  20989. }
  20990. virtual void stop(bool aborting)
  20991. {
  20992. puller.stop(aborting);
  20993. CRoxieServerActivity::stop(aborting);
  20994. }
  20995. virtual void reset()
  20996. {
  20997. CRoxieServerActivity::reset();
  20998. puller.reset();
  20999. if (varFileInfo)
  21000. {
  21001. keySet.clear();
  21002. varFileInfo.clear();
  21003. }
  21004. }
  21005. virtual IRoxieInput *queryOutput(unsigned idx)
  21006. {
  21007. if (idx==(unsigned)-1)
  21008. idx = 0;
  21009. return idx ? NULL : &remote;
  21010. }
  21011. virtual void processRow(const void *row)
  21012. {
  21013. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21014. // called from front puller thread
  21015. // buffer up an IndexRead request
  21016. if (helper.leftCanMatch(row))
  21017. {
  21018. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21019. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21020. OwnedConstRoxieRow extracted;
  21021. if (indexReadSize)
  21022. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21023. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21024. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21025. {
  21026. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21027. if (thisBase)
  21028. {
  21029. unsigned fileNo = 0;
  21030. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21031. try
  21032. {
  21033. tlk->setKey(thisKey);
  21034. tlk->setLayoutTranslator(translators->item(fileNo));
  21035. helper.createSegmentMonitors(tlk, extracted);
  21036. if (rootIndex)
  21037. rootIndex->mergeSegmentMonitors(tlk);
  21038. tlk->finishSegmentMonitors();
  21039. tlk->reset();
  21040. loop
  21041. {
  21042. typedef const void * cvp;
  21043. if (thisKey->isTopLevelKey())
  21044. {
  21045. bool locallySorted = !thisKey->isFullySorted();
  21046. while (locallySorted || tlk->lookup(false))
  21047. {
  21048. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21049. if (locallySorted || slavePart)
  21050. {
  21051. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21052. *outputBuffer++ = jg;
  21053. if (indexReadInputRecordVariable)
  21054. {
  21055. *(unsigned *) outputBuffer = indexReadSize;
  21056. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21057. }
  21058. jg->notePending();
  21059. memcpy(outputBuffer, extracted, indexReadSize);
  21060. if (locallySorted)
  21061. {
  21062. for (unsigned i = 1; i < numChannels; i++)
  21063. jg->notePending();
  21064. break;
  21065. }
  21066. }
  21067. }
  21068. }
  21069. else
  21070. {
  21071. // MORE - this code seems to be duplicated in half keyed
  21072. unsigned accepted = 0;
  21073. unsigned rejected = 0;
  21074. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21075. jg->notePending();
  21076. unsigned candidateCount = 0;
  21077. while (tlk->lookup(true))
  21078. {
  21079. candidateCount++;
  21080. atomic_inc(&indexRecordsRead);
  21081. KLBlobProviderAdapter adapter(tlk);
  21082. offset_t recptr;
  21083. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21084. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21085. {
  21086. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21087. rhs->fpos = recptr;
  21088. rhs->thisGroup = jg;
  21089. rhs->partNo = partNo;
  21090. result->append(rhs);
  21091. }
  21092. else
  21093. {
  21094. rejected++;
  21095. atomic_inc(&postFiltered);
  21096. }
  21097. }
  21098. // output an end marker for the matches to this group
  21099. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21100. endMarker->fpos = (offset_t) candidateCount;
  21101. endMarker->thisGroup = jg;
  21102. endMarker->partNo = (unsigned short) -1;
  21103. result->append(endMarker);
  21104. remote.injectResult(result.getClear());
  21105. if (accepted)
  21106. noteStatistic(STATS_ACCEPTED, accepted, 1);
  21107. if (rejected)
  21108. noteStatistic(STATS_REJECTED, rejected, 1);
  21109. }
  21110. if (++fileNo < thisBase->numParts())
  21111. {
  21112. thisKey = thisBase->queryPart(fileNo);
  21113. tlk->setKey(thisKey);
  21114. tlk->setLayoutTranslator(translators->item(fileNo));
  21115. tlk->reset();
  21116. }
  21117. else
  21118. break;
  21119. }
  21120. tlk->releaseSegmentMonitors();
  21121. tlk->setKey(NULL);
  21122. }
  21123. catch (...)
  21124. {
  21125. tlk->releaseSegmentMonitors();
  21126. tlk->setKey(NULL);
  21127. throw;
  21128. }
  21129. }
  21130. }
  21131. joinHandler->noteEndReceived(jg, 0);
  21132. }
  21133. else
  21134. {
  21135. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21136. }
  21137. }
  21138. void processGroup(const ConstPointerArray &)
  21139. {
  21140. throwUnexpected();
  21141. }
  21142. virtual void processEOG()
  21143. {
  21144. joinHandler->processEOG();
  21145. }
  21146. virtual void processDone()
  21147. {
  21148. // called from puller thread
  21149. remote.flush();
  21150. remote.senddone();
  21151. }
  21152. virtual void onLimitExceeded(bool isKeyed)
  21153. {
  21154. if (traceLevel > 4)
  21155. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21156. if (isKeyed)
  21157. throwUnexpected();
  21158. helper.onLimitExceeded();
  21159. }
  21160. virtual const void *createLimitFailRow(bool isKeyed)
  21161. {
  21162. throwUnexpected();
  21163. }
  21164. virtual bool fireException(IException *e)
  21165. {
  21166. // called from puller thread on failure
  21167. remote.fireException(LINK(e));
  21168. return joinHandler->fireException(e);
  21169. }
  21170. virtual const void *nextInGroup()
  21171. {
  21172. throwUnexpected(); // I am nobody's input
  21173. }
  21174. };
  21175. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21176. {
  21177. protected:
  21178. IHThorKeyedJoinArg &helper;
  21179. KeyedJoinRemoteAdaptor remote;
  21180. RecordPullerThread puller;
  21181. OwnedConstRoxieRow defaultRight;
  21182. Owned<IEngineRowAllocator> defaultRightAllocator;
  21183. unsigned joinFlags;
  21184. unsigned atMost;
  21185. unsigned atmostsTriggered;
  21186. unsigned abortLimit;
  21187. unsigned keepLimit;
  21188. bool limitFail;
  21189. bool limitOnFail;
  21190. bool preserveGroups;
  21191. bool cloneLeft;
  21192. bool isSimple;
  21193. bool isLocal;
  21194. ThorActivityKind activityKind;
  21195. CJoinGroup *groupStart;
  21196. CriticalSection groupsCrit;
  21197. QueueOf<CJoinGroup, false> groups;
  21198. IRoxieInput *indexReadInput;
  21199. IIndexReadActivityInfo *rootIndex;
  21200. void createDefaultRight()
  21201. {
  21202. if (!defaultRight)
  21203. {
  21204. if (!defaultRightAllocator)
  21205. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21206. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21207. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21208. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21209. }
  21210. }
  21211. public:
  21212. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21213. , bool isFull, bool _isSimple, bool _isLocal)
  21214. : CRoxieServerActivity(_factory, _probeManager),
  21215. helper((IHThorKeyedJoinArg &)basehelper),
  21216. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21217. joinFlags(_joinFlags),
  21218. preserveGroups(meta.isGrouped()),
  21219. puller(false),
  21220. isSimple(_isSimple),
  21221. isLocal(_isLocal),
  21222. abortLimit(0),
  21223. keepLimit(0),
  21224. atMost(0),
  21225. limitFail(false),
  21226. limitOnFail(false),
  21227. cloneLeft(false)
  21228. {
  21229. groupStart = NULL;
  21230. activityKind = _factory->getKind();
  21231. indexReadInput = NULL;
  21232. rootIndex = NULL;
  21233. atmostsTriggered = 0;
  21234. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  21235. }
  21236. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21237. {
  21238. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21239. remote.onCreate(this, this, _ctx, _colocalParent);
  21240. }
  21241. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21242. {
  21243. if (!idx)
  21244. puller.setInput(this, _in);
  21245. else if (idx==1)
  21246. indexReadInput = _in;
  21247. else
  21248. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21249. }
  21250. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21251. {
  21252. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21253. if (indexReadInput)
  21254. {
  21255. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21256. rootIndex = indexReadInput->queryIndexReadActivity();
  21257. if (!rootIndex)
  21258. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21259. }
  21260. remote.onStart(parentExtractSize, parentExtract);
  21261. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21262. atmostsTriggered = 0;
  21263. atMost = helper.getJoinLimit();
  21264. if (atMost == 0) atMost = (unsigned)-1;
  21265. abortLimit = helper.getMatchAbortLimit();
  21266. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  21267. keepLimit = helper.getKeepLimit();
  21268. if (keepLimit == 0) keepLimit = (unsigned)-1;
  21269. getLimitType(joinFlags, limitFail, limitOnFail);
  21270. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  21271. if (joinFlags & JFleftouter)
  21272. createDefaultRight();
  21273. }
  21274. virtual void stop(bool aborting)
  21275. {
  21276. puller.stop(aborting);
  21277. if (indexReadInput)
  21278. indexReadInput->stop(aborting);
  21279. CRoxieServerActivity::stop(aborting);
  21280. }
  21281. virtual unsigned __int64 queryLocalCycles() const
  21282. {
  21283. __int64 localCycles = remote.totalCycles;
  21284. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  21285. if (localCycles < 0)
  21286. localCycles = 0;
  21287. return localCycles;
  21288. }
  21289. virtual IRoxieInput *queryInput(unsigned idx)
  21290. {
  21291. if (idx==0)
  21292. return puller.queryInput();
  21293. else if (idx==1)
  21294. return indexReadInput;
  21295. else
  21296. return NULL;
  21297. }
  21298. virtual void reset()
  21299. {
  21300. totalCycles = remote.totalCycles;
  21301. remote.totalCycles = 0;
  21302. processed = remote.joinProcessed;
  21303. remote.joinProcessed = 0;
  21304. defaultRight.clear();
  21305. if (indexReadInput)
  21306. indexReadInput->reset();
  21307. if (atmostsTriggered)
  21308. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  21309. CRoxieServerActivity::reset();
  21310. puller.reset();
  21311. while (groups.ordinality())
  21312. {
  21313. ::Release(groups.dequeue());
  21314. }
  21315. }
  21316. virtual IRoxieInput *queryOutput(unsigned idx)
  21317. {
  21318. if (idx==(unsigned)-1)
  21319. idx = 0;
  21320. return idx ? NULL : &remote;
  21321. }
  21322. #undef new
  21323. virtual CJoinGroup *createJoinGroup(const void *row)
  21324. {
  21325. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  21326. CriticalBlock c(groupsCrit);
  21327. if (preserveGroups && !groupStart)
  21328. {
  21329. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  21330. groups.enqueue(groupStart);
  21331. }
  21332. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  21333. groups.enqueue(jg);
  21334. return jg;
  21335. }
  21336. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21337. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21338. #endif
  21339. void endGroup()
  21340. {
  21341. CriticalBlock c(groupsCrit);
  21342. if (groupStart)
  21343. noteEndReceived(groupStart, 0);
  21344. groupStart = NULL;
  21345. }
  21346. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  21347. {
  21348. if (jg->noteEndReceived(candidateCount))
  21349. processCompletedGroups();
  21350. }
  21351. void processCompletedGroups()
  21352. {
  21353. loop
  21354. {
  21355. CriticalBlock c(groupsCrit);
  21356. if (!groups.head()->complete())
  21357. break;
  21358. Owned<CJoinGroup> head = groups.dequeue();
  21359. if (preserveGroups)
  21360. {
  21361. assert(head->isHeadRecord());
  21362. assert(groups.head()->inGroup(head));
  21363. unsigned joinGroupSize = 0;
  21364. while (groups.ordinality() && groups.head()->inGroup(head))
  21365. {
  21366. Owned<CJoinGroup> finger = groups.dequeue();
  21367. joinGroupSize += doJoinGroup(finger);
  21368. }
  21369. if (joinGroupSize)
  21370. remote.addResult(NULL);
  21371. }
  21372. else
  21373. doJoinGroup(head);
  21374. if (!groups.ordinality())
  21375. break;
  21376. }
  21377. }
  21378. void failLimit(const void * left)
  21379. {
  21380. helper.onMatchAbortLimitExceeded();
  21381. CommonXmlWriter xmlwrite(0);
  21382. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  21383. {
  21384. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  21385. }
  21386. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  21387. }
  21388. virtual bool needsAllocator() const { return true; }
  21389. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group)
  21390. {
  21391. if (cloneLeft && !except)
  21392. {
  21393. LinkRoxieRow(left);
  21394. remote.addResult((void *) left);
  21395. return 1;
  21396. }
  21397. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21398. unsigned outSize;
  21399. try
  21400. {
  21401. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  21402. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  21403. helper.transform(rowBuilder, left, right, fpos_or_count);
  21404. }
  21405. catch (IException *E)
  21406. {
  21407. throw makeWrappedException(E);
  21408. }
  21409. if (outSize)
  21410. {
  21411. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  21412. remote.addResult(shrunk);
  21413. return 1;
  21414. }
  21415. else
  21416. return 0;
  21417. }
  21418. unsigned doJoinGroup(CJoinGroup *jg)
  21419. {
  21420. unsigned matched = jg->rowsSeen();
  21421. unsigned added = 0;
  21422. const void *left = jg->queryLeft();
  21423. if (jg->candidateCount() > abortLimit)
  21424. {
  21425. if (limitFail)
  21426. failLimit(left);
  21427. if (ctx->queryDebugContext())
  21428. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21429. if (limitOnFail)
  21430. {
  21431. Owned<IException> except;
  21432. try
  21433. {
  21434. failLimit(left);
  21435. }
  21436. catch(IException * e)
  21437. {
  21438. except.setown(e);
  21439. }
  21440. added = doTransform(left, defaultRight, 0, except, NULL);
  21441. }
  21442. }
  21443. else if (!matched || jg->candidateCount() > atMost)
  21444. {
  21445. if (jg->candidateCount() > atMost)
  21446. atmostsTriggered++;
  21447. switch (joinFlags & JFtypemask)
  21448. {
  21449. case JFleftouter:
  21450. case JFleftonly:
  21451. switch (activityKind)
  21452. {
  21453. case TAKkeyedjoin:
  21454. case TAKkeyeddenormalizegroup:
  21455. added = doTransform(left, defaultRight, 0, NULL, NULL);
  21456. break;
  21457. case TAKkeyeddenormalize:
  21458. LinkRoxieRow(left);
  21459. remote.addResult((void *) left);
  21460. added++;
  21461. break;
  21462. }
  21463. break;
  21464. }
  21465. }
  21466. else if (!(joinFlags & JFexclude))
  21467. {
  21468. unsigned idx = 0;
  21469. switch (activityKind)
  21470. {
  21471. case TAKkeyedjoin:
  21472. while (idx < matched)
  21473. {
  21474. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21475. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL);
  21476. if (added==keepLimit)
  21477. break;
  21478. idx++;
  21479. }
  21480. break;
  21481. case TAKkeyeddenormalize:
  21482. {
  21483. OwnedConstRoxieRow newLeft;
  21484. newLeft.set(left);
  21485. unsigned rowSize = 0;
  21486. unsigned rightAdded = 0;
  21487. while (idx < matched)
  21488. {
  21489. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21490. try
  21491. {
  21492. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21493. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  21494. if (transformedSize)
  21495. {
  21496. rowSize = transformedSize;
  21497. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  21498. rightAdded++;
  21499. if (rightAdded==keepLimit)
  21500. break;
  21501. }
  21502. idx++;
  21503. }
  21504. catch (IException *E)
  21505. {
  21506. throw makeWrappedException(E);
  21507. }
  21508. }
  21509. if (rowSize)
  21510. {
  21511. remote.addResult(newLeft.getClear());
  21512. added++;
  21513. }
  21514. }
  21515. break;
  21516. case TAKkeyeddenormalizegroup:
  21517. {
  21518. ConstPointerArray extractedRows;
  21519. while (idx < matched && idx < keepLimit)
  21520. {
  21521. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21522. extractedRows.append((void *) &rhs->rhsdata);
  21523. idx++;
  21524. }
  21525. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray());
  21526. }
  21527. break;
  21528. }
  21529. }
  21530. return added;
  21531. }
  21532. virtual void processDone()
  21533. {
  21534. // called from puller thread
  21535. remote.flush();
  21536. remote.senddone();
  21537. }
  21538. virtual void onLimitExceeded(bool isKeyed)
  21539. {
  21540. if (traceLevel > 4)
  21541. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21542. if (isKeyed)
  21543. throwUnexpected();
  21544. helper.onLimitExceeded();
  21545. }
  21546. virtual const void *createLimitFailRow(bool isKeyed)
  21547. {
  21548. throwUnexpected();
  21549. }
  21550. virtual bool fireException(IException *e)
  21551. {
  21552. // called from puller thread on failure
  21553. return remote.fireException(e);
  21554. }
  21555. virtual const void *nextInGroup()
  21556. {
  21557. throwUnexpected(); // I am nobody's input
  21558. }
  21559. };
  21560. #ifdef _MSC_VER
  21561. #pragma warning ( push )
  21562. #pragma warning ( disable: 4355 )
  21563. #endif
  21564. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21565. {
  21566. CRoxieServerFullKeyedJoinHead head;
  21567. Owned<IEngineRowAllocator> fetchInputAllocator;
  21568. Linked<IFilePartMap> map;
  21569. bool variableFetchFileName;
  21570. Owned<const IResolvedFile> varFetchFileInfo;
  21571. CachedOutputMetaData fetchInputFields;
  21572. public:
  21573. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  21574. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  21575. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  21576. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  21577. map(_map)
  21578. {
  21579. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  21580. variableFetchFileName = allFilesDynamic || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21581. }
  21582. virtual const IResolvedFile *queryVarFileInfo() const
  21583. {
  21584. return varFetchFileInfo;
  21585. }
  21586. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21587. {
  21588. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21589. head.onCreate(_ctx, _colocalParent);
  21590. fetchInputFields.set(helper.queryFetchInputRecordSize());
  21591. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  21592. }
  21593. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21594. {
  21595. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21596. if (variableFetchFileName)
  21597. {
  21598. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  21599. OwnedRoxieString fname(helper.getFileName());
  21600. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  21601. if (varFetchFileInfo)
  21602. map.setown(varFetchFileInfo->getFileMap());
  21603. }
  21604. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), false, ctx);
  21605. }
  21606. virtual void setInput(unsigned idx, IRoxieInput *in)
  21607. {
  21608. head.setInput(idx, in);
  21609. }
  21610. virtual void processRow(const void *_rhs)
  21611. {
  21612. // called from puller thread
  21613. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  21614. CJoinGroup *jg = rhs->thisGroup;
  21615. if (rhs->partNo != (unsigned short) -1)
  21616. {
  21617. unsigned partNo = map->mapOffset(rhs->fpos);
  21618. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  21619. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  21620. if (fetchInputFields.isVariableSize())
  21621. {
  21622. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  21623. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21624. ReleaseRoxieRow(rhs);
  21625. jg->notePending();
  21626. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  21627. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  21628. }
  21629. else
  21630. {
  21631. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  21632. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21633. ReleaseRoxieRow(rhs);
  21634. jg->notePending();
  21635. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  21636. }
  21637. }
  21638. else
  21639. {
  21640. unsigned candidateCount = (unsigned) rhs->fpos;
  21641. // CTXLOG("Full keyed join - all results back from index");
  21642. ReleaseRoxieRow(rhs);
  21643. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  21644. }
  21645. }
  21646. virtual void processEOG()
  21647. {
  21648. // called from front puller thread
  21649. if (preserveGroups)
  21650. endGroup();
  21651. }
  21652. void processGroup(const ConstPointerArray &)
  21653. {
  21654. throwUnexpected();
  21655. }
  21656. };
  21657. #ifdef _MSC_VER
  21658. #pragma warning ( pop )
  21659. #endif
  21660. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21661. {
  21662. IOutputMetaData *indexReadMeta;
  21663. Owned<IEngineRowAllocator> indexReadAllocator;
  21664. Owned<IKeyManager> tlk;
  21665. bool variableIndexFileName;
  21666. bool indexReadInputRecordVariable;
  21667. Owned<const IResolvedFile> varFileInfo;
  21668. Linked<TranslatorArray> translators;
  21669. Linked<IKeyArray> keySet;
  21670. Owned<IOutputMetaData> joinPrefixedMeta;
  21671. Owned<IEngineRowAllocator> joinFieldsAllocator;
  21672. public:
  21673. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  21674. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  21675. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  21676. indexReadMeta(_indexReadMeta),
  21677. tlk(createKeyManager(NULL, 0, this)),
  21678. keySet(_keySet),
  21679. translators(_translators)
  21680. {
  21681. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21682. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21683. }
  21684. virtual void serializeExtra(MemoryBuffer &out)
  21685. {
  21686. if (helper.getJoinFlags() & JFindexfromactivity)
  21687. {
  21688. assertex(rootIndex);
  21689. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21690. indexId.serialize(out);
  21691. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21692. MemoryBuffer tmp;
  21693. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21694. if (rootIndex->queryActivity()->queryVarFileInfo())
  21695. {
  21696. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21697. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21698. }
  21699. unsigned ctxlen = tmp.length();
  21700. out.append(ctxlen).append(tmp);
  21701. }
  21702. }
  21703. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21704. {
  21705. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21706. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21707. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  21708. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  21709. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  21710. }
  21711. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21712. {
  21713. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21714. if (rootIndex)
  21715. {
  21716. varFileInfo.setown(rootIndex->getVarFileInfo());
  21717. translators.setown(rootIndex->getTranslators());
  21718. keySet.setown(rootIndex->getKeySet());
  21719. }
  21720. else if (variableIndexFileName)
  21721. {
  21722. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21723. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21724. if (varFileInfo)
  21725. {
  21726. translators.setown(new TranslatorArray);
  21727. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  21728. }
  21729. }
  21730. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), isSimple, ctx);
  21731. }
  21732. virtual const IResolvedFile *queryVarFileInfo() const
  21733. {
  21734. return varFileInfo;
  21735. }
  21736. virtual void reset()
  21737. {
  21738. CRoxieServerKeyedJoinBase::reset();
  21739. if (varFileInfo)
  21740. {
  21741. keySet.clear();
  21742. varFileInfo.clear();
  21743. }
  21744. }
  21745. virtual void processRow(const void *row)
  21746. {
  21747. // called from front puller thread
  21748. // buffer up an IndexRead request
  21749. if (helper.leftCanMatch(row) && keySet)
  21750. {
  21751. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  21752. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  21753. OwnedConstRoxieRow extracted;
  21754. if (indexReadRecordSize)
  21755. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  21756. CJoinGroup *jg = createJoinGroup(row);
  21757. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21758. {
  21759. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21760. if (thisBase)
  21761. {
  21762. unsigned fileNo = 0;
  21763. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21764. tlk->setKey(thisKey);
  21765. tlk->setLayoutTranslator(translators->item(fileNo));
  21766. helper.createSegmentMonitors(tlk, extracted);
  21767. if (rootIndex)
  21768. rootIndex->mergeSegmentMonitors(tlk);
  21769. tlk->finishSegmentMonitors();
  21770. try
  21771. {
  21772. tlk->reset();
  21773. loop
  21774. {
  21775. typedef const void * cvp;
  21776. if (thisKey && thisKey->isTopLevelKey())
  21777. {
  21778. bool locallySorted = (!thisKey->isFullySorted());
  21779. while (locallySorted || tlk->lookup(false))
  21780. {
  21781. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21782. if (locallySorted || slavePart)
  21783. {
  21784. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21785. *outputBuffer++ = jg;
  21786. if (indexReadInputRecordVariable)
  21787. {
  21788. *(unsigned *) outputBuffer = indexReadRecordSize;
  21789. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  21790. }
  21791. jg->notePending();
  21792. memcpy(outputBuffer, extracted, indexReadRecordSize);
  21793. if (locallySorted)
  21794. {
  21795. for (unsigned i = 1; i < numChannels; i++)
  21796. jg->notePending();
  21797. break;
  21798. }
  21799. }
  21800. }
  21801. }
  21802. else
  21803. {
  21804. unsigned accepted = 0;
  21805. unsigned rejected = 0;
  21806. Owned<CRowArrayMessageResult> result;
  21807. if (!isSimple)
  21808. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  21809. // MORE - This code seems to be duplicated in keyedJoinHead
  21810. jg->notePending();
  21811. unsigned candidateCount = 0;
  21812. while (tlk->lookup(true))
  21813. {
  21814. candidateCount++;
  21815. atomic_inc(&indexRecordsRead);
  21816. KLBlobProviderAdapter adapter(tlk);
  21817. offset_t recptr;
  21818. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21819. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21820. {
  21821. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  21822. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  21823. accepted++;
  21824. KLBlobProviderAdapter adapter(tlk);
  21825. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  21826. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  21827. rec->fpos = recptr;
  21828. rec->thisGroup = jg;
  21829. rec->partNo = partNo;
  21830. if (isSimple)
  21831. remote.injected.enqueue(rec);
  21832. else
  21833. result->append(rec);
  21834. }
  21835. else
  21836. {
  21837. rejected++;
  21838. atomic_inc(&postFiltered);
  21839. }
  21840. }
  21841. // output an end marker for the matches to this group
  21842. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21843. rec->fpos = (offset_t) candidateCount;
  21844. rec->thisGroup = jg;
  21845. rec->partNo = (unsigned short) -1;
  21846. if (isSimple)
  21847. remote.injected.enqueue(rec);
  21848. else
  21849. {
  21850. result->append(rec);
  21851. remote.injectResult(result.getClear());
  21852. }
  21853. if (accepted)
  21854. noteStatistic(STATS_ACCEPTED, accepted, 1);
  21855. if (rejected)
  21856. noteStatistic(STATS_REJECTED, rejected, 1);
  21857. }
  21858. if (++fileNo < thisBase->numParts())
  21859. {
  21860. thisKey = thisBase->queryPart(fileNo);
  21861. tlk->setKey(thisKey);
  21862. tlk->setLayoutTranslator(translators->item(fileNo));
  21863. tlk->reset();
  21864. }
  21865. else
  21866. break;
  21867. }
  21868. tlk->releaseSegmentMonitors();
  21869. tlk->setKey(NULL);
  21870. }
  21871. catch (...)
  21872. {
  21873. tlk->releaseSegmentMonitors();
  21874. tlk->setKey(NULL);
  21875. throw;
  21876. }
  21877. }
  21878. }
  21879. noteEndReceived(jg, 0);
  21880. }
  21881. else
  21882. {
  21883. noteEndReceived(createJoinGroup(row), 0);
  21884. }
  21885. }
  21886. virtual void processEOG()
  21887. {
  21888. // called from front puller thread
  21889. if (preserveGroups)
  21890. endGroup();
  21891. }
  21892. void processGroup(const ConstPointerArray &)
  21893. {
  21894. throwUnexpected();
  21895. }
  21896. };
  21897. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  21898. {
  21899. Owned<const IResolvedFile> indexfile;
  21900. Owned<const IResolvedFile> datafile;
  21901. Owned<IKeyArray> keySet;
  21902. Owned<TranslatorArray> translatorArray;
  21903. Owned<IDefRecordMeta> activityMeta;
  21904. RemoteActivityId headId;
  21905. RemoteActivityId tailId;
  21906. IOutputMetaData *indexReadMeta;
  21907. Owned<IFilePartMap> map;
  21908. Owned<IFileIOArray> files;
  21909. unsigned joinFlags;
  21910. bool isHalfKeyed;
  21911. bool isLocal;
  21912. bool enableFieldTranslation;
  21913. bool variableFetchFileName;
  21914. bool variableIndexFileName;
  21915. bool isSimple;
  21916. public:
  21917. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  21918. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  21919. {
  21920. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  21921. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21922. isSimple = isLocal;
  21923. rtlDataAttr indexLayoutMeta;
  21924. size32_t indexLayoutSize;
  21925. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  21926. assertex(indexLayoutSize== 0);
  21927. MemoryBuffer m;
  21928. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  21929. activityMeta.setown(deserializeRecordMeta(m, true));
  21930. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  21931. translatorArray.setown(new TranslatorArray);
  21932. joinFlags = helper->getJoinFlags();
  21933. variableIndexFileName = allFilesDynamic || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21934. variableFetchFileName = allFilesDynamic || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21935. if (!variableIndexFileName)
  21936. {
  21937. bool isOpt = (joinFlags & JFindexoptional) != 0;
  21938. OwnedRoxieString indexFileName(helper->getIndexFileName());
  21939. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, queryFactory.queryWorkUnit()));
  21940. if (indexfile)
  21941. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  21942. }
  21943. if (keySet && keySet->length()==1 && !isSimple)
  21944. {
  21945. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  21946. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  21947. isSimple = true;
  21948. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  21949. }
  21950. if (!simpleLocalKeyedJoins)
  21951. isSimple = false;
  21952. isHalfKeyed = !helper->diskAccessRequired();
  21953. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  21954. if (!isHalfKeyed && !variableFetchFileName)
  21955. {
  21956. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  21957. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isFetchOpt, true, _queryFactory.queryWorkUnit()));
  21958. if (datafile)
  21959. {
  21960. if (isLocal)
  21961. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  21962. else
  21963. map.setown(datafile->getFileMap());
  21964. }
  21965. }
  21966. }
  21967. virtual bool getEnableFieldTranslation() const
  21968. {
  21969. return enableFieldTranslation;
  21970. }
  21971. virtual IDefRecordMeta *queryActivityMeta() const
  21972. {
  21973. return activityMeta;
  21974. }
  21975. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21976. {
  21977. if (isHalfKeyed)
  21978. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  21979. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  21980. else
  21981. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  21982. headId, keySet, translatorArray, indexReadMeta,
  21983. tailId, map, joinFlags, isLocal);
  21984. }
  21985. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21986. {
  21987. if (datafile)
  21988. addXrefFileInfo(reply, datafile);
  21989. if (indexfile)
  21990. addXrefFileInfo(reply, indexfile);
  21991. }
  21992. };
  21993. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  21994. {
  21995. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  21996. }
  21997. //=================================================================================
  21998. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  21999. {
  22000. protected:
  22001. Owned<ISoapCallHelper> soaphelper;
  22002. IHThorSoapActionArg & helper;
  22003. StringBuffer authToken;
  22004. bool eof;
  22005. CriticalSection crit;
  22006. ClientCertificate *pClientCert;
  22007. public:
  22008. IMPLEMENT_IINTERFACE;
  22009. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22010. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22011. {
  22012. eof = false;
  22013. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22014. pClientCert = &clientCert;
  22015. else
  22016. pClientCert = NULL;
  22017. }
  22018. // ISoapCallRowProvider
  22019. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22020. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22021. virtual const void * getNextRow() { return NULL; };
  22022. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22023. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22024. {
  22025. eof = false;
  22026. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22027. authToken.append(ctx->queryAuthToken());
  22028. }
  22029. virtual void reset()
  22030. {
  22031. // MORE - Shouldn't we make sure thread is stopped etc???
  22032. soaphelper.clear();
  22033. CRoxieServerActivity::reset();
  22034. }
  22035. // IRoxieAbortMonitor
  22036. virtual void checkForAbort() { checkAbort(); }
  22037. };
  22038. //---------------------------------------------------------------------------
  22039. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22040. {
  22041. IHThorSoapCallArg & callHelper;
  22042. public:
  22043. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22044. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22045. {
  22046. }
  22047. virtual IHThorSoapCallArg * queryCallHelper()
  22048. {
  22049. return &callHelper;
  22050. }
  22051. virtual bool needsAllocator() const { return true; }
  22052. virtual const void *nextInGroup()
  22053. {
  22054. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22055. if(eof) return NULL;
  22056. if (soaphelper == NULL)
  22057. {
  22058. if (factory->getKind()==TAKhttp_rowdataset)
  22059. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22060. else
  22061. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22062. soaphelper->start();
  22063. }
  22064. OwnedConstRoxieRow ret = soaphelper->getRow();
  22065. if (!ret)
  22066. {
  22067. eof = true;
  22068. return NULL;
  22069. }
  22070. ++processed;
  22071. return ret.getClear();
  22072. }
  22073. };
  22074. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22075. {
  22076. public:
  22077. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22078. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22079. {
  22080. }
  22081. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22082. {
  22083. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22084. }
  22085. };
  22086. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22087. {
  22088. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22089. }
  22090. //---------------------------------------------------------------------------
  22091. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22092. {
  22093. public:
  22094. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22095. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22096. {}
  22097. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22098. {
  22099. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22100. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *ctx, this));
  22101. soaphelper->start();
  22102. soaphelper->waitUntilDone();
  22103. IException *e = soaphelper->getError();
  22104. soaphelper.clear();
  22105. if (e)
  22106. throw e;
  22107. }
  22108. virtual IRoxieInput *queryOutput(unsigned idx)
  22109. {
  22110. return NULL;
  22111. }
  22112. virtual const void *nextInGroup()
  22113. {
  22114. throwUnexpected(); // I am nobody's input
  22115. }
  22116. };
  22117. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22118. {
  22119. bool isRoot;
  22120. public:
  22121. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22122. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22123. {
  22124. }
  22125. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22126. {
  22127. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22128. }
  22129. virtual bool isSink() const
  22130. {
  22131. return isRoot;
  22132. }
  22133. };
  22134. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22135. {
  22136. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22137. }
  22138. //---------------------------------------------------------------------------
  22139. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22140. {
  22141. IHThorSoapCallArg & callHelper;
  22142. public:
  22143. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22144. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22145. {
  22146. }
  22147. virtual IHThorSoapCallArg * queryCallHelper()
  22148. {
  22149. return &callHelper;
  22150. }
  22151. virtual const void *getNextRow()
  22152. {
  22153. CriticalBlock b(crit);
  22154. const void *nextrec = input->nextInGroup();
  22155. if (!nextrec)
  22156. {
  22157. nextrec = input->nextInGroup();
  22158. }
  22159. return nextrec;
  22160. }
  22161. virtual bool needsAllocator() const { return true; }
  22162. virtual const void *nextInGroup()
  22163. {
  22164. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22165. if(eof) return NULL;
  22166. if (soaphelper == NULL)
  22167. {
  22168. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *ctx, this));
  22169. soaphelper->start();
  22170. }
  22171. OwnedConstRoxieRow ret = soaphelper->getRow();
  22172. if (!ret)
  22173. {
  22174. eof = true;
  22175. return NULL;
  22176. }
  22177. ++processed;
  22178. return ret.getClear();
  22179. }
  22180. };
  22181. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22182. {
  22183. public:
  22184. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22185. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22186. {
  22187. }
  22188. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22189. {
  22190. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22191. }
  22192. };
  22193. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22194. {
  22195. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22196. }
  22197. //---------------------------------------------------------------------------
  22198. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22199. {
  22200. public:
  22201. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22202. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22203. {}
  22204. virtual const void *getNextRow()
  22205. {
  22206. CriticalBlock b(crit);
  22207. const void *nextrec = input->nextInGroup();
  22208. if (!nextrec)
  22209. {
  22210. nextrec = input->nextInGroup();
  22211. }
  22212. if (nextrec)
  22213. processed++;
  22214. return nextrec;
  22215. }
  22216. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22217. {
  22218. try
  22219. {
  22220. start(parentExtractSize, parentExtract, false);
  22221. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *ctx, this));
  22222. soaphelper->start();
  22223. soaphelper->waitUntilDone();
  22224. IException *e = soaphelper->getError();
  22225. soaphelper.clear();
  22226. if (e)
  22227. throw e;
  22228. stop(false);
  22229. }
  22230. catch (IException *E)
  22231. {
  22232. ctx->notifyAbort(E);
  22233. stop(true);
  22234. throw;
  22235. }
  22236. catch(...)
  22237. {
  22238. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  22239. ctx->notifyAbort(E);
  22240. stop(true);
  22241. throw;
  22242. }
  22243. }
  22244. virtual IRoxieInput *queryOutput(unsigned idx)
  22245. {
  22246. return NULL;
  22247. }
  22248. virtual const void *nextInGroup()
  22249. {
  22250. throwUnexpected(); // I am nobody's input
  22251. }
  22252. };
  22253. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  22254. {
  22255. bool isRoot;
  22256. public:
  22257. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22258. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22259. {
  22260. }
  22261. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22262. {
  22263. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  22264. }
  22265. virtual bool isSink() const
  22266. {
  22267. return isRoot;
  22268. }
  22269. };
  22270. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22271. {
  22272. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22273. }
  22274. //=====================================================================================================
  22275. class CGraphResults : public CInterface, implements IRoxieGraphResults
  22276. {
  22277. IArrayOf<IGraphResult> results;
  22278. CriticalSection cs;
  22279. IGraphResult & select(unsigned idx)
  22280. {
  22281. CriticalBlock procedure(cs);
  22282. if (idx >= results.ordinality())
  22283. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  22284. return results.item(idx);
  22285. }
  22286. public:
  22287. IMPLEMENT_IINTERFACE
  22288. void clear()
  22289. {
  22290. CriticalBlock procedure(cs);
  22291. results.kill();
  22292. }
  22293. IRoxieInput * createIterator(unsigned id)
  22294. {
  22295. return select(id).createIterator();
  22296. }
  22297. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22298. {
  22299. select(id).getLinkedResult(count, ret);
  22300. }
  22301. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22302. {
  22303. select(id).getLinkedResult(count, ret);
  22304. }
  22305. void setResult(unsigned id, IGraphResult * result)
  22306. {
  22307. CriticalBlock procedure(cs);
  22308. if (results.ordinality() <= id)
  22309. {
  22310. while (results.ordinality() < id)
  22311. results.append(*new CGraphResult);
  22312. results.append(*LINK(result));
  22313. }
  22314. else
  22315. results.replace(*LINK(result), id);
  22316. }
  22317. void appendResult(IGraphResult * result)
  22318. {
  22319. CriticalBlock procedure(cs);
  22320. results.append(*LINK(result));
  22321. }
  22322. };
  22323. //===================================================================================================================
  22324. class CPseudoArg : public CInterface, implements IHThorArg
  22325. {
  22326. public:
  22327. IMPLEMENT_IINTERFACE
  22328. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  22329. };
  22330. class CPseudoActivity : public CRoxieServerActivity
  22331. {
  22332. public:
  22333. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  22334. virtual const void *nextInGroup()
  22335. {
  22336. throwUnexpected(); // I am nobody's input
  22337. }
  22338. };
  22339. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  22340. {
  22341. protected:
  22342. IArrayOf<IRoxieServerActivity> activities;
  22343. IArrayOf<IRoxieInput> probes;
  22344. IRoxieServerActivityCopyArray sinks;
  22345. StringAttr graphName;
  22346. Owned<CGraphResults> results;
  22347. CGraphResults graphLoopResults;
  22348. ActivityArray & graphDefinition;
  22349. CriticalSection evaluateCrit;
  22350. IProbeManager *probeManager;
  22351. unsigned id;
  22352. unsigned loopCounter;
  22353. class ActivityGraphSlaveContext : public IndirectSlaveContext
  22354. {
  22355. SpinLock abortLock;
  22356. bool aborted;
  22357. Owned<IException> exception;
  22358. public:
  22359. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  22360. {
  22361. aborted = false;
  22362. }
  22363. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  22364. virtual void notifyAbort(IException *E)
  22365. {
  22366. SpinBlock b(abortLock);
  22367. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  22368. {
  22369. aborted = true;
  22370. exception.set(E);
  22371. }
  22372. }
  22373. virtual void checkAbort()
  22374. {
  22375. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  22376. {
  22377. SpinBlock b(abortLock);
  22378. if (!exception)
  22379. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  22380. throw exception.getLink();
  22381. }
  22382. IndirectSlaveContext::checkAbort();
  22383. }
  22384. virtual ICodeContext *queryCodeContext()
  22385. {
  22386. return codeContext;
  22387. }
  22388. void setCodeContext(ICodeContext * _codeContext)
  22389. {
  22390. codeContext = _codeContext;
  22391. }
  22392. void setLoopCounter(unsigned _loopCounter)
  22393. {
  22394. loopCounter = _loopCounter;
  22395. }
  22396. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  22397. {
  22398. childGraphs.setValue(id, childGraph);
  22399. }
  22400. virtual IActivityGraph * queryChildGraph(unsigned id)
  22401. {
  22402. if (queryTraceLevel() > 10)
  22403. CTXLOG("resolveChildGraph %d", id);
  22404. IActivityGraph *childGraph = childGraphs.getValue(id);
  22405. assertex(childGraph);
  22406. return childGraph;
  22407. }
  22408. // 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
  22409. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  22410. {
  22411. logctx.getLogPrefix(ret);
  22412. if (loopCounter)
  22413. ret.appendf("{%u}", loopCounter);
  22414. return ret;
  22415. }
  22416. protected:
  22417. const IRoxieContextLogger &logctx;
  22418. unsigned loopCounter;
  22419. ICodeContext * codeContext;
  22420. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  22421. } graphSlaveContext;
  22422. class ActivityGraphCodeContext : public IndirectCodeContext
  22423. {
  22424. public:
  22425. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  22426. {
  22427. if ((unsigned) activityId == container->queryId())
  22428. return container;
  22429. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22430. if (match)
  22431. return match->queryLocalGraph();
  22432. return IndirectCodeContext::resolveLocalQuery(activityId);
  22433. }
  22434. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  22435. {
  22436. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22437. return LINK(match->queryChildGraph());
  22438. }
  22439. virtual unsigned getGraphLoopCounter() const
  22440. {
  22441. return container->queryLoopCounter(); // only called if value is valid
  22442. }
  22443. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  22444. {
  22445. slaveContext = _slaveContext;
  22446. container = _container;
  22447. }
  22448. protected:
  22449. IRoxieSlaveContext * slaveContext;
  22450. CActivityGraph * container;
  22451. } graphCodeContext;
  22452. public:
  22453. IMPLEMENT_IINTERFACE;
  22454. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  22455. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  22456. {
  22457. id = x.getLibraryGraphId();
  22458. if (!id)
  22459. id = _id;
  22460. loopCounter = 0;
  22461. graphSlaveContext.setCodeContext(&graphCodeContext);
  22462. graphCodeContext.setContainer(&graphSlaveContext, this);
  22463. }
  22464. ~CActivityGraph()
  22465. {
  22466. if (probeManager)
  22467. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  22468. }
  22469. virtual const char *queryName() const
  22470. {
  22471. return graphName.get();
  22472. }
  22473. void createGraph()
  22474. {
  22475. ForEachItemIn(idx, graphDefinition)
  22476. {
  22477. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  22478. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  22479. activities.append(activity);
  22480. if (donor.isSink())
  22481. {
  22482. sinks.append(activity);
  22483. if (probeManager)
  22484. probeManager->noteSink(&activity);
  22485. }
  22486. }
  22487. ForEachItemIn(idx1, graphDefinition)
  22488. {
  22489. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  22490. IRoxieServerActivity &activity = activities.item(idx1);
  22491. unsigned inputidx = 0;
  22492. loop
  22493. {
  22494. unsigned outputidx;
  22495. unsigned source = donor.getInput(inputidx, outputidx);
  22496. if (source==(unsigned) -1)
  22497. break;
  22498. connectInput(idx1, inputidx, source, outputidx, 0);
  22499. inputidx++;
  22500. }
  22501. IntArray &dependencies = donor.queryDependencies();
  22502. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  22503. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  22504. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  22505. ForEachItemIn(idx2, dependencies)
  22506. {
  22507. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  22508. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  22509. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  22510. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  22511. if (probeManager)
  22512. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  22513. }
  22514. }
  22515. }
  22516. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  22517. {
  22518. IRoxieServerActivity &targetActivity = activities.item(target);
  22519. IRoxieServerActivity &sourceActivity = activities.item(source);
  22520. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  22521. if (probeManager)
  22522. {
  22523. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  22524. output = static_cast<IRoxieInput*>(inputBase);
  22525. probes.append(*LINK(output));
  22526. }
  22527. targetActivity.setInput(targetIdx, output);
  22528. }
  22529. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  22530. {
  22531. graphSlaveContext.set(ctx);
  22532. if (graphDefinition.isMultiInstance())
  22533. {
  22534. graphCodeContext.set(ctx->queryCodeContext());
  22535. ctx = &graphSlaveContext;
  22536. }
  22537. ForEachItemIn(idx, activities)
  22538. {
  22539. IRoxieServerActivity *activity = &activities.item(idx);
  22540. if (activity)
  22541. activity->onCreate(ctx, _colocalParent);
  22542. }
  22543. }
  22544. virtual void abort()
  22545. {
  22546. ForEachItemIn(idx, sinks)
  22547. {
  22548. IRoxieServerActivity &sink = sinks.item(idx);
  22549. sink.stop(true);
  22550. }
  22551. }
  22552. virtual void reset()
  22553. {
  22554. ForEachItemIn(idx, sinks)
  22555. {
  22556. IRoxieServerActivity &sink = sinks.item(idx);
  22557. sink.reset();
  22558. }
  22559. }
  22560. Linked<IException> exception;
  22561. CriticalSection eCrit;
  22562. virtual void noteException(IException *E)
  22563. {
  22564. CriticalBlock b(eCrit);
  22565. if (!exception)
  22566. {
  22567. if (graphSlaveContext.queryDebugContext())
  22568. {
  22569. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  22570. }
  22571. exception.set(E);
  22572. }
  22573. }
  22574. virtual void checkAbort()
  22575. {
  22576. CriticalBlock b(eCrit);
  22577. if (exception)
  22578. throw exception.getLink();
  22579. }
  22580. virtual void execute()
  22581. {
  22582. doExecute(0, NULL);
  22583. }
  22584. //New child query code...
  22585. virtual IThorChildGraph * queryChildGraph()
  22586. {
  22587. return this;
  22588. }
  22589. virtual IEclGraphResults * queryLocalGraph()
  22590. {
  22591. return this;
  22592. }
  22593. virtual IRoxieServerChildGraph * queryLoopGraph()
  22594. {
  22595. return this;
  22596. }
  22597. inline unsigned queryId() const
  22598. {
  22599. return id;
  22600. }
  22601. inline unsigned queryLoopCounter() const
  22602. {
  22603. return loopCounter;
  22604. }
  22605. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  22606. {
  22607. if (sinks.ordinality()==1)
  22608. sinks.item(0).execute(parentExtractSize, parentExtract);
  22609. #ifdef PARALLEL_EXECUTE
  22610. else if (!probeManager && !graphDefinition.isSequential())
  22611. {
  22612. class casyncfor: public CAsyncFor
  22613. {
  22614. public:
  22615. IActivityGraph &parent;
  22616. unsigned parentExtractSize;
  22617. const byte * parentExtract;
  22618. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  22619. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  22620. void Do(unsigned i)
  22621. {
  22622. try
  22623. {
  22624. sinks.item(i).execute(parentExtractSize, parentExtract);
  22625. }
  22626. catch (IException *E)
  22627. {
  22628. parent.noteException(E);
  22629. throw;
  22630. }
  22631. }
  22632. private:
  22633. IRoxieServerActivityCopyArray &sinks;
  22634. } afor(sinks, *this, parentExtractSize, parentExtract);
  22635. afor.For(sinks.ordinality(), sinks.ordinality());
  22636. }
  22637. #endif
  22638. else
  22639. {
  22640. ForEachItemIn(idx, sinks)
  22641. {
  22642. IRoxieServerActivity &sink = sinks.item(idx);
  22643. sink.execute(parentExtractSize, parentExtract);
  22644. }
  22645. }
  22646. }
  22647. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  22648. {
  22649. CriticalBlock block(evaluateCrit);
  22650. results.setown(new CGraphResults);
  22651. try
  22652. {
  22653. doExecute(parentExtractSize, parentExtract);
  22654. }
  22655. catch (...)
  22656. {
  22657. DBGLOG("Exception thrown in child query - cleaning up");
  22658. reset();
  22659. throw;
  22660. }
  22661. reset();
  22662. return results.getClear();
  22663. }
  22664. //interface IRoxieServerChildGraph
  22665. virtual void beforeExecute()
  22666. {
  22667. results.setown(new CGraphResults);
  22668. }
  22669. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22670. {
  22671. IRoxieInput * ret = selectOutput(id);
  22672. ret->start(parentExtractSize, parentExtract, paused);
  22673. return ret;
  22674. }
  22675. virtual IRoxieInput * selectOutput(unsigned id)
  22676. {
  22677. ForEachItemIn(i, sinks)
  22678. {
  22679. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  22680. if (ret)
  22681. return ret;
  22682. }
  22683. throwUnexpected();
  22684. return NULL;
  22685. }
  22686. virtual void setInputResult(unsigned id, IGraphResult * result)
  22687. {
  22688. results->setResult(id, result);
  22689. }
  22690. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  22691. {
  22692. ForEachItemIn(i, activities)
  22693. {
  22694. if (activities.item(i).querySetStreamInput(id, input))
  22695. return true;
  22696. }
  22697. return false;
  22698. }
  22699. virtual void stopUnusedOutputs()
  22700. {
  22701. //Hmm not sure how to do this...
  22702. }
  22703. virtual void afterExecute()
  22704. {
  22705. ForEachItemIn(i, sinks)
  22706. {
  22707. sinks.item(i).stop(false);
  22708. }
  22709. if (graphSlaveContext.queryDebugContext())
  22710. {
  22711. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  22712. }
  22713. reset();
  22714. }
  22715. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  22716. {
  22717. doExecute(parentExtractSize, parentExtract);
  22718. return LINK(results);
  22719. }
  22720. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22721. {
  22722. results->getLinkedResult(count, ret, id);
  22723. }
  22724. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22725. {
  22726. results->getLinkedResult(count, ret, id);
  22727. }
  22728. virtual void setResult(unsigned id, IGraphResult * result)
  22729. {
  22730. results->setResult(id, result);
  22731. }
  22732. virtual IRoxieInput * createResultIterator(unsigned id)
  22733. {
  22734. return results->createIterator(id);
  22735. }
  22736. virtual void setGraphLoopResult(IGraphResult * result)
  22737. {
  22738. graphLoopResults.appendResult(result);
  22739. }
  22740. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  22741. {
  22742. try
  22743. {
  22744. return graphLoopResults.createIterator(id);
  22745. }
  22746. catch (IException * e)
  22747. {
  22748. e->Release();
  22749. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  22750. }
  22751. }
  22752. virtual void clearGraphLoopResults()
  22753. {
  22754. graphLoopResults.clear();
  22755. }
  22756. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  22757. {
  22758. doExecute(parentExtractSize, parentExtract);
  22759. }
  22760. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  22761. {
  22762. graphLoopResults.setResult(id, result);
  22763. }
  22764. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  22765. {
  22766. return graphLoopResults.createIterator(id);
  22767. }
  22768. virtual void getProbeResponse(IPropertyTree *query)
  22769. {
  22770. if (probeManager)
  22771. probeManager->getProbeResponse(query);
  22772. }
  22773. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  22774. {
  22775. throwUnexpected();
  22776. }
  22777. virtual CGraphIterationInfo *selectGraphLoopOutput()
  22778. {
  22779. return NULL;
  22780. }
  22781. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  22782. {
  22783. throwUnexpected();
  22784. }
  22785. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  22786. {
  22787. throwUnexpected();
  22788. }
  22789. };
  22790. class CIterationActivityGraph : public CActivityGraph
  22791. {
  22792. IHThorArg * colocalParent;
  22793. unsigned fixedParentExtractSize;
  22794. const byte * fixedParentExtract;
  22795. unsigned graphOutputActivityIndex;
  22796. public:
  22797. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  22798. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  22799. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  22800. {
  22801. graphOutputActivityIndex = 0;
  22802. loopCounter = _loopCounter;
  22803. colocalParent = _colocalParent;
  22804. graphSlaveContext.set(ctx);
  22805. graphSlaveContext.setLoopCounter(loopCounter);
  22806. graphCodeContext.set(ctx->queryCodeContext());
  22807. fixedParentExtractSize = parentExtractSize;
  22808. fixedParentExtract = parentExtract;
  22809. }
  22810. void createIterationGraph()
  22811. {
  22812. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  22813. ForEachItemIn(idx1, graphDefinition)
  22814. activities.append(*LINK(pseudoActivity));
  22815. graphOutputActivityIndex = queryGraphOutputIndex();
  22816. recursiveCreateGraph(graphOutputActivityIndex);
  22817. }
  22818. unsigned queryGraphOutputIndex() const
  22819. {
  22820. ForEachItemIn(i, graphDefinition)
  22821. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  22822. return i;
  22823. throwUnexpected();
  22824. }
  22825. void recursiveCreateGraph(unsigned whichActivity)
  22826. {
  22827. //Check to see if already created
  22828. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  22829. if (prevActivity.queryId() != 0)
  22830. {
  22831. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  22832. return;
  22833. }
  22834. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  22835. IRoxieServerActivity * activity = NULL;
  22836. if (donor.isGraphInvariant())
  22837. {
  22838. ThorActivityKind kind = donor.getKind();
  22839. switch (kind)
  22840. {
  22841. case TAKif:
  22842. case TAKchildif:
  22843. case TAKcase:
  22844. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  22845. {
  22846. Owned<IHThorArg> helper = &donor.getHelper();
  22847. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  22848. helper->onStart(fixedParentExtract, NULL);
  22849. unsigned branch;
  22850. switch (kind)
  22851. {
  22852. case TAKif: case TAKchildif:
  22853. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  22854. break;
  22855. case TAKcase: case TAKchildcase:
  22856. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  22857. if (branch >= donor.numInputs())
  22858. branch = donor.numInputs() - 1;
  22859. break;
  22860. default:
  22861. throwUnexpected();
  22862. }
  22863. helper.clear();
  22864. unsigned outputidx;
  22865. unsigned source = donor.getInput(branch, outputidx);
  22866. if (source ==(unsigned) -1)
  22867. activity = createRoxieServerNullActivity(&donor, probeManager);
  22868. else
  22869. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  22870. activities.replace(*activity, whichActivity);
  22871. activity->onCreate(&graphSlaveContext, colocalParent);
  22872. if (source ==(unsigned) -1)
  22873. return;
  22874. recursiveCreateGraph(source);
  22875. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  22876. break;
  22877. }
  22878. }
  22879. }
  22880. if (!activity)
  22881. {
  22882. activity = donor.createActivity(probeManager);
  22883. activities.replace(*activity, whichActivity);
  22884. activity->onCreate(&graphSlaveContext, colocalParent);
  22885. activity->resetOutputsUsed();
  22886. unsigned inputidx = 0;
  22887. loop
  22888. {
  22889. unsigned outputidx;
  22890. unsigned source = donor.getInput(inputidx, outputidx);
  22891. if (source==(unsigned) -1)
  22892. break;
  22893. recursiveCreateGraph(source);
  22894. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  22895. inputidx++;
  22896. }
  22897. }
  22898. IntArray &dependencies = donor.queryDependencies();
  22899. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  22900. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  22901. ForEachItemIn(idx2, dependencies)
  22902. {
  22903. unsigned input = dependencies.item(idx2);
  22904. recursiveCreateGraph(input);
  22905. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  22906. }
  22907. }
  22908. virtual CGraphIterationInfo *selectGraphLoopOutput()
  22909. {
  22910. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  22911. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  22912. }
  22913. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  22914. {
  22915. ForEachItemIn(i, activities)
  22916. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  22917. }
  22918. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  22919. {
  22920. ForEachItemIn(i, activities)
  22921. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  22922. }
  22923. };
  22924. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  22925. {
  22926. StringAttr graphName;
  22927. ActivityArray & graphDefinition;
  22928. IProbeManager *probeManager;
  22929. unsigned id;
  22930. IRoxieSlaveContext * ctx;
  22931. IHThorArg * colocalParent;
  22932. public:
  22933. IMPLEMENT_IINTERFACE;
  22934. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  22935. : probeManager(_probeManager), graphDefinition(x)
  22936. {
  22937. graphName.set(_graphName);
  22938. id = _id;
  22939. ctx = NULL;
  22940. colocalParent = NULL;
  22941. }
  22942. virtual const char *queryName() const { return graphName.get(); }
  22943. virtual void abort() { throwUnexpected(); }
  22944. virtual void reset() { }
  22945. virtual void execute() { throwUnexpected(); }
  22946. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  22947. virtual void noteException(IException *E) { throwUnexpected(); }
  22948. virtual void checkAbort() { throwUnexpected(); }
  22949. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  22950. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  22951. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  22952. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22953. {
  22954. ctx = _ctx;
  22955. colocalParent = _colocalParent;
  22956. }
  22957. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  22958. {
  22959. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  22960. ret->createIterationGraph();
  22961. return ret.getClear();
  22962. }
  22963. };
  22964. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  22965. {
  22966. if (childFactories.isDelayed())
  22967. {
  22968. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  22969. }
  22970. else
  22971. {
  22972. Owned<IProbeManager> childProbe;
  22973. if (_probeManager)
  22974. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  22975. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  22976. ret->createGraph();
  22977. if (_probeManager)
  22978. _probeManager->endChildGraph(childProbe, parentActivity);
  22979. return ret.getClear();
  22980. }
  22981. }
  22982. //================================================================================================================
  22983. #ifdef _USE_CPPUNIT
  22984. #include "unittests.hpp"
  22985. // 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...
  22986. #if _MSC_VER==1200
  22987. #undef protected
  22988. #endif
  22989. static const char *sortAlgorithm;
  22990. class TestMetaData : public CInterface, implements IOutputMetaData
  22991. {
  22992. public:
  22993. IMPLEMENT_IINTERFACE;
  22994. virtual size32_t getRecordSize(const void *) { return 10; }
  22995. virtual size32_t getMinRecordSize() const { return 10; }
  22996. virtual size32_t getFixedSize() const { return 10; }
  22997. virtual void toXML(const byte * self, IXmlWriter & out) {}
  22998. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  22999. virtual unsigned getMetaFlags() { return 0; }
  23000. virtual void destruct(byte * self) {}
  23001. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23002. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23003. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23004. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23005. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23006. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23007. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23008. } testMeta;
  23009. class TestInput : public CInterface, implements IRoxieInput
  23010. {
  23011. char const * const *input;
  23012. IRoxieSlaveContext *ctx;
  23013. unsigned endSeen;
  23014. bool eof;
  23015. unsigned count;
  23016. unsigned __int64 totalCycles;
  23017. size32_t recordSize;
  23018. unsigned activityId;
  23019. public:
  23020. enum { STATEreset, STATEstarted, STATEstopped } state;
  23021. bool allRead;
  23022. IMPLEMENT_IINTERFACE;
  23023. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23024. {
  23025. ctx = _ctx;
  23026. input = _input;
  23027. count = 0;
  23028. eof = false;
  23029. allRead = false;
  23030. endSeen = 0;
  23031. recordSize = testMeta.getFixedSize();
  23032. state = STATEreset;
  23033. totalCycles = 0;
  23034. activityId = 1;
  23035. }
  23036. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23037. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23038. {
  23039. ASSERT(state == STATEreset);
  23040. }
  23041. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23042. {
  23043. ASSERT(state == STATEreset);
  23044. state = STATEstarted;
  23045. }
  23046. virtual IRoxieServerActivity *queryActivity()
  23047. {
  23048. throwUnexpected();
  23049. }
  23050. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23051. {
  23052. throwUnexpected();
  23053. }
  23054. virtual void stop(bool aborting)
  23055. {
  23056. state = STATEstopped;
  23057. }
  23058. virtual void reset()
  23059. {
  23060. ASSERT(state == STATEstopped);
  23061. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset; totalCycles = 0;
  23062. }
  23063. virtual void resetEOF()
  23064. {
  23065. throwUnexpected();
  23066. }
  23067. virtual void checkAbort() {}
  23068. virtual unsigned queryId() const { return activityId; };
  23069. virtual const void *nextInGroup()
  23070. {
  23071. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  23072. ASSERT(state == STATEstarted);
  23073. ASSERT(allRead || !eof);
  23074. if (eof)
  23075. return NULL;
  23076. const char *nextSource = input[count++];
  23077. if (nextSource)
  23078. {
  23079. endSeen = 0;
  23080. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23081. memset(ret, 0, recordSize);
  23082. strncpy((char *) ret, nextSource, recordSize);
  23083. return ret;
  23084. }
  23085. else
  23086. {
  23087. endSeen++;
  23088. if (endSeen==2)
  23089. eof = true;
  23090. return NULL;
  23091. }
  23092. }
  23093. virtual bool nextGroup(ConstPointerArray & group)
  23094. {
  23095. const void * next;
  23096. while ((next = nextInGroup()) != NULL)
  23097. group.append(next);
  23098. if (group.ordinality())
  23099. return true;
  23100. return false;
  23101. }
  23102. virtual unsigned __int64 queryTotalCycles() const { return totalCycles; }
  23103. virtual unsigned __int64 queryLocalCycles() const { return totalCycles; }
  23104. virtual IRoxieInput *queryInput(unsigned idx) const
  23105. {
  23106. return NULL;
  23107. }
  23108. };
  23109. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23110. public:
  23111. struct CompareClass : public ICompare {
  23112. virtual int docompare(const void * _left, const void * _right) const {
  23113. return memcmp(_left, _right, 5);
  23114. }
  23115. } compare;
  23116. virtual ICompare * queryCompare() { return &compare; }
  23117. virtual IOutputMetaData * queryOutputMeta()
  23118. {
  23119. return &testMeta;
  23120. }
  23121. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23122. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23123. };
  23124. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23125. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23126. static bool isDedup;
  23127. public:
  23128. struct CompareClass : public ICompare {
  23129. virtual int docompare(const void * _left, const void * _right) const {
  23130. return memcmp(_left, _right, 5);
  23131. }
  23132. } compare;
  23133. virtual ICompare * queryCompare() { return &compare; }
  23134. virtual IOutputMetaData * queryOutputMeta()
  23135. {
  23136. return &testMeta;
  23137. }
  23138. virtual bool dedup() { return isDedup; }
  23139. };
  23140. bool MergeActivityTest::isDedup = false;
  23141. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23142. class CcdServerTest : public CppUnit::TestFixture
  23143. {
  23144. CPPUNIT_TEST_SUITE(CcdServerTest);
  23145. CPPUNIT_TEST(testSetup);
  23146. CPPUNIT_TEST(testHeapSort);
  23147. CPPUNIT_TEST(testInsertionSort);
  23148. CPPUNIT_TEST(testQuickSort);
  23149. CPPUNIT_TEST(testMerge);
  23150. CPPUNIT_TEST(testMergeDedup);
  23151. CPPUNIT_TEST(testMiscellaneous);
  23152. CPPUNIT_TEST(testCleanup);
  23153. CPPUNIT_TEST_SUITE_END();
  23154. protected:
  23155. SlaveContextLogger logctx;
  23156. Owned<const IQueryDll> queryDll;
  23157. Owned<IRoxiePackage> package;
  23158. Owned<IRoxieSlaveContext> ctx;
  23159. Owned<IQueryFactory> queryFactory;
  23160. void testSetup()
  23161. {
  23162. roxiemem::setTotalMemoryLimit(false, 100 * 1024 * 1024, 0, NULL);
  23163. }
  23164. void testCleanup()
  23165. {
  23166. roxiemem::releaseRoxieHeap();
  23167. }
  23168. void init()
  23169. {
  23170. package.setown(createRoxiePackage(NULL, NULL));
  23171. ctx.setown(createSlaveContext(NULL, logctx, 0, 50*1024*1024, NULL));
  23172. queryDll.setown(createExeQueryDll("roxie"));
  23173. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, NULL));
  23174. timer->reset();
  23175. }
  23176. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  23177. {
  23178. testActivity(activity, input, NULL, output);
  23179. }
  23180. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output)
  23181. {
  23182. TestInput in(ctx, input);
  23183. TestInput in2(ctx, input2);
  23184. IRoxieInput *out = activity->queryOutput(0);
  23185. IOutputMetaData *meta = out->queryOutputMeta();
  23186. activity->setInput(0, &in);
  23187. if (input2)
  23188. activity->setInput(1, &in2);
  23189. void *buf = alloca(meta->getFixedSize());
  23190. for (unsigned iteration = 0; iteration < 8; iteration++)
  23191. {
  23192. // 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)
  23193. // This should be true whether we read all, some, or none of the data.
  23194. // Should not matter if an activity is not started
  23195. if (iteration % 4 == 0)
  23196. activity->onCreate(ctx, NULL);
  23197. unsigned count = 0;
  23198. if (iteration % 4 != 3)
  23199. {
  23200. activity->start(0, NULL, false);
  23201. ASSERT(in.state == TestInput::STATEstarted);
  23202. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  23203. loop
  23204. {
  23205. const void *next = out->nextInGroup();
  23206. if (!next)
  23207. {
  23208. ASSERT(output[count++] == NULL);
  23209. next = out->nextInGroup();
  23210. if (!next)
  23211. {
  23212. ASSERT(output[count++] == NULL);
  23213. break;
  23214. }
  23215. }
  23216. ASSERT(output[count] != NULL);
  23217. unsigned outsize = meta->getRecordSize(next);
  23218. memset(buf, 0, outsize);
  23219. strncpy((char *) buf, output[count++], outsize);
  23220. ASSERT(memcmp(next, buf, outsize) == 0);
  23221. ReleaseRoxieRow(next);
  23222. if (iteration % 4 == 2)
  23223. break;
  23224. }
  23225. if (iteration % 4 != 2)
  23226. {
  23227. // Check that reading after end is harmless
  23228. in.allRead = true;
  23229. const void *next = out->nextInGroup();
  23230. ASSERT(next == NULL);
  23231. }
  23232. }
  23233. activity->stop(false);
  23234. ASSERT(in.state == TestInput::STATEstopped);
  23235. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  23236. activity->reset();
  23237. ASSERT(in.state == TestInput::STATEreset);
  23238. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  23239. ctx->queryRowManager().reportLeaks();
  23240. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  23241. }
  23242. }
  23243. static int compareFunc(const void *l, const void *r)
  23244. {
  23245. return strcmp(*(char **) l, *(char **) r);
  23246. }
  23247. void testSort(unsigned type)
  23248. {
  23249. init();
  23250. sortAlgorithm = NULL;
  23251. if (type==2)
  23252. sortAlgorithm = "heapSort";
  23253. else if (type == 1)
  23254. sortAlgorithm = "insertionSort";
  23255. else
  23256. sortAlgorithm = "quickSort";
  23257. DBGLOG("Testing %s activity", sortAlgorithm);
  23258. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort);
  23259. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23260. const char * test[] = { NULL, NULL };
  23261. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23262. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  23263. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23264. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23265. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23266. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23267. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23268. testActivity(activity, test, test);
  23269. testActivity(activity, test12345, test12345);
  23270. testActivity(activity, test54321, test12345);
  23271. testActivity(activity, test11111, test11111);
  23272. testActivity(activity, test11111_12345, test11111_12345);
  23273. testActivity(activity, test11111_54321, test11111_12345);
  23274. testActivity(activity, test54321_54321, test12345_12345);
  23275. // A few larger tests
  23276. char *input[2002];
  23277. char *output[2002];
  23278. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  23279. unsigned i;
  23280. // identical
  23281. for (i=0; i<2000; i++)
  23282. {
  23283. input[i] = new char[11];
  23284. output[i] = new char[11];
  23285. sprintf(input[i], "1");
  23286. sprintf(output[i], "1");
  23287. }
  23288. testActivity(activity, input, output);
  23289. // Ascending
  23290. for (i=0; i<2000; i++)
  23291. {
  23292. sprintf(input[i], "%04d", i);
  23293. sprintf(output[i], "%04d", i);
  23294. }
  23295. testActivity(activity, input, output);
  23296. // Almost sorted
  23297. for (i=0; i<20; i++)
  23298. {
  23299. unsigned h = i*100;
  23300. sprintf(input[h], "%04d", 1900-h);
  23301. }
  23302. testActivity(activity, input, output);
  23303. // Descending
  23304. for (i=0; i<2000; i++)
  23305. {
  23306. sprintf(input[i], "%04d", 1999-i);
  23307. sprintf(output[i], "%04d", i);
  23308. }
  23309. testActivity(activity, input, output);
  23310. // Random
  23311. for (i=0; i<2000; i++)
  23312. {
  23313. unsigned r = rand() % 1500;
  23314. sprintf(input[i], "%04d", r);
  23315. sprintf(output[i], "%04d", r);
  23316. }
  23317. qsort(output, 2000, sizeof(output[0]), compareFunc);
  23318. testActivity(activity, input, output);
  23319. #if 0
  23320. // Random
  23321. #define BIGSORTSIZE 1000000
  23322. char **linput = new char*[BIGSORTSIZE +2];
  23323. char **loutput = new char *[BIGSORTSIZE+2];
  23324. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  23325. for (i=0; i<BIGSORTSIZE; i++)
  23326. {
  23327. unsigned r = rand() % 15000;
  23328. linput[i] = loutput[i] = new char[11];
  23329. sprintf(linput[i], "%04d", r);
  23330. }
  23331. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  23332. testActivity(activity, linput, loutput);
  23333. for (i=0; i<BIGSORTSIZE; i++)
  23334. {
  23335. delete [] linput[i];
  23336. }
  23337. delete [] linput;
  23338. delete [] loutput;
  23339. #endif
  23340. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  23341. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  23342. factory->resetNodeProgressInfo();
  23343. if (type)
  23344. {
  23345. // Other than quicksort, it's supposed to be stable. Let's check that it is
  23346. // All sort identical
  23347. for (i=0; i<2000; i++)
  23348. {
  23349. sprintf(input[i], "1 %d", i);
  23350. sprintf(output[i], "1 %d", i);
  23351. }
  23352. testActivity(activity, input, output);
  23353. // Already sorted
  23354. for (i=0; i<2000; i++)
  23355. {
  23356. sprintf(input[i], "%04d %d", i / 10, i);
  23357. sprintf(output[i], "%04d %d", i / 10, i);
  23358. }
  23359. testActivity(activity, input, output);
  23360. // Reverse order
  23361. for (i=0; i<2000; i++)
  23362. {
  23363. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  23364. sprintf(output[i], "%04d %d", i / 10, i%10);
  23365. }
  23366. testActivity(activity, input, output);
  23367. }
  23368. for (i=0; i<2000; i++)
  23369. {
  23370. delete [] input[i];
  23371. delete [] output[i];
  23372. }
  23373. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  23374. }
  23375. void testQuickSort()
  23376. {
  23377. testSort(0);
  23378. }
  23379. void testInsertionSort()
  23380. {
  23381. testSort(1);
  23382. }
  23383. void testHeapSort()
  23384. {
  23385. testSort(2);
  23386. }
  23387. void testMerge()
  23388. {
  23389. DBGLOG("testMerge");
  23390. init();
  23391. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23392. factory->setInput(0,0,0);
  23393. factory->setInput(1,0,0);
  23394. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23395. const char * test[] = { NULL, NULL };
  23396. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23397. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  23398. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23399. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  23400. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23401. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23402. 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 };
  23403. testActivity(activity, test, test, test);
  23404. testActivity(activity, test12345, test, test12345);
  23405. testActivity(activity, test, test12345, test12345);
  23406. testActivity(activity, test12345, test12345, test1122334455);
  23407. testActivity(activity, test11111, test, test11111);
  23408. testActivity(activity, test, test11111, test11111);
  23409. testActivity(activity, test11111, test11111, test1111111111);
  23410. testActivity(activity, test11111_12345, test, test1111112345);
  23411. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  23412. // Should really test WHICH side gets kept...
  23413. // Should test with more than 2 inputs...
  23414. DBGLOG("testMerge done");
  23415. }
  23416. void testMergeDedup()
  23417. {
  23418. DBGLOG("testMergeDedup");
  23419. init();
  23420. MergeActivityTest::isDedup = true;
  23421. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23422. factory->setInput(0,0,0);
  23423. factory->setInput(1,0,0);
  23424. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23425. const char * test[] = { NULL, NULL };
  23426. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23427. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23428. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23429. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23430. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  23431. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  23432. testActivity(activity, test, test11111, test11111);
  23433. testActivity(activity, test, test, test);
  23434. testActivity(activity, test12345, test, test12345);
  23435. testActivity(activity, test, test12345, test12345);
  23436. testActivity(activity, test12345, test12345, test12345);
  23437. testActivity(activity, test11111_12345, test, test1111112345);
  23438. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  23439. // Should really test WHICH side gets kept...
  23440. // Should test with more than 2 inputs...
  23441. DBGLOG("testMergeDedup done");
  23442. }
  23443. void testMiscellaneous()
  23444. {
  23445. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  23446. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  23447. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  23448. ASSERT(sizeof(CJoinGroup) <= 120);
  23449. }
  23450. };
  23451. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  23452. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  23453. #endif