ccdserver.cpp 911 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "jlzw.hpp"
  27. #include "javahash.hpp"
  28. #include "javahash.tpp"
  29. #include "thorstep.ipp"
  30. #include "thorpipe.hpp"
  31. #include "thorfile.hpp"
  32. #include "eclhelper.hpp"
  33. #include "eclrtl_imp.hpp"
  34. #include "rtlfield_imp.hpp"
  35. #include "rtlds_imp.hpp"
  36. #include "rtlread_imp.hpp"
  37. #include "dafdesc.hpp"
  38. #include "dautils.hpp"
  39. namespace ccdserver_hqlhelper
  40. {
  41. #include "eclhelper_base.hpp"
  42. }
  43. #include "ccd.hpp"
  44. #include "ccdserver.hpp"
  45. #include "ccdcontext.hpp"
  46. #include "ccdactivities.hpp"
  47. #include "ccdquery.hpp"
  48. #include "ccdstate.hpp"
  49. #include "ccdqueue.ipp"
  50. #include "ccdsnmp.hpp"
  51. #include "ccddali.hpp"
  52. #include "jsmartsock.hpp"
  53. #include "dllserver.hpp"
  54. #include "workflow.hpp"
  55. #include "roxiemem.hpp"
  56. #include "roxierowbuff.hpp"
  57. #include "roxiehelper.hpp"
  58. #include "roxielmj.hpp"
  59. #include "roxierow.hpp"
  60. #include "thorplugin.hpp"
  61. #include "keybuild.hpp"
  62. #define MAX_HTTP_HEADERSIZE 8000
  63. #define MIN_PAYLOAD_SIZE 800
  64. #pragma warning(disable : 4355)
  65. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  66. #define PROBE
  67. #ifdef _DEBUG
  68. //#define FAKE_EXCEPTIONS
  69. //#define TRACE_JOINGROUPS
  70. //#define TRACE_SPLIT
  71. //#define _CHECK_HEAPSORT
  72. //#undef PARALLEL_EXECUTE
  73. //#define TRACE_SEEK_REQUESTS
  74. #endif
  75. using roxiemem::OwnedRoxieRow;
  76. using roxiemem::OwnedRoxieString;
  77. using roxiemem::OwnedConstRoxieRow;
  78. using roxiemem::IRowManager;
  79. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  80. #if _MSC_VER==1200
  81. #define protected public
  82. #endif
  83. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  84. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  85. inline void ReleaseRoxieRowSet(ConstPointerArray &data)
  86. {
  87. ForEachItemIn(idx, data)
  88. ReleaseRoxieRow(data.item(idx));
  89. data.kill();
  90. }
  91. //=================================================================================
  92. class RestartableThread : public CInterface
  93. {
  94. class MyThread : public Thread
  95. {
  96. Linked<RestartableThread> owner;
  97. public:
  98. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  99. {
  100. }
  101. virtual int run()
  102. {
  103. owner->started.signal();
  104. return owner->run();
  105. }
  106. };
  107. friend class MyThread;
  108. Semaphore started;
  109. Owned<MyThread> thread;
  110. CriticalSection crit;
  111. StringAttr name;
  112. public:
  113. RestartableThread(const char *_name) : name(_name)
  114. {
  115. }
  116. virtual void start(const char *namePrefix)
  117. {
  118. StringBuffer s(namePrefix);
  119. s.append(name);
  120. {
  121. CriticalBlock b(crit);
  122. assertex(!thread);
  123. thread.setown(new MyThread(this, s));
  124. thread->start();
  125. }
  126. started.wait();
  127. }
  128. virtual void join()
  129. {
  130. {
  131. Owned<Thread> tthread;
  132. {
  133. CriticalBlock b(crit);
  134. tthread.setown(thread.getClear());
  135. }
  136. if (tthread)
  137. tthread->join();
  138. }
  139. }
  140. virtual int run() = 0;
  141. };
  142. //================================================================================
  143. // default implementation - can be overridden for efficiency...
  144. bool IRoxieInput::nextGroup(ConstPointerArray & group)
  145. {
  146. // MORE - this should be replaced with a version that reads to a builder
  147. const void * next;
  148. while ((next = nextInGroup()) != NULL)
  149. group.append(next);
  150. if (group.ordinality())
  151. return true;
  152. return false;
  153. }
  154. void IRoxieInput::readAll(RtlLinkedDatasetBuilder &builder)
  155. {
  156. loop
  157. {
  158. const void *nextrec = nextInGroup();
  159. if (!nextrec)
  160. {
  161. nextrec = nextInGroup();
  162. if (!nextrec)
  163. break;
  164. builder.appendEOG();
  165. }
  166. builder.appendOwn(nextrec);
  167. }
  168. }
  169. inline const void * nextUngrouped(IRoxieInput * input)
  170. {
  171. const void * ret = input->nextInGroup();
  172. if (!ret)
  173. ret = input->nextInGroup();
  174. return ret;
  175. };
  176. //=================================================================================
  177. //The following don't link their arguments because that creates a circular reference
  178. //But I wish there was a better way
  179. class IndirectSlaveContext : public CInterface, implements IRoxieSlaveContext
  180. {
  181. public:
  182. IndirectSlaveContext(IRoxieSlaveContext * _ctx = NULL) : ctx(_ctx) {}
  183. IMPLEMENT_IINTERFACE
  184. void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  185. virtual ICodeContext *queryCodeContext()
  186. {
  187. return ctx->queryCodeContext();
  188. }
  189. virtual void checkAbort()
  190. {
  191. ctx->checkAbort();
  192. }
  193. virtual void notifyAbort(IException *E)
  194. {
  195. ctx->notifyAbort(E);
  196. }
  197. virtual IActivityGraph * queryChildGraph(unsigned id)
  198. {
  199. return ctx->queryChildGraph(id);
  200. }
  201. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  202. {
  203. ctx->noteChildGraph(id, childGraph) ;
  204. }
  205. virtual IRowManager &queryRowManager()
  206. {
  207. return ctx->queryRowManager();
  208. }
  209. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  210. {
  211. ctx->noteStatistic(kind, value);
  212. }
  213. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  214. {
  215. ctx->mergeStats(from);
  216. }
  217. virtual const CRuntimeStatisticCollection &queryStats() const
  218. {
  219. return ctx->queryStats();
  220. }
  221. virtual void CTXLOGva(const char *format, va_list args) const
  222. {
  223. ctx->CTXLOGva(format, args);
  224. }
  225. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  226. {
  227. ctx->CTXLOGa(category, prefix, text);
  228. }
  229. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  230. {
  231. ctx->logOperatorExceptionVA(E, file, line, format, args);
  232. }
  233. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  234. {
  235. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  236. }
  237. virtual void CTXLOGl(LogItem *log) const
  238. {
  239. ctx->CTXLOGl(log);
  240. }
  241. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  242. {
  243. return ctx->getLogPrefix(ret);
  244. }
  245. virtual unsigned queryTraceLevel() const
  246. {
  247. return ctx->queryTraceLevel();
  248. }
  249. virtual bool isIntercepted() const
  250. {
  251. return ctx->isIntercepted();
  252. }
  253. virtual bool isBlind() const
  254. {
  255. return ctx->isBlind();
  256. }
  257. virtual const QueryOptions &queryOptions() const
  258. {
  259. return ctx->queryOptions();
  260. }
  261. virtual void addSlavesReplyLen(unsigned len)
  262. {
  263. ctx->addSlavesReplyLen(len);
  264. }
  265. virtual const char *queryAuthToken()
  266. {
  267. return ctx->queryAuthToken();
  268. }
  269. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  270. {
  271. return ctx->resolveLFN(filename, isOpt);
  272. }
  273. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  274. {
  275. return ctx->createLFN(filename, overwrite, extend, clusters);
  276. }
  277. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  278. {
  279. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  280. }
  281. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  282. {
  283. return ctx->getLibraryGraph(extra, parentActivity);
  284. }
  285. virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed) const
  286. {
  287. ctx->noteProcessed(subgraphId, activityId, _idx, _processed);
  288. }
  289. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  290. {
  291. ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
  292. }
  293. virtual IProbeManager *queryProbeManager() const
  294. {
  295. return ctx->queryProbeManager();
  296. }
  297. virtual IDebuggableContext *queryDebugContext() const
  298. {
  299. return ctx->queryDebugContext();
  300. }
  301. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  302. {
  303. ctx->printResults(output, name, sequence);
  304. }
  305. virtual void setWUState(WUState state)
  306. {
  307. ctx->setWUState(state);
  308. }
  309. virtual bool checkWuAborted()
  310. {
  311. return ctx->checkWuAborted();
  312. }
  313. virtual IWorkUnit *updateWorkUnit() const
  314. {
  315. return ctx->updateWorkUnit();
  316. }
  317. virtual IConstWorkUnit *queryWorkUnit() const
  318. {
  319. return ctx->queryWorkUnit();
  320. }
  321. virtual IRoxieServerContext *queryServerContext()
  322. {
  323. return ctx->queryServerContext();
  324. }
  325. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  326. {
  327. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  328. }
  329. protected:
  330. IRoxieSlaveContext * ctx;
  331. };
  332. //=================================================================================
  333. #define RESULT_FLUSH_THRESHOLD 10000u
  334. #ifdef _DEBUG
  335. #define SOAP_SPLIT_THRESHOLD 100u
  336. #define SOAP_SPLIT_RESERVE 200u
  337. #else
  338. #define SOAP_SPLIT_THRESHOLD 64000u
  339. #define SOAP_SPLIT_RESERVE 65535u
  340. #endif
  341. //=================================================================================
  342. // General activity statistics
  343. static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  344. StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StKindNone);
  345. static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
  346. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  347. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  348. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  349. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  350. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  351. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  352. StNumDiskRejected, StKindNone);
  353. static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  354. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  355. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  356. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  357. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  358. StNumIndexRowsRead, StKindNone);
  359. static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  360. StNumDiskRejected, StKindNone);
  361. //=================================================================================
  362. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  363. {
  364. protected:
  365. IntArray dependencies; // things I am dependent on
  366. IntArray dependencyIndexes; // things I am dependent on
  367. IntArray dependencyControlIds; // things I am dependent on
  368. StringArray dependencyEdgeIds; // How to describe them to the debugger
  369. unsigned dependentCount; // things dependent on me
  370. mutable CriticalSection statsCrit;
  371. mutable __int64 processed;
  372. mutable __int64 started;
  373. mutable __int64 totalCycles;
  374. mutable __int64 localCycles;
  375. public:
  376. IMPLEMENT_IINTERFACE;
  377. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  378. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  379. {
  380. processed = 0;
  381. started = 0;
  382. totalCycles = 0;
  383. localCycles = 0;
  384. dependentCount = 0;
  385. }
  386. ~CRoxieServerActivityFactoryBase()
  387. {
  388. }
  389. StringBuffer &toString(StringBuffer &ret) const
  390. {
  391. return ret.appendf("%p", this);
  392. }
  393. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  394. {
  395. dependencies.append(_source);
  396. dependencyIndexes.append(_sourceIdx);
  397. dependencyControlIds.append(controlId);
  398. dependencyEdgeIds.append(edgeId);
  399. }
  400. virtual void noteDependent(unsigned target)
  401. {
  402. dependentCount++;
  403. }
  404. virtual IntArray &queryDependencies() { return dependencies; }
  405. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  406. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  407. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  408. virtual unsigned queryId() const { return id; }
  409. virtual unsigned querySubgraphId() const { return subgraphId; }
  410. virtual ThorActivityKind getKind() const { return kind; }
  411. virtual IOutputMetaData * queryOutputMeta() const
  412. {
  413. return meta;
  414. }
  415. virtual bool isSink() const
  416. {
  417. return false;
  418. }
  419. virtual bool isFunction() const
  420. {
  421. return false;
  422. }
  423. virtual bool isGraphInvariant() const
  424. {
  425. return false;
  426. }
  427. virtual IHThorArg &getHelper() const
  428. {
  429. return *helperFactory();
  430. }
  431. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  432. {
  433. arg.Release();
  434. throwUnexpected();
  435. }
  436. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  437. {
  438. CActivityFactory::mergeStats(from);
  439. }
  440. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  441. {
  442. dbgassertex(!_idx);
  443. if (_processed)
  444. {
  445. CriticalBlock b(statsCrit);
  446. processed += processed;
  447. }
  448. }
  449. virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
  450. {
  451. if (_totalCycles.totalCycles || _localCycles)
  452. {
  453. CriticalBlock b(statsCrit);
  454. dbgassertex(_totalCycles.totalCycles >= _localCycles);
  455. totalCycles += _totalCycles.totalCycles;
  456. localCycles += _localCycles;
  457. }
  458. CActivityFactory::mergeStats(fromStats);
  459. }
  460. virtual void noteStarted() const
  461. {
  462. CriticalBlock b(statsCrit);
  463. started ++;
  464. }
  465. virtual void noteStarted(unsigned idx) const
  466. {
  467. throwUnexpected(); // should be implemented/required by multiOutput cases only
  468. }
  469. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  470. {
  471. CriticalBlock b(statsCrit);
  472. if (output == 0)
  473. {
  474. putStatsValue(&edge, "count", "sum", processed);
  475. if (started)
  476. putStatsValue(&edge, "started", "sum", started);
  477. }
  478. else
  479. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  480. }
  481. virtual void getNodeProgressInfo(IPropertyTree &node) const
  482. {
  483. CActivityFactory::getNodeProgressInfo(node);
  484. CriticalBlock b(statsCrit);
  485. if (started)
  486. putStatsValue(&node, "_roxieStarted", "sum", started);
  487. if (totalCycles)
  488. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  489. if (localCycles)
  490. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  491. }
  492. virtual void resetNodeProgressInfo()
  493. {
  494. CActivityFactory::resetNodeProgressInfo();
  495. CriticalBlock b(statsCrit);
  496. processed = 0;
  497. started = 0;
  498. totalCycles = 0;
  499. localCycles = 0;
  500. }
  501. virtual void getActivityMetrics(StringBuffer &reply) const
  502. {
  503. CActivityFactory::getActivityMetrics(reply);
  504. CriticalBlock b(statsCrit);
  505. putStatsValue(reply, "_roxieStarted", "sum", started);
  506. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  507. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  508. }
  509. virtual unsigned __int64 queryLocalCycles() const
  510. {
  511. return localCycles;
  512. }
  513. virtual IQueryFactory &queryQueryFactory() const
  514. {
  515. return CActivityFactory::queryQueryFactory();
  516. }
  517. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  518. {
  519. return CActivityFactory::queryChildQuery(idx, id);
  520. }
  521. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  522. {
  523. CActivityFactory::addChildQuery(id, childQuery);
  524. }
  525. virtual void createChildQueries(IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx) const
  526. {
  527. ForEachItemIn(idx, childQueries)
  528. {
  529. childGraphs.append(*createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx));
  530. }
  531. }
  532. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs) const
  533. {
  534. ForEachItemIn(idx, childGraphs)
  535. {
  536. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  537. childGraphs.item(idx).onCreate(ctx, colocalArg);
  538. }
  539. }
  540. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  541. {
  542. unsigned match = childQueryIndexes.find(childId);
  543. assertex(match != NotFound);
  544. Owned<IActivityGraph> graph = createActivityGraph(NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx);
  545. graph->onCreate(ctx, colocalArg);
  546. return graph.getClear();
  547. }
  548. virtual IRoxieServerSideCache *queryServerSideCache() const
  549. {
  550. return NULL; // Activities that wish to support server-side caching will need to do better....
  551. }
  552. virtual bool getEnableFieldTranslation() const
  553. {
  554. throwUnexpected(); // only implemented by index-related subclasses
  555. }
  556. virtual IDefRecordMeta *queryActivityMeta() const
  557. {
  558. throwUnexpected(); // only implemented by index-related subclasses
  559. }
  560. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  561. {
  562. // Most activities have nothing to say...
  563. }
  564. virtual const StatisticsMapping &queryStatsMapping() const
  565. {
  566. return actStatistics; // Overridden by anyone that needs more
  567. }
  568. };
  569. class CRoxieServerMultiInputInfo
  570. {
  571. private:
  572. UnsignedArray inputs;
  573. UnsignedArray inputIndexes;
  574. public:
  575. void set(unsigned idx, unsigned source, unsigned sourceidx)
  576. {
  577. if (idx==inputs.length())
  578. {
  579. inputs.append(source);
  580. inputIndexes.append(sourceidx);
  581. }
  582. else
  583. {
  584. while (!inputs.isItem(idx))
  585. {
  586. inputs.append(0);
  587. inputIndexes.append(0);
  588. }
  589. inputs.replace(source, idx);
  590. inputIndexes.replace(sourceidx, idx);
  591. }
  592. }
  593. unsigned get(unsigned idx, unsigned &sourceidx) const
  594. {
  595. if (inputs.isItem(idx))
  596. {
  597. sourceidx = inputIndexes.item(idx);
  598. return inputs.item(idx);
  599. }
  600. else
  601. return (unsigned) -1;
  602. }
  603. inline unsigned ordinality() const { return inputs.ordinality(); }
  604. };
  605. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  606. {
  607. private:
  608. CRoxieServerMultiInputInfo inputs;
  609. public:
  610. IMPLEMENT_IINTERFACE;
  611. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  612. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  613. {
  614. }
  615. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  616. {
  617. inputs.set(idx, source, sourceidx);
  618. }
  619. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  620. {
  621. return inputs.get(idx, sourceidx);
  622. }
  623. virtual unsigned numInputs() const { return inputs.ordinality(); }
  624. };
  625. class CWrappedException : public CInterface, implements IException
  626. {
  627. Owned<IException> wrapped;
  628. ThorActivityKind kind;
  629. unsigned queryId;
  630. public:
  631. IMPLEMENT_IINTERFACE;
  632. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  633. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  634. {
  635. }
  636. virtual int errorCode() const { return wrapped->errorCode(); }
  637. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  638. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  639. };
  640. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  641. {
  642. protected:
  643. unsigned input;
  644. unsigned inputidx;
  645. public:
  646. IMPLEMENT_IINTERFACE;
  647. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  648. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  649. {
  650. input = (unsigned) -1;
  651. inputidx = 0;
  652. }
  653. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  654. {
  655. if (idx != 0)
  656. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  657. if (input != -1)
  658. 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__);
  659. input = source;
  660. inputidx = sourceidx;
  661. }
  662. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  663. {
  664. if (!idx)
  665. {
  666. sourceidx = inputidx;
  667. return input;
  668. }
  669. return (unsigned) -1;
  670. }
  671. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  672. };
  673. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  674. {
  675. protected:
  676. unsigned numOutputs;
  677. unsigned __int64 *processedArray;
  678. bool *startedArray;
  679. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  680. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  681. {
  682. numOutputs = 0;
  683. processedArray = NULL;
  684. startedArray = NULL;
  685. }
  686. ~CRoxieServerMultiOutputFactory()
  687. {
  688. delete [] processedArray;
  689. delete [] startedArray;
  690. }
  691. void setNumOutputs(unsigned num)
  692. {
  693. numOutputs = num;
  694. if (!num)
  695. num = 1; // Even sink activities like to track how many records they process
  696. processedArray = new unsigned __int64[num];
  697. startedArray = new bool[num];
  698. for (unsigned i = 0; i < num; i++)
  699. {
  700. processedArray[i] = 0;
  701. startedArray[i] = 0;
  702. }
  703. }
  704. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  705. {
  706. assertex(numOutputs ? idx < numOutputs : idx==0);
  707. CriticalBlock b(statsCrit);
  708. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  709. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  710. }
  711. virtual void resetNodeProgressInfo()
  712. {
  713. CRoxieServerActivityFactory::resetNodeProgressInfo();
  714. CriticalBlock b(statsCrit);
  715. for (unsigned i = 0; i < numOutputs; i++)
  716. {
  717. processedArray[i] = 0;
  718. startedArray[i] = 0;
  719. }
  720. }
  721. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  722. {
  723. assertex(numOutputs ? idx < numOutputs : idx==0);
  724. CriticalBlock b(statsCrit);
  725. processedArray[idx] += _processed;
  726. }
  727. virtual void noteStarted(unsigned idx) const
  728. {
  729. assertex(numOutputs ? idx < numOutputs : idx==0);
  730. CriticalBlock b(statsCrit);
  731. startedArray[idx] = true;
  732. }
  733. };
  734. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  735. {
  736. protected:
  737. bool isInternal;
  738. bool isRoot;
  739. unsigned usageCount;
  740. public:
  741. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  742. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  743. {
  744. usageCount = _usageCount;
  745. isRoot = _isRoot;
  746. isInternal = false; // filled in by derived class constructor
  747. }
  748. virtual bool isSink() const
  749. {
  750. //only a sink if a root activity
  751. 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?
  752. }
  753. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  754. {
  755. // 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
  756. // Just leave it blank is safest.
  757. }
  758. };
  759. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  760. const char *queryStateText(activityState state)
  761. {
  762. switch (state)
  763. {
  764. case STATEreset: return "reset";
  765. case STATEstarted: return "started";
  766. case STATEstopped: return "stopped";
  767. case STATEstarting: return "starting";
  768. default: return "unknown";
  769. }
  770. }
  771. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  772. class CParallelActivityExecutor : public CAsyncFor
  773. {
  774. public:
  775. unsigned parentExtractSize;
  776. const byte * parentExtract;
  777. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  778. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  779. void Do(unsigned i)
  780. {
  781. activities.item(i).execute(parentExtractSize, parentExtract);
  782. }
  783. private:
  784. IRoxieServerActivityCopyArray & activities;
  785. };
  786. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  787. {
  788. protected:
  789. IRoxieInput *input;
  790. IHThorArg &basehelper;
  791. IRoxieSlaveContext *ctx;
  792. const IRoxieServerActivityFactory *factory;
  793. IRoxieServerActivityCopyArray dependencies;
  794. IntArray dependencyIndexes;
  795. IntArray dependencyControlIds;
  796. IArrayOf<IActivityGraph> childGraphs;
  797. CachedOutputMetaData meta;
  798. IHThorArg *colocalParent;
  799. IEngineRowAllocator *rowAllocator;
  800. CriticalSection statecrit;
  801. mutable CRuntimeStatisticCollection stats;
  802. unsigned processed;
  803. ActivityTimeAccumulator totalCycles;
  804. cycle_t localCycles;
  805. unsigned activityId;
  806. activityState state;
  807. bool createPending;
  808. bool debugging;
  809. bool timeActivities;
  810. public:
  811. IMPLEMENT_IINTERFACE;
  812. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  813. : factory(_factory),
  814. basehelper(_factory->getHelper()),
  815. activityId(_factory->queryId()),
  816. stats(_factory ? factory->queryStatsMapping() : actStatistics)
  817. {
  818. input = NULL;
  819. ctx = NULL;
  820. meta.set(basehelper.queryOutputMeta());
  821. processed = 0;
  822. localCycles = 0;
  823. if (factory)
  824. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  825. state=STATEreset;
  826. rowAllocator = NULL;
  827. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  828. colocalParent = NULL;
  829. createPending = true;
  830. timeActivities = defaultTimeActivities;
  831. }
  832. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper), stats(allStatistics)
  833. {
  834. activityId = 0;
  835. input = NULL;
  836. ctx = NULL;
  837. meta.set(basehelper.queryOutputMeta());
  838. processed = 0;
  839. localCycles = 0;
  840. state=STATEreset;
  841. rowAllocator = NULL;
  842. debugging = false;
  843. colocalParent = NULL;
  844. createPending = true;
  845. timeActivities = defaultTimeActivities;
  846. }
  847. ~CRoxieServerActivity()
  848. {
  849. if (traceStartStop)
  850. {
  851. // There was an old comment here stating // Note- CTXLOG may not be safe
  852. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  853. // was released while activities still referenced it.
  854. // However these should now all be fixed
  855. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  856. if (watchActivityId && watchActivityId==activityId)
  857. {
  858. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  859. }
  860. }
  861. if (state!=STATEreset)
  862. {
  863. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  864. state = STATEreset; // bit pointless but there you go...
  865. }
  866. if (factory && !debugging)
  867. {
  868. if (processed)
  869. factory->noteProcessed(0, processed);
  870. factory->mergeActivityStats(stats, totalCycles, localCycles);
  871. }
  872. if (ctx)
  873. {
  874. if (processed)
  875. ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed);
  876. ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
  877. }
  878. basehelper.Release();
  879. ::Release(rowAllocator);
  880. }
  881. virtual const IRoxieContextLogger &queryLogCtx()const
  882. {
  883. return *this;
  884. }
  885. virtual void mergeStats(MemoryBuffer &buf)
  886. {
  887. stats.deserializeMerge(buf);
  888. }
  889. inline void createRowAllocator()
  890. {
  891. if (!rowAllocator)
  892. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  893. }
  894. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  895. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  896. {
  897. if (ctx)
  898. ctx->CTXLOGa(category, prefix, text);
  899. else
  900. DBGLOG("[%s] %s", prefix, text);
  901. }
  902. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  903. {
  904. if (ctx)
  905. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  906. else
  907. {
  908. StringBuffer ss;
  909. ss.appendf("[%s] ERROR", prefix);
  910. if (E)
  911. ss.append(": ").append(E->errorCode());
  912. if (file)
  913. ss.appendf(": %s(%d) ", file, line);
  914. if (E)
  915. E->errorMessage(ss.append(": "));
  916. if (format)
  917. {
  918. ss.append(": ").valist_appendf(format, args);
  919. }
  920. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  921. }
  922. }
  923. virtual void CTXLOGl(LogItem *log) const
  924. {
  925. if (ctx)
  926. ctx->CTXLOGl(log);
  927. else
  928. {
  929. assert(ctx);
  930. log->Release(); // Should never happen
  931. }
  932. }
  933. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  934. {
  935. stats.addStatistic(kind, value);
  936. }
  937. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  938. {
  939. stats.merge(from);
  940. }
  941. virtual const CRuntimeStatisticCollection &queryStats() const
  942. {
  943. return stats;
  944. }
  945. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  946. {
  947. if (ctx)
  948. ctx->getLogPrefix(ret);
  949. return ret.append('@').append(activityId);
  950. }
  951. virtual bool isIntercepted() const
  952. {
  953. return ctx ? ctx->isIntercepted() : false;
  954. }
  955. virtual bool isBlind() const
  956. {
  957. return ctx ? ctx->isBlind() : blindLogging;
  958. }
  959. virtual unsigned queryTraceLevel() const
  960. {
  961. if (ctx)
  962. return ctx->queryTraceLevel();
  963. else
  964. return traceLevel;
  965. }
  966. virtual bool isPassThrough()
  967. {
  968. return false;
  969. }
  970. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  971. {
  972. return ctx->resolveLFN(filename, isOpt);
  973. }
  974. virtual const IResolvedFile *queryVarFileInfo() const
  975. {
  976. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  977. return NULL;
  978. }
  979. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  980. {
  981. throwUnexpected(); // should be implemented in more derived class wherever needed
  982. }
  983. virtual IRoxieSlaveContext *queryContext()
  984. {
  985. return ctx;
  986. }
  987. virtual IRoxieServerActivity *queryActivity() { return this; }
  988. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  989. virtual bool needsAllocator() const { return false; }
  990. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  991. {
  992. ctx = _ctx;
  993. colocalParent = _colocalParent;
  994. createPending = true;
  995. if (needsAllocator())
  996. createRowAllocator();
  997. processed = 0;
  998. if (factory)
  999. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  1000. if (ctx)
  1001. timeActivities = ctx->queryOptions().timeActivities;
  1002. }
  1003. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1004. {
  1005. //This should only be called after onStart has been called on the helper
  1006. assertex(!createPending);
  1007. assertex(state==STATEstarted);
  1008. unsigned startlen = out.length();
  1009. basehelper.serializeCreateContext(out);
  1010. basehelper.serializeStartContext(out);
  1011. if (queryTraceLevel() > 10)
  1012. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1013. }
  1014. virtual void serializeExtra(MemoryBuffer &out) {}
  1015. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1016. {
  1017. CriticalBlock cb(statecrit);
  1018. if (state != STATEreset && state != STATEstarting)
  1019. {
  1020. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1021. }
  1022. state=STATEstarted;
  1023. #ifdef TRACE_STARTSTOP
  1024. if (traceStartStop)
  1025. {
  1026. CTXLOG("start %p %d", this, activityId);
  1027. if (watchActivityId && watchActivityId==activityId)
  1028. {
  1029. CTXLOG("WATCH: start %p %d", this, activityId);
  1030. }
  1031. }
  1032. #endif
  1033. executeDependencies(parentExtractSize, parentExtract, 0);
  1034. if (input)
  1035. input->start(parentExtractSize, parentExtract, paused);
  1036. ensureCreated();
  1037. basehelper.onStart(parentExtract, NULL);
  1038. if (factory)
  1039. factory->noteStarted();
  1040. }
  1041. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1042. {
  1043. //MORE: Create a filtered list and then use asyncfor
  1044. ForEachItemIn(idx, dependencies)
  1045. {
  1046. if (dependencyControlIds.item(idx) == controlId)
  1047. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1048. }
  1049. }
  1050. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1051. {
  1052. ForEachItemIn(idx, dependencies)
  1053. {
  1054. if (dependencyControlIds.item(idx) == controlId)
  1055. dependencies.item(idx).stop(false);
  1056. }
  1057. }
  1058. virtual unsigned __int64 queryTotalCycles() const
  1059. {
  1060. return totalCycles.totalCycles;
  1061. }
  1062. virtual unsigned __int64 queryLocalCycles() const
  1063. {
  1064. __int64 ret = totalCycles.totalCycles;
  1065. if (input) ret -= input->queryTotalCycles();
  1066. if (ret < 0)
  1067. ret = 0;
  1068. return ret;
  1069. }
  1070. virtual IRoxieInput *queryInput(unsigned idx) const
  1071. {
  1072. if (idx==0)
  1073. return input;
  1074. else
  1075. return NULL;
  1076. }
  1077. inline void ensureCreated()
  1078. {
  1079. if (createPending)
  1080. {
  1081. createPending = false;
  1082. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1083. }
  1084. }
  1085. inline void stop(bool aborting)
  1086. {
  1087. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1088. if (state != STATEstopped)
  1089. {
  1090. CriticalBlock cb(statecrit);
  1091. if (state != STATEstopped)
  1092. {
  1093. #ifdef TRACE_STARTSTOP
  1094. if (traceStartStop)
  1095. {
  1096. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1097. if (watchActivityId && watchActivityId==activityId)
  1098. {
  1099. CTXLOG("WATCH: stop %p %d", this, activityId);
  1100. }
  1101. }
  1102. #endif
  1103. state=STATEstopped;
  1104. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1105. ForEachItemIn(idx, dependencies)
  1106. {
  1107. if (dependencyControlIds.item(idx) == 0)
  1108. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1109. }
  1110. if (input)
  1111. input->stop(aborting);
  1112. }
  1113. }
  1114. }
  1115. inline void reset()
  1116. {
  1117. if (state != STATEreset)
  1118. {
  1119. CriticalBlock cb(statecrit);
  1120. if (state != STATEreset)
  1121. {
  1122. if (state==STATEstarted || state==STATEstarting)
  1123. {
  1124. if (traceStartStop || traceLevel > 2)
  1125. CTXLOG("STATE: activity %d reset without stop", activityId);
  1126. stop(false);
  1127. }
  1128. state = STATEreset;
  1129. #ifdef TRACE_STARTSTOP
  1130. if (traceStartStop)
  1131. {
  1132. CTXLOG("reset %p %d", this, activityId);
  1133. if (watchActivityId && watchActivityId==activityId)
  1134. {
  1135. CTXLOG("WATCH: reset %p %d", this, activityId);
  1136. }
  1137. }
  1138. #endif
  1139. ForEachItemIn(idx, dependencies)
  1140. dependencies.item(idx).reset();
  1141. localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
  1142. if (input)
  1143. input->reset();
  1144. }
  1145. }
  1146. }
  1147. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1148. {
  1149. dependencies.append(source);
  1150. dependencyIndexes.append(sourceIdx);
  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 void stopSink(unsigned idx)
  1167. {
  1168. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1169. }
  1170. virtual __int64 evaluate()
  1171. {
  1172. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1173. }
  1174. virtual IRoxieInput * querySelectOutput(unsigned id)
  1175. {
  1176. return NULL;
  1177. }
  1178. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1179. {
  1180. return false;
  1181. }
  1182. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1183. {
  1184. assertex(!idx);
  1185. input = _in;
  1186. }
  1187. virtual IRoxieInput *queryOutput(unsigned idx)
  1188. {
  1189. if (idx == (unsigned) -1)
  1190. idx = 0;
  1191. return idx ? NULL : this;
  1192. }
  1193. virtual IOutputMetaData *queryOutputMeta() const
  1194. {
  1195. return meta.queryOriginal();
  1196. }
  1197. virtual unsigned queryId() const
  1198. {
  1199. return activityId;
  1200. }
  1201. virtual unsigned querySubgraphId() const
  1202. {
  1203. return factory->querySubgraphId();
  1204. }
  1205. virtual void checkAbort()
  1206. {
  1207. ctx->checkAbort();
  1208. }
  1209. IException *makeWrappedException(IException *e)
  1210. {
  1211. StringBuffer msg;
  1212. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1213. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1214. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1215. return e;
  1216. else
  1217. return new CWrappedException(e, activityKind, activityId);
  1218. }
  1219. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1220. {
  1221. }
  1222. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1223. {
  1224. }
  1225. virtual void resetOutputsUsed()
  1226. {
  1227. }
  1228. virtual void noteOutputUsed()
  1229. {
  1230. }
  1231. virtual IRoxieServerSideCache *queryServerSideCache() const
  1232. {
  1233. return factory->queryServerSideCache();
  1234. }
  1235. virtual const IRoxieServerActivityFactory *queryFactory() const
  1236. {
  1237. return factory;
  1238. }
  1239. inline ThorActivityKind getKind() const
  1240. {
  1241. return factory->getKind();
  1242. }
  1243. inline bool isSink() const
  1244. {
  1245. return (factory != NULL) && factory->isSink();
  1246. }
  1247. };
  1248. //=====================================================================================================
  1249. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1250. {
  1251. protected:
  1252. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1253. bool prefiltered;
  1254. bool eof;
  1255. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1256. {
  1257. prefiltered = !any;
  1258. eof = prefiltered;
  1259. if (!prefiltered)
  1260. input->start(parentExtractSize, parentExtract, false);
  1261. else
  1262. {
  1263. if (traceStartStop)
  1264. CTXLOG("lateStart activity stopping input early as prefiltered");
  1265. input->stop(false);
  1266. }
  1267. }
  1268. public:
  1269. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1270. : CRoxieServerActivity(_factory, _probeManager)
  1271. {
  1272. input = NULL;
  1273. prefiltered = false;
  1274. eof = false;
  1275. }
  1276. virtual void stop(bool aborting)
  1277. {
  1278. if (!prefiltered)
  1279. {
  1280. input->stop(aborting);
  1281. }
  1282. else if (traceStartStop)
  1283. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1284. CRoxieServerActivity::stop(aborting);
  1285. }
  1286. virtual IRoxieInput *queryInput(unsigned idx) const
  1287. {
  1288. if (idx==0)
  1289. return input;
  1290. else
  1291. return NULL;
  1292. }
  1293. virtual void reset()
  1294. {
  1295. CRoxieServerActivity::reset();
  1296. input->reset();
  1297. prefiltered = false;
  1298. }
  1299. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1300. {
  1301. assertex(!idx);
  1302. input = _in;
  1303. }
  1304. };
  1305. //=====================================================================================================
  1306. atomic_t nextInstanceId;
  1307. extern unsigned getNextInstanceId()
  1308. {
  1309. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1310. }
  1311. atomic_t nextRuid;
  1312. ruid_t getNextRuid()
  1313. {
  1314. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1315. while (ret < RUID_FIRST)
  1316. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1317. return ret;
  1318. }
  1319. void setStartRuid(unsigned restarts)
  1320. {
  1321. atomic_set(&nextRuid, restarts * 0x10000);
  1322. atomic_set(&nextInstanceId, restarts * 10000);
  1323. }
  1324. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1325. class LimitSkipException : public CInterface, public IException
  1326. {
  1327. int code;
  1328. public:
  1329. LimitSkipException(int _code) { code = _code; }
  1330. IMPLEMENT_IINTERFACE;
  1331. virtual int errorCode() const { return code; }
  1332. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1333. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1334. };
  1335. IException *makeLimitSkipException(bool isKeyed)
  1336. {
  1337. // We need to make sure what we throw is IException not something derived from it....
  1338. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1339. }
  1340. //=================================================================================
  1341. interface IRecordPullerCallback : extends IExceptionHandler
  1342. {
  1343. virtual void processRow(const void *row) = 0;
  1344. virtual void processEOG() = 0;
  1345. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1346. virtual void processDone() = 0;
  1347. };
  1348. class RecordPullerThread : public RestartableThread
  1349. {
  1350. protected:
  1351. IRoxieInput *input;
  1352. IRecordPullerCallback *helper;
  1353. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1354. bool groupAtOnce, eof, eog;
  1355. CriticalSection crit;
  1356. public:
  1357. RecordPullerThread(bool _groupAtOnce)
  1358. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1359. {
  1360. input = NULL;
  1361. helper = NULL;
  1362. eof = eog = FALSE;
  1363. }
  1364. inline unsigned __int64 queryTotalCycles() const
  1365. {
  1366. return input->queryTotalCycles();
  1367. }
  1368. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1369. {
  1370. helper = _helper;
  1371. input = _input;
  1372. }
  1373. IRoxieInput *queryInput() const
  1374. {
  1375. return input;
  1376. }
  1377. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1378. {
  1379. eof = false;
  1380. eog = false;
  1381. input->start(parentExtractSize, parentExtract, paused);
  1382. try
  1383. {
  1384. if (preload && !paused)
  1385. {
  1386. if (traceLevel > 4)
  1387. DBGLOG("Preload fetching first %d records", preload);
  1388. if (groupAtOnce)
  1389. pullGroups(preload);
  1390. else
  1391. pullRecords(preload);
  1392. }
  1393. if (eof)
  1394. {
  1395. if (traceLevel > 4)
  1396. DBGLOG("No need to start puller after preload");
  1397. helper->processDone();
  1398. }
  1399. else
  1400. {
  1401. if (!noThread)
  1402. {
  1403. StringBuffer logPrefix("[");
  1404. if (ctx) ctx->getLogPrefix(logPrefix);
  1405. logPrefix.append("] ");
  1406. RestartableThread::start(logPrefix);
  1407. started.wait();
  1408. }
  1409. }
  1410. }
  1411. catch (IException *e)
  1412. {
  1413. helper->fireException(e);
  1414. }
  1415. catch (...)
  1416. {
  1417. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1418. }
  1419. }
  1420. void stop(bool aborting)
  1421. {
  1422. if (traceStartStop)
  1423. DBGLOG("RecordPullerThread::stop");
  1424. {
  1425. 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.
  1426. input->stop(aborting);
  1427. }
  1428. RestartableThread::join();
  1429. }
  1430. void reset()
  1431. {
  1432. input->reset();
  1433. }
  1434. virtual int run()
  1435. {
  1436. started.signal();
  1437. try
  1438. {
  1439. if (groupAtOnce)
  1440. pullGroups((unsigned) -1);
  1441. else
  1442. pullRecords((unsigned) -1);
  1443. helper->processDone();
  1444. }
  1445. catch (IException *e)
  1446. {
  1447. helper->fireException(e);
  1448. }
  1449. catch (...)
  1450. {
  1451. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1452. }
  1453. return 0;
  1454. }
  1455. void done()
  1456. {
  1457. helper->processDone();
  1458. }
  1459. bool pullRecords(unsigned preload)
  1460. {
  1461. if (eof)
  1462. return false;
  1463. while (preload)
  1464. {
  1465. const void * row;
  1466. {
  1467. CriticalBlock c(crit); // See comments in stop for why this is needed
  1468. row = input->nextInGroup();
  1469. }
  1470. if (row)
  1471. {
  1472. eog = false;
  1473. helper->processRow(row);
  1474. }
  1475. else if (!eog)
  1476. {
  1477. helper->processEOG();
  1478. eog = true;
  1479. }
  1480. else
  1481. {
  1482. eof = true;
  1483. return false;
  1484. }
  1485. if (preload != (unsigned) -1)
  1486. preload--;
  1487. }
  1488. return true;
  1489. }
  1490. void pullGroups(unsigned preload)
  1491. {
  1492. ConstPointerArray thisGroup;
  1493. unsigned rowsDone = 0;
  1494. while (preload && !eof)
  1495. {
  1496. const void *row;
  1497. {
  1498. CriticalBlock c(crit);
  1499. row = input->nextInGroup();
  1500. }
  1501. if (row)
  1502. {
  1503. thisGroup.append(row);
  1504. rowsDone++;
  1505. }
  1506. else if (thisGroup.length())
  1507. {
  1508. helper->processGroup(thisGroup);
  1509. thisGroup.kill();
  1510. if (preload != (unsigned) -1)
  1511. {
  1512. if (preload > rowsDone)
  1513. preload -= rowsDone;
  1514. else
  1515. break;
  1516. }
  1517. rowsDone = 0;
  1518. }
  1519. else
  1520. {
  1521. eof = true;
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. };
  1527. //=================================================================================
  1528. #define READAHEAD_SIZE 1000
  1529. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1530. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1531. {
  1532. QueueOf<const void, true> buffer;
  1533. InterruptableSemaphore ready;
  1534. InterruptableSemaphore space;
  1535. CriticalSection crit;
  1536. bool eof;
  1537. bool disabled;
  1538. RecordPullerThread puller;
  1539. unsigned preload;
  1540. cycle_t totalCycles;
  1541. IRoxieSlaveContext *ctx;
  1542. bool timeActivities;
  1543. public:
  1544. IMPLEMENT_IINTERFACE;
  1545. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1546. {
  1547. eof = false;
  1548. disabled = false;
  1549. ctx = NULL;
  1550. totalCycles = 0;
  1551. timeActivities = defaultTimeActivities;
  1552. }
  1553. void onCreate(IRoxieSlaveContext *_ctx)
  1554. {
  1555. ctx = _ctx;
  1556. disabled = (ctx->queryDebugContext() != NULL);
  1557. if (ctx)
  1558. timeActivities = ctx->queryOptions().timeActivities;
  1559. }
  1560. virtual IRoxieServerActivity *queryActivity()
  1561. {
  1562. return puller.queryInput()->queryActivity();
  1563. }
  1564. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1565. {
  1566. return puller.queryInput()->queryIndexReadActivity();
  1567. }
  1568. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1569. {
  1570. eof = false;
  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. SimpleActivityTimer t(totalCycles, timeActivities);
  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.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1742. else
  1743. ret = totalCycles.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.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. unsigned numOutputs;
  1856. bool executed;
  1857. bool *stopped;
  1858. CriticalSection ecrit;
  1859. Owned<IException> exception;
  1860. public:
  1861. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  1862. : CRoxieServerActivity(_factory, _probeManager), numOutputs(_numOutputs)
  1863. {
  1864. executed = false;
  1865. stopped = new bool[numOutputs];
  1866. for (unsigned s = 0; s < numOutputs; s++)
  1867. stopped[s] = false;
  1868. }
  1869. ~CRoxieServerInternalSinkActivity()
  1870. {
  1871. delete [] stopped;
  1872. }
  1873. virtual void reset()
  1874. {
  1875. for (unsigned s = 0; s < numOutputs; s++)
  1876. stopped[s] = false;
  1877. executed = false;
  1878. exception.clear();
  1879. CRoxieServerActivity::reset();
  1880. }
  1881. virtual IRoxieInput *queryOutput(unsigned idx)
  1882. {
  1883. return NULL;
  1884. }
  1885. virtual void stopSink(unsigned outputIdx)
  1886. {
  1887. if (!stopped[outputIdx])
  1888. {
  1889. stopped[outputIdx] = true;
  1890. for (unsigned s = 0; s < numOutputs; s++)
  1891. if (!stopped[s])
  1892. return;
  1893. stop(false); // all outputs stopped - stop parent.
  1894. }
  1895. }
  1896. virtual const void *nextInGroup()
  1897. {
  1898. throwUnexpected(); // I am nobody's input
  1899. }
  1900. virtual void onExecute() = 0;
  1901. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1902. {
  1903. CriticalBlock b(ecrit);
  1904. if (exception)
  1905. throw exception.getLink();
  1906. if (!executed)
  1907. {
  1908. try
  1909. {
  1910. start(parentExtractSize, parentExtract, false);
  1911. {
  1912. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  1913. onExecute();
  1914. }
  1915. stop(false);
  1916. executed = true;
  1917. }
  1918. catch (IException *E)
  1919. {
  1920. exception.set(E); // (or maybe makeWrappedException?)
  1921. stop(true);
  1922. throw;
  1923. }
  1924. catch (...)
  1925. {
  1926. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1927. stop(true);
  1928. throw;
  1929. }
  1930. }
  1931. }
  1932. };
  1933. //=================================================================================
  1934. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1935. {
  1936. protected:
  1937. Owned<IMessageResult> result;
  1938. Owned<IRoxieQueryPacket> packet;
  1939. Linked<IRoxieServerQueryPacket> continuation;
  1940. unsigned hash;
  1941. unsigned seq;
  1942. unsigned lastDebugSequence;
  1943. Owned<IRoxieQueryPacket> lastDebugResponse;
  1944. ILRUChain *prev;
  1945. ILRUChain *next;
  1946. bool delayed;
  1947. public:
  1948. IMPLEMENT_IINTERFACE;
  1949. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1950. {
  1951. hash = 0;
  1952. seq = 0;
  1953. prev = NULL;
  1954. next = NULL;
  1955. delayed = false;
  1956. lastDebugSequence = 0;
  1957. }
  1958. virtual IRoxieQueryPacket *queryPacket() const
  1959. {
  1960. return packet;
  1961. }
  1962. virtual bool isContinuation() const
  1963. {
  1964. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1965. }
  1966. virtual bool isDelayed() const
  1967. {
  1968. return delayed;
  1969. }
  1970. virtual bool isEnd() const
  1971. {
  1972. return false;
  1973. }
  1974. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1975. {
  1976. return false;
  1977. }
  1978. virtual bool hasResult() const
  1979. {
  1980. return result != NULL;
  1981. }
  1982. virtual bool hasContinuation() const
  1983. {
  1984. return continuation != NULL;
  1985. }
  1986. virtual void setDelayed(bool _delayed)
  1987. {
  1988. delayed = _delayed;
  1989. }
  1990. virtual void setPacket(IRoxieQueryPacket *_packet)
  1991. {
  1992. packet.setown(_packet);
  1993. }
  1994. virtual void setSequence(unsigned _seq)
  1995. {
  1996. assertex(!IsShared());
  1997. seq = _seq;
  1998. }
  1999. virtual unsigned getSequence() const
  2000. {
  2001. return seq;
  2002. }
  2003. IMessageResult *getResult()
  2004. {
  2005. return result.getLink();
  2006. }
  2007. IMessageResult *queryResult()
  2008. {
  2009. return result;
  2010. }
  2011. void setResult(IMessageResult *r)
  2012. {
  2013. result.setown(r);
  2014. }
  2015. IRoxieServerQueryPacket *queryContinuation()
  2016. {
  2017. return continuation;
  2018. }
  2019. void setContinuation(IRoxieServerQueryPacket *c)
  2020. {
  2021. continuation.setown(c);
  2022. }
  2023. virtual unsigned queryHash() const
  2024. {
  2025. return hash;
  2026. }
  2027. virtual void setHash(unsigned _hash)
  2028. {
  2029. hash = _hash;
  2030. }
  2031. virtual ILRUChain *queryPrev() const { return prev; }
  2032. virtual ILRUChain *queryNext() const { return next; }
  2033. virtual void setPrev(ILRUChain *p) { prev = p; }
  2034. virtual void setNext(ILRUChain *n) { next = n; }
  2035. virtual void unchain()
  2036. {
  2037. if (prev && next)
  2038. {
  2039. prev->setNext(next);
  2040. next->setPrev(prev);
  2041. }
  2042. next = NULL;
  2043. prev = NULL;
  2044. }
  2045. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2046. {
  2047. if (sequence == lastDebugSequence)
  2048. return lastDebugResponse.getLink();
  2049. else if (sequence > lastDebugSequence)
  2050. {
  2051. lastDebugResponse.clear();
  2052. return NULL;
  2053. }
  2054. else
  2055. throwUnexpected();
  2056. }
  2057. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2058. {
  2059. lastDebugSequence = sequence;
  2060. lastDebugResponse.set(response);
  2061. }
  2062. };
  2063. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2064. {
  2065. public:
  2066. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2067. {
  2068. }
  2069. virtual bool isEnd() const
  2070. {
  2071. return true;
  2072. }
  2073. };
  2074. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2075. {
  2076. unsigned __int64 rowLimit;
  2077. unsigned __int64 keyedLimit;
  2078. unsigned __int64 stopAfter;
  2079. public:
  2080. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2081. {
  2082. rowLimit = _rowLimit;
  2083. keyedLimit = _keyedLimit;
  2084. stopAfter = _stopAfter;
  2085. }
  2086. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2087. {
  2088. _rowLimit = rowLimit;
  2089. _keyedLimit = keyedLimit;
  2090. _stopAfter = stopAfter;
  2091. return true;
  2092. }
  2093. };
  2094. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2095. {
  2096. protected:
  2097. unsigned cacheTableSize;
  2098. unsigned cacheTableSpace;
  2099. IRoxieServerQueryPacket **cacheTable;
  2100. mutable ILRUChain *prev;
  2101. mutable ILRUChain *next;
  2102. mutable CriticalSection crit;
  2103. virtual ILRUChain *queryPrev() const { return prev; }
  2104. virtual ILRUChain *queryNext() const { return next; }
  2105. virtual void setPrev(ILRUChain *p) { prev = p; }
  2106. virtual void setNext(ILRUChain *n) { next = n; }
  2107. virtual void unchain()
  2108. {
  2109. prev->setNext(next);
  2110. next->setPrev(prev);
  2111. next = NULL;
  2112. prev = NULL;
  2113. }
  2114. void moveToHead(IRoxieServerQueryPacket *mru)
  2115. {
  2116. mru->unchain();
  2117. mru->setNext(next);
  2118. next->setPrev(mru);
  2119. mru->setPrev(this);
  2120. next = mru;
  2121. }
  2122. IRoxieServerQueryPacket *removeLRU()
  2123. {
  2124. if (next==this)
  2125. assertex(next != this);
  2126. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2127. goer->unchain(); // NOTE - this will modify the value of next
  2128. return goer;
  2129. }
  2130. void removeEntry(IRoxieServerQueryPacket *goer)
  2131. {
  2132. unsigned v = goer->queryHash() % cacheTableSize;
  2133. loop
  2134. {
  2135. IRoxieServerQueryPacket *found = cacheTable[v];
  2136. assertex(found);
  2137. if (found == goer)
  2138. {
  2139. cacheTable[v] = NULL;
  2140. unsigned vn = v;
  2141. loop
  2142. {
  2143. vn++;
  2144. if (vn==cacheTableSize) vn = 0;
  2145. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2146. if (!found2)
  2147. break;
  2148. unsigned vm = found2->queryHash() % cacheTableSize;
  2149. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2150. {
  2151. cacheTable[v] = found2;
  2152. v = vn;
  2153. cacheTable[v] = NULL;
  2154. }
  2155. }
  2156. cacheTableSpace++;
  2157. break;
  2158. }
  2159. v++;
  2160. if (v==cacheTableSize)
  2161. v = 0;
  2162. }
  2163. goer->Release();
  2164. }
  2165. public:
  2166. CRoxieServerSideCache(unsigned _cacheSize)
  2167. {
  2168. cacheTableSize = (_cacheSize*4)/3;
  2169. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2170. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2171. cacheTableSpace = _cacheSize;
  2172. prev = this;
  2173. next = this;
  2174. }
  2175. ~CRoxieServerSideCache()
  2176. {
  2177. for (unsigned i = 0; i < cacheTableSize; i++)
  2178. {
  2179. ::Release(cacheTable[i]);
  2180. }
  2181. delete [] cacheTable;
  2182. }
  2183. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2184. {
  2185. unsigned hash = p->hash();
  2186. unsigned et = hash % cacheTableSize;
  2187. if (traceServerSideCache)
  2188. {
  2189. StringBuffer s;
  2190. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2191. }
  2192. CriticalBlock b(crit);
  2193. loop
  2194. {
  2195. IRoxieServerQueryPacket *found = cacheTable[et];
  2196. if (!found)
  2197. return NULL;
  2198. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2199. {
  2200. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2201. if (traceServerSideCache)
  2202. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2203. logctx.noteStatistic(StNumServerCacheHits, 1);
  2204. return NULL;
  2205. // Because IMessageResult cannot be replayed, this scheme is flawed. I'm leaving the code here just as a stats gatherer to see how useful it would have been....
  2206. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2207. //ret->setResult(found->getResult());
  2208. //return ret;
  2209. }
  2210. et++;
  2211. if (et == cacheTableSize)
  2212. et = 0;
  2213. }
  2214. }
  2215. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2216. {
  2217. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2218. {
  2219. unsigned hash = out->queryPacket()->hash();
  2220. out->setHash(hash);
  2221. unsigned et = hash % cacheTableSize;
  2222. if (traceServerSideCache)
  2223. {
  2224. StringBuffer s;
  2225. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2226. }
  2227. CriticalBlock b(crit);
  2228. loop
  2229. {
  2230. IRoxieServerQueryPacket *found = cacheTable[et];
  2231. if (!found)
  2232. {
  2233. if (cacheTableSpace)
  2234. {
  2235. out->setResult(LINK(in));
  2236. cacheTable[et] = LINK(out);
  2237. cacheTableSpace--;
  2238. moveToHead(out);
  2239. break;
  2240. }
  2241. else
  2242. {
  2243. IRoxieServerQueryPacket *goer = removeLRU();
  2244. removeEntry(goer);
  2245. et = hash % cacheTableSize;
  2246. continue;
  2247. }
  2248. }
  2249. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2250. {
  2251. moveToHead(found);
  2252. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2253. // multiple copies of a slave query are in-flight at once.
  2254. }
  2255. et++;
  2256. if (et == cacheTableSize)
  2257. et = 0;
  2258. }
  2259. }
  2260. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2261. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2262. }
  2263. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2264. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2265. // more than make up for it
  2266. };
  2267. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2268. {
  2269. ConstPointerArray &data;
  2270. Linked<IMessageResult> result;
  2271. public:
  2272. IMPLEMENT_IINTERFACE;
  2273. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2274. : data(_data), result(_result)
  2275. {
  2276. }
  2277. virtual bool atEOF() const
  2278. {
  2279. return data.length()==0;
  2280. }
  2281. virtual bool isSerialized() const
  2282. {
  2283. return false;
  2284. }
  2285. virtual const void * getNext(int length)
  2286. {
  2287. if (!data.length())
  2288. return NULL;
  2289. const void *ret = data.item(0);
  2290. data.remove(0);
  2291. return ret;
  2292. }
  2293. };
  2294. // MORE - should possibly move more over to the lazy version used in indexread?
  2295. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2296. {
  2297. ConstPointerArray data;
  2298. IRowManager &rowManager;
  2299. bool variableSize;
  2300. public:
  2301. IMPLEMENT_IINTERFACE;
  2302. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2303. {
  2304. }
  2305. ~CRowArrayMessageResult()
  2306. {
  2307. ReleaseRoxieRowSet(data);
  2308. }
  2309. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2310. {
  2311. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2312. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2313. }
  2314. virtual const void *getMessageHeader(unsigned &length) const
  2315. {
  2316. throwUnexpected(); // should never get called - I don't have a header available
  2317. length = 0;
  2318. return NULL;
  2319. }
  2320. virtual const void *getMessageMetadata(unsigned &length) const
  2321. {
  2322. length = 0;
  2323. return NULL;
  2324. }
  2325. virtual void discard() const
  2326. {
  2327. throwUnexpected();
  2328. }
  2329. void append(const void *row)
  2330. {
  2331. data.append(row);
  2332. }
  2333. };
  2334. void throwRemoteException(IMessageUnpackCursor *extra)
  2335. {
  2336. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2337. if (rowlen)
  2338. {
  2339. char *xml = (char *) extra->getNext(*rowlen);
  2340. ReleaseRoxieRow(rowlen);
  2341. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2342. ReleaseRoxieRow(xml);
  2343. unsigned code = p->getPropInt("Code", 0);
  2344. const char *msg = p->queryProp("Message");
  2345. if (!msg)
  2346. msg = xml;
  2347. throw MakeStringException(code, "%s", msg);
  2348. }
  2349. throwUnexpected();
  2350. }
  2351. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2352. {
  2353. friend class CRemoteResultMerger;
  2354. class CRemoteResultMerger
  2355. {
  2356. class HeapEntry : public CInterface
  2357. {
  2358. private:
  2359. CRemoteResultAdaptor &adaptor;
  2360. IMessageUnpackCursor *cursor;
  2361. public:
  2362. const void *current;
  2363. bool isLast;
  2364. bool lastIsComplete;
  2365. IRoxieServerQueryPacket *packet;
  2366. unsigned seq;
  2367. public:
  2368. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2369. {
  2370. cursor = _cursor;
  2371. lastIsComplete = _lastIsComplete;
  2372. return next();
  2373. }
  2374. public:
  2375. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2376. {
  2377. cursor = NULL;
  2378. current = NULL;
  2379. isLast = false;
  2380. lastIsComplete = true;
  2381. }
  2382. ~HeapEntry()
  2383. {
  2384. ::Release(packet);
  2385. ::Release(cursor);
  2386. ReleaseRoxieRow(current);
  2387. }
  2388. bool isCompleteMatch() const
  2389. {
  2390. if (!isLast || lastIsComplete)
  2391. return true;
  2392. else
  2393. return false;
  2394. }
  2395. const void *next()
  2396. {
  2397. if (cursor)
  2398. {
  2399. ReleaseClearRoxieRow(current);
  2400. current = adaptor.getRow(cursor);
  2401. isLast = cursor->atEOF();
  2402. if (!current)
  2403. {
  2404. cursor->Release();
  2405. cursor = NULL;
  2406. }
  2407. }
  2408. return current;
  2409. }
  2410. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2411. {
  2412. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2413. unsigned skipped = 0;
  2414. loop
  2415. {
  2416. int c = compare->docompare(current, seek, numFields);
  2417. //If larger than the seek values, then we may be allowed to return an inexact match,
  2418. //if equal then it is required to be an exact match,
  2419. if (c > 0)
  2420. {
  2421. if (!requireExactMatch || isCompleteMatch())
  2422. break;
  2423. }
  2424. else if ((c == 0) && isCompleteMatch())
  2425. break;
  2426. skipped++;
  2427. if (!next())
  2428. break;
  2429. }
  2430. return skipped;
  2431. }
  2432. };
  2433. CRemoteResultAdaptor &adaptor;
  2434. CIArrayOf<HeapEntry> heapEntries;
  2435. UnsignedArray heap;
  2436. IRowManager *rowManager;
  2437. unsigned numPending;
  2438. unsigned numFields;
  2439. bool endSeen;
  2440. bool remakePending;
  2441. IRangeCompare *compare;
  2442. bool deferredContinuation;
  2443. inline int doCompare(unsigned l, unsigned r)
  2444. {
  2445. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2446. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2447. return ret;
  2448. }
  2449. void makeHeap()
  2450. {
  2451. /* Permute blocks to establish the heap property
  2452. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2453. The children of p must both be greater than or equal to p
  2454. The parent of a child c is given by p = (c-1)/2
  2455. */
  2456. unsigned i;
  2457. unsigned n = heap.length();
  2458. unsigned *s = heap.getArray();
  2459. for (i=1; i<n; i++)
  2460. {
  2461. unsigned r = s[i];
  2462. int c = i; /* child */
  2463. while (c > 0)
  2464. {
  2465. int p = (c-1)/2; /* parent */
  2466. if ( doCompare( s[c], s[p] ) >= 0 )
  2467. break;
  2468. s[c] = s[p];
  2469. s[p] = r;
  2470. c = p;
  2471. }
  2472. }
  2473. remakePending = false;
  2474. }
  2475. void remakeHeap()
  2476. {
  2477. /* The row associated with block[0] will have changed
  2478. This code restores the heap property
  2479. */
  2480. unsigned p = 0; /* parent */
  2481. unsigned n = heap.length();
  2482. unsigned *s = heap.getArray();
  2483. while (1)
  2484. {
  2485. unsigned c = p*2 + 1; /* child */
  2486. if ( c >= n )
  2487. break;
  2488. /* Select smaller child */
  2489. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2490. /* If child is greater or equal than parent then we are done */
  2491. if ( doCompare( s[c], s[p] ) >= 0 )
  2492. break;
  2493. /* Swap parent and child */
  2494. unsigned r = s[c];
  2495. s[c] = s[p];
  2496. s[p] = r;
  2497. /* child becomes parent */
  2498. p = c;
  2499. }
  2500. remakePending = false;
  2501. }
  2502. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2503. {
  2504. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2505. IMessageResult *result = p->queryResult();
  2506. assertex(result);
  2507. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2508. {
  2509. heapEntries.append(h);
  2510. heap.append(heap.ordinality());
  2511. }
  2512. else
  2513. h.Release();
  2514. }
  2515. void removeHeap(unsigned idx)
  2516. {
  2517. heapEntries.remove(idx);
  2518. ForEachItemIn(i, heap)
  2519. {
  2520. unsigned v = heap.item(i);
  2521. assertex(v != idx);
  2522. if (v > idx)
  2523. heap.replace(v-1, i);
  2524. }
  2525. }
  2526. bool isCompleteMatchFlag(IMessageResult *result)
  2527. {
  2528. unsigned metaLen;
  2529. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2530. if (metaLen)
  2531. {
  2532. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2533. if (continuationLen >= sizeof(bool))
  2534. {
  2535. metaInfo += sizeof(unsigned short);
  2536. return *(bool *) metaInfo;
  2537. }
  2538. }
  2539. return true; // if no continuation info, last row was complete.
  2540. }
  2541. public:
  2542. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2543. {
  2544. init(NULL, NULL);
  2545. }
  2546. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2547. {
  2548. if (meta)
  2549. {
  2550. numFields = meta->getNumFields();
  2551. compare = meta->queryCompare();
  2552. }
  2553. else
  2554. {
  2555. numFields = 0;
  2556. compare = NULL;
  2557. }
  2558. rowManager = _rowManager;
  2559. numPending = 0;
  2560. endSeen = false;
  2561. remakePending = false;
  2562. deferredContinuation = false;
  2563. }
  2564. void reset()
  2565. {
  2566. heapEntries.kill();
  2567. heap.kill();
  2568. numPending = 0;
  2569. endSeen = false;
  2570. remakePending = false;
  2571. deferredContinuation = false;
  2572. }
  2573. inline bool noteEndSeen()
  2574. {
  2575. bool hadSeen = endSeen;
  2576. if (!endSeen)
  2577. makeHeap();
  2578. endSeen = true;
  2579. return !hadSeen;
  2580. }
  2581. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2582. {
  2583. if (!p->isContinuation())
  2584. append(p, seq);
  2585. else
  2586. {
  2587. ForEachItemIn(idx, heapEntries)
  2588. {
  2589. HeapEntry &h = heapEntries.item(idx);
  2590. if (h.packet == p)
  2591. {
  2592. IMessageResult *result = p->queryResult();
  2593. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2594. {
  2595. heap.zap(idx);
  2596. removeHeap(idx);
  2597. }
  2598. numPending--;
  2599. if (!numPending)
  2600. makeHeap();
  2601. return;
  2602. }
  2603. }
  2604. }
  2605. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2606. return;
  2607. }
  2608. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2609. {
  2610. HeapEntry &entry = heapEntries.item(idx);
  2611. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2612. if (!entry.current)
  2613. {
  2614. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2615. if (continuation)
  2616. {
  2617. continuation->Link();
  2618. entry.packet->Release();
  2619. entry.packet = continuation;
  2620. if (continuation->hasResult())
  2621. {
  2622. IMessageResult *result = continuation->queryResult();
  2623. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2624. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2625. }
  2626. else
  2627. {
  2628. if (continuation->isDelayed())
  2629. {
  2630. continuation->setDelayed(false);
  2631. MemoryBuffer serializedSkip;
  2632. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2633. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2634. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2635. adaptor.sentsome.signal();
  2636. }
  2637. numPending++;
  2638. }
  2639. }
  2640. else
  2641. {
  2642. heap.zap(idx);
  2643. removeHeap(idx);
  2644. idx--;
  2645. }
  2646. }
  2647. return skipped;
  2648. }
  2649. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2650. {
  2651. // We discard all rows < seekval from all entries in heap
  2652. // If this results in additional slave requests, we return NULL so that we can wait for them
  2653. // If not, we rebuild the heap (if any were skipped) and return the first row
  2654. deferredContinuation = false;
  2655. if (heap.length())
  2656. {
  2657. unsigned skipped = 0;
  2658. unsigned idx = 0;
  2659. while(heapEntries.isItem(idx))
  2660. {
  2661. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2662. idx++;
  2663. }
  2664. if (numPending)
  2665. return NULL; // can't answer yet, need more results from slaves
  2666. else
  2667. {
  2668. if (skipped)
  2669. makeHeap();
  2670. return next(wasCompleteMatch, stepExtra);
  2671. }
  2672. }
  2673. else
  2674. return NULL;
  2675. }
  2676. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2677. {
  2678. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2679. if (continuation)
  2680. {
  2681. if (continuation->isDelayed() && canDefer)
  2682. {
  2683. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2684. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2685. deferredContinuation = true;
  2686. }
  2687. else
  2688. {
  2689. deferredContinuation = false;
  2690. continuation->Link();
  2691. topEntry.packet->Release();
  2692. topEntry.packet = continuation;
  2693. if (continuation->hasResult())
  2694. {
  2695. IMessageResult *result = continuation->queryResult();
  2696. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2697. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2698. }
  2699. else
  2700. {
  2701. if (continuation->isDelayed()) // has the continuation been requested yet?
  2702. {
  2703. continuation->Link();
  2704. topEntry.packet->Release();
  2705. topEntry.packet = continuation;
  2706. continuation->setDelayed(false);
  2707. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2708. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2709. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2710. adaptor.sentsome.signal();
  2711. }
  2712. numPending++; // we are waiting for one that is already in flight
  2713. }
  2714. }
  2715. return true; // next not known yet
  2716. }
  2717. else
  2718. return false;
  2719. }
  2720. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2721. {
  2722. OwnedConstRoxieRow ret;
  2723. if (heap.length())
  2724. {
  2725. if (deferredContinuation)
  2726. {
  2727. unsigned top = heap.item(0);
  2728. HeapEntry &topEntry = heapEntries.item(top);
  2729. doContinuation(topEntry, false);
  2730. return NULL;
  2731. }
  2732. if (remakePending)
  2733. remakeHeap();
  2734. unsigned top = heap.item(0);
  2735. HeapEntry &topEntry = heapEntries.item(top);
  2736. ret.set(topEntry.current);
  2737. wasCompleteMatch = topEntry.isCompleteMatch();
  2738. const void *next = topEntry.next();
  2739. if (!next)
  2740. {
  2741. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2742. {
  2743. unsigned last = heap.popGet();
  2744. if (heap.length())
  2745. heap.replace(last, 0);
  2746. removeHeap(top);
  2747. }
  2748. }
  2749. remakePending = true;
  2750. }
  2751. return ret.getClear();
  2752. }
  2753. bool ready()
  2754. {
  2755. return endSeen && numPending == 0;
  2756. }
  2757. };
  2758. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2759. {
  2760. if (serverSideCache && !debugContext)
  2761. {
  2762. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2763. if (ret)
  2764. {
  2765. p->Release();
  2766. cached = true;
  2767. return ret;
  2768. }
  2769. }
  2770. cached = false;
  2771. return new CRoxieServerQueryPacket(p);
  2772. }
  2773. #ifdef _DEBUG
  2774. void dumpPending()
  2775. {
  2776. CriticalBlock b(pendingCrit);
  2777. ForEachItemIn(idx, pending)
  2778. {
  2779. IRoxieServerQueryPacket &p = pending.item(idx);
  2780. StringBuffer s;
  2781. unsigned __int64 dummy;
  2782. if (p.isEnd())
  2783. s.append("END");
  2784. else if (p.isLimit(dummy, dummy, dummy))
  2785. s.append("LIMIT");
  2786. else
  2787. {
  2788. IRoxieQueryPacket *i = p.queryPacket();
  2789. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2790. if (i)
  2791. {
  2792. RoxiePacketHeader &header = i->queryHeader();
  2793. header.toString(s);
  2794. }
  2795. }
  2796. DBGLOG("Pending %d %s", idx, s.str());
  2797. }
  2798. }
  2799. #endif
  2800. void abortPending()
  2801. {
  2802. CriticalBlock b(pendingCrit);
  2803. ForEachItemIn(idx, pending)
  2804. {
  2805. IRoxieServerQueryPacket &p = pending.item(idx);
  2806. if (!p.hasResult())
  2807. {
  2808. IRoxieQueryPacket *i = p.queryPacket();
  2809. if (i)
  2810. {
  2811. RoxiePacketHeader &header = i->queryHeader();
  2812. ROQ->sendAbort(header, activity.queryLogCtx());
  2813. }
  2814. }
  2815. }
  2816. pending.kill();
  2817. }
  2818. void checkDelayed()
  2819. {
  2820. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2821. {
  2822. bool allDelayed = true;
  2823. CriticalBlock b(pendingCrit);
  2824. unsigned sendIdx = (unsigned) -1;
  2825. ForEachItemIn(idx, pending)
  2826. {
  2827. IRoxieServerQueryPacket &p = pending.item(idx);
  2828. if (p.queryPacket())
  2829. {
  2830. if (p.isDelayed())
  2831. {
  2832. if (sendIdx == (unsigned) -1)
  2833. sendIdx = idx;
  2834. }
  2835. else if (!p.hasResult())
  2836. {
  2837. allDelayed = false;
  2838. break;
  2839. }
  2840. }
  2841. }
  2842. if (allDelayed && sendIdx != (unsigned) -1)
  2843. {
  2844. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2845. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2846. pending.item(sendIdx).setDelayed(false);
  2847. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2848. sentsome.signal();
  2849. }
  2850. }
  2851. else if (deferredStart)
  2852. {
  2853. CriticalBlock b(pendingCrit);
  2854. ForEachItemIn(idx, pending)
  2855. {
  2856. IRoxieServerQueryPacket &p = pending.item(idx);
  2857. if (p.isDelayed())
  2858. {
  2859. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2860. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2861. p.setDelayed(false);
  2862. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2863. sentsome.signal();
  2864. }
  2865. }
  2866. deferredStart = false;
  2867. }
  2868. }
  2869. void retryPending()
  2870. {
  2871. CriticalBlock b(pendingCrit);
  2872. checkDelayed();
  2873. ForEachItemIn(idx, pending)
  2874. {
  2875. IRoxieServerQueryPacket &p = pending.item(idx);
  2876. if (!p.hasResult() && !p.isDelayed())
  2877. {
  2878. IRoxieQueryPacket *i = p.queryPacket();
  2879. if (i)
  2880. {
  2881. if (!i->queryHeader().retry())
  2882. {
  2883. StringBuffer s;
  2884. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2885. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2886. throw E;
  2887. }
  2888. if (!localSlave)
  2889. {
  2890. ROQ->sendPacket(i, activity.queryLogCtx());
  2891. atomic_inc(&retriesSent);
  2892. }
  2893. }
  2894. }
  2895. }
  2896. }
  2897. class ChannelBuffer
  2898. {
  2899. protected:
  2900. unsigned bufferLeft;
  2901. MemoryBuffer buffer;
  2902. char *nextBuf;
  2903. unsigned overflowSequence;
  2904. unsigned channel; // == bonded channel
  2905. bool needsFlush;
  2906. InterruptableSemaphore flowController;
  2907. const CRemoteResultAdaptor &owner;
  2908. CriticalSection crit;
  2909. public:
  2910. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2911. {
  2912. overflowSequence = 0;
  2913. needsFlush = false;
  2914. bufferLeft = 0;
  2915. nextBuf = NULL;
  2916. }
  2917. void init(unsigned minSize)
  2918. {
  2919. assertex(!buffer.length());
  2920. if (minSize < MIN_PAYLOAD_SIZE)
  2921. minSize = MIN_PAYLOAD_SIZE;
  2922. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2923. unsigned bufferSize = headerSize+minSize;
  2924. if (bufferSize < mtu_size)
  2925. bufferSize = mtu_size;
  2926. buffer.reserveTruncate(bufferSize);
  2927. bufferLeft = bufferSize - headerSize;
  2928. assertex(buffer.toByteArray());
  2929. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2930. needsFlush = false;
  2931. }
  2932. inline IRoxieQueryPacket *flush()
  2933. {
  2934. CriticalBlock cb(crit);
  2935. Owned<IRoxieQueryPacket> ret;
  2936. if (needsFlush)
  2937. {
  2938. buffer.setLength(nextBuf - buffer.toByteArray());
  2939. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2940. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2941. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2942. byte * tgt = (byte*)(h+1);
  2943. owner.copyHeader(tgt, channel);
  2944. ret.setown(createRoxiePacket(buffer));
  2945. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2946. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2947. else
  2948. overflowSequence++;
  2949. needsFlush = false;
  2950. bufferLeft = 0;
  2951. if (owner.flowControlled)
  2952. {
  2953. CriticalUnblock cub(crit);
  2954. while (!flowController.wait(1000))
  2955. {
  2956. StringBuffer s;
  2957. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2958. }
  2959. }
  2960. }
  2961. return ret.getClear();
  2962. }
  2963. inline void signal()
  2964. {
  2965. if (owner.flowControlled)
  2966. flowController.signal();
  2967. }
  2968. inline void interrupt(IException *e)
  2969. {
  2970. flowController.interrupt(e);
  2971. }
  2972. inline void *getBuffer(unsigned size)
  2973. {
  2974. CriticalBlock cb(crit);
  2975. if (bufferLeft >= size)
  2976. {
  2977. needsFlush = true;
  2978. void * ret = nextBuf;
  2979. nextBuf += size;
  2980. bufferLeft -= size;
  2981. return ret;
  2982. }
  2983. else if (!needsFlush)
  2984. {
  2985. init(size);
  2986. return getBuffer(size);
  2987. }
  2988. else if (owner.mergeOrder)
  2989. {
  2990. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2991. }
  2992. else
  2993. return NULL; // will force it to flush and start a new packet
  2994. }
  2995. };
  2996. private:
  2997. friend class CRemoteResultMerger;
  2998. bool allread;
  2999. bool contextCached;
  3000. bool preserveOrder;
  3001. InterruptableSemaphore sentsome;
  3002. Owned <IMessageCollator> mc;
  3003. Owned<IMessageUnpackCursor> mu;
  3004. Owned<IMessageResult> mr;
  3005. ChannelBuffer **buffers;
  3006. IHThorArg &helper;
  3007. unsigned __int64 stopAfter;
  3008. unsigned resendSequence;
  3009. IHThorArg *colocalArg;
  3010. IArrayOf<IRoxieServerQueryPacket> pending;
  3011. CriticalSection pendingCrit;
  3012. IRoxieServerSideCache *serverSideCache;
  3013. unsigned sentSequence;
  3014. Owned<IOutputRowDeserializer> deserializer;
  3015. Owned<IEngineRowAllocator> rowAllocator;
  3016. CRemoteResultMerger merger;
  3017. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3018. MemoryBuffer tempRowBuffer;
  3019. Owned<ISerialStream> bufferStream;
  3020. CThorStreamDeserializerSource rowSource;
  3021. protected:
  3022. IRowManager *rowManager;
  3023. IRoxieInput *owner;
  3024. unsigned __int64 rowLimit;
  3025. unsigned __int64 keyedLimit;
  3026. IRoxieServerErrorHandler *errorHandler;
  3027. CachedOutputMetaData meta;
  3028. public:
  3029. ISteppingMeta *mergeOrder;
  3030. IRoxieSlaveContext *ctx;
  3031. IDebuggableContext *debugContext;
  3032. IRoxieServerActivity &activity;
  3033. unsigned parentExtractSize;
  3034. const byte * parentExtract;
  3035. bool flowControlled;
  3036. bool deferredStart;
  3037. MemoryBuffer logInfo;
  3038. MemoryBuffer cachedContext;
  3039. const RemoteActivityId &remoteId;
  3040. ruid_t ruid;
  3041. mutable CriticalSection buffersCrit;
  3042. unsigned processed;
  3043. cycle_t totalCycles;
  3044. bool timeActivities;
  3045. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3046. const void *getRow(IMessageUnpackCursor *mu)
  3047. {
  3048. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3049. return mu->getNext(meta.getFixedSize());
  3050. else
  3051. {
  3052. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3053. if (rowlen)
  3054. {
  3055. RecordLengthType len = *rowlen;
  3056. ReleaseRoxieRow(rowlen);
  3057. const void *slaveRec = mu->getNext(len);
  3058. if (deserializer && mu->isSerialized())
  3059. {
  3060. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3061. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3062. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3063. ReleaseRoxieRow(slaveRec);
  3064. return rowBuilder.finalizeRowClear(outsize);
  3065. }
  3066. else
  3067. return slaveRec;
  3068. }
  3069. else
  3070. return NULL;
  3071. }
  3072. }
  3073. private:
  3074. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3075. {
  3076. CriticalBlock cb(buffersCrit);
  3077. ChannelBuffer *b = buffers[channel];
  3078. if (!b && force)
  3079. {
  3080. if (!contextCached)
  3081. {
  3082. logInfo.clear();
  3083. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3084. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3085. const QueryOptions &options = ctx->queryOptions();
  3086. if (activity.queryLogCtx().isIntercepted())
  3087. loggingFlags |= LOGGING_INTERCEPTED;
  3088. if (options.timeActivities)
  3089. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3090. if (activity.queryLogCtx().isBlind())
  3091. loggingFlags |= LOGGING_BLIND;
  3092. if (options.checkingHeap)
  3093. loggingFlags |= LOGGING_CHECKINGHEAP;
  3094. if (ctx->queryWorkUnit())
  3095. loggingFlags |= LOGGING_WUID;
  3096. if (debugContext)
  3097. {
  3098. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3099. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3100. MemoryBuffer bpInfo;
  3101. debugContext->serialize(bpInfo);
  3102. bpInfo.append((__uint64)(memsize_t) &activity);
  3103. logInfo.append((unsigned short) bpInfo.length());
  3104. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3105. }
  3106. else
  3107. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3108. StringBuffer logPrefix;
  3109. activity.queryLogCtx().getLogPrefix(logPrefix);
  3110. logInfo.append(logPrefix);
  3111. activity.serializeCreateStartContext(cachedContext.clear());
  3112. activity.serializeExtra(cachedContext);
  3113. if (activity.queryVarFileInfo())
  3114. {
  3115. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3116. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3117. }
  3118. contextCached = true;
  3119. }
  3120. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3121. }
  3122. return b;
  3123. }
  3124. void processRow(const void *got)
  3125. {
  3126. processed++;
  3127. if (processed > rowLimit)
  3128. {
  3129. ReleaseRoxieRow(got);
  3130. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3131. throwUnexpected();
  3132. }
  3133. else if (processed > keyedLimit)
  3134. {
  3135. ReleaseRoxieRow(got);
  3136. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3137. throwUnexpected();
  3138. }
  3139. }
  3140. public:
  3141. IMPLEMENT_IINTERFACE;
  3142. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3143. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3144. {
  3145. rowLimit = (unsigned __int64) -1;
  3146. keyedLimit = (unsigned __int64) -1;
  3147. contextCached = false;
  3148. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3149. buffers = new ChannelBuffer*[numChannels+1];
  3150. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3151. parentExtractSize = 0;
  3152. parentExtract = NULL;
  3153. debugContext = NULL;
  3154. owner = NULL;
  3155. mergeOrder = NULL;
  3156. deferredStart = false;
  3157. processed = 0;
  3158. sentSequence = 0;
  3159. resendSequence = 0;
  3160. totalCycles = 0;
  3161. serverSideCache = activity.queryServerSideCache();
  3162. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3163. rowSource.setStream(bufferStream);
  3164. timeActivities = defaultTimeActivities;
  3165. }
  3166. ~CRemoteResultAdaptor()
  3167. {
  3168. if (mc)
  3169. {
  3170. ROQ->queryReceiveManager()->detachCollator(mc);
  3171. mc.clear();
  3172. }
  3173. for (unsigned channel = 0; channel <= numChannels; channel++)
  3174. {
  3175. delete(buffers[channel]);
  3176. }
  3177. delete [] buffers;
  3178. }
  3179. void setMeta(IOutputMetaData *newmeta)
  3180. {
  3181. meta.set(newmeta);
  3182. }
  3183. virtual IRoxieServerActivity *queryActivity()
  3184. {
  3185. return &activity;
  3186. }
  3187. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3188. {
  3189. return NULL;
  3190. }
  3191. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3192. {
  3193. mergeOrder = _mergeOrder;
  3194. deferredStart = true;
  3195. }
  3196. void send(IRoxieQueryPacket *p)
  3197. {
  3198. if (p)
  3199. {
  3200. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3201. assertex(p->queryHeader().uid==ruid);
  3202. // MORE: Maybe we should base the fastlane flag on some other
  3203. // criteria !! (i.e A Roxie server prediction based on the
  3204. // activity type/activity behaviour/expected reply size .. etc).
  3205. //
  3206. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3207. // But this could still cause too many reply packets on the fatlane
  3208. // (higher priority output Q), which may cause the activities on the
  3209. // low priority output Q to not get service on time.
  3210. if ((colocalArg == 0) && // not a child query activity??
  3211. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3212. (p->queryHeader().overflowSequence == 0) &&
  3213. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3214. p->queryHeader().retries |= ROXIE_FASTLANE;
  3215. if (p->queryHeader().channel)
  3216. {
  3217. bool cached = false;
  3218. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3219. if (deferredStart)
  3220. rsqp->setDelayed(true);
  3221. rsqp->setSequence(sentSequence++);
  3222. {
  3223. CriticalBlock b(pendingCrit);
  3224. pending.append(*rsqp);
  3225. }
  3226. if (!deferredStart)
  3227. {
  3228. if (!cached)
  3229. ROQ->sendPacket(p, activity.queryLogCtx());
  3230. sentsome.signal();
  3231. }
  3232. }
  3233. else
  3234. {
  3235. // 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
  3236. // Need to add first, then send
  3237. unsigned i;
  3238. bool allCached = true;
  3239. for (i = 1; i <= numChannels; i++)
  3240. {
  3241. IRoxieQueryPacket *q = p->clonePacket(i);
  3242. bool thisChannelCached;
  3243. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3244. if (!thisChannelCached)
  3245. allCached = false;
  3246. rsqp->setSequence(sentSequence++);
  3247. if (deferredStart)
  3248. {
  3249. rsqp->setDelayed(true);
  3250. }
  3251. {
  3252. CriticalBlock b(pendingCrit);
  3253. pending.append(*rsqp);
  3254. }
  3255. if (!deferredStart)
  3256. sentsome.signal();
  3257. }
  3258. if (!allCached && !deferredStart)
  3259. ROQ->sendPacket(p, activity.queryLogCtx());
  3260. buffers[0]->signal(); // since replies won't come back on that channel...
  3261. p->Release();
  3262. }
  3263. }
  3264. }
  3265. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3266. {
  3267. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3268. size += sizeof(PartNoType);
  3269. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3270. char *buffer = (char *) b->getBuffer(size);
  3271. if (!buffer)
  3272. {
  3273. send(b->flush());
  3274. buffer = (char *) b->getBuffer(size);
  3275. }
  3276. PartNoType sp;
  3277. sp.partNo = partNo;
  3278. sp.fileNo = fileNo;
  3279. memcpy(buffer, &sp, sizeof(sp));
  3280. buffer += sizeof(sp);
  3281. return buffer;
  3282. }
  3283. void injectResult(IMessageResult *result)
  3284. {
  3285. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3286. f->setSequence(sentSequence++);
  3287. f->setResult(result);
  3288. CriticalBlock b(pendingCrit);
  3289. pending.append(*f);
  3290. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3291. }
  3292. void flush()
  3293. {
  3294. for (unsigned channel = 0; channel <= numChannels; channel++)
  3295. {
  3296. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3297. if (b)
  3298. send(b->flush());
  3299. }
  3300. }
  3301. void interruptBuffers(IException *e)
  3302. {
  3303. for (unsigned channel = 0; channel <= numChannels; channel++)
  3304. {
  3305. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3306. if (b)
  3307. b->interrupt(LINK(e));
  3308. }
  3309. }
  3310. void senddone()
  3311. {
  3312. CriticalBlock b(pendingCrit);
  3313. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3314. sentsome.signal();
  3315. }
  3316. bool fireException(IException *e)
  3317. {
  3318. {
  3319. CriticalBlock b(pendingCrit);
  3320. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3321. }
  3322. interruptBuffers(e);
  3323. if (mc)
  3324. mc->interrupt(LINK(e));
  3325. sentsome.interrupt(e);
  3326. return true;
  3327. }
  3328. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3329. {
  3330. owner = _owner;
  3331. errorHandler = _errorHandler;
  3332. ctx = _ctx;
  3333. debugContext = ctx->queryDebugContext();
  3334. colocalArg = _colocalArg;
  3335. if (meta.needsSerializeDisk())
  3336. {
  3337. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3338. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3339. }
  3340. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3341. deferredStart = true;
  3342. if (ctx)
  3343. timeActivities = ctx->queryOptions().timeActivities;
  3344. }
  3345. virtual unsigned queryId() const
  3346. {
  3347. return owner->queryId();
  3348. }
  3349. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3350. {
  3351. #ifdef TRACE_STARTSTOP
  3352. if (traceStartStop)
  3353. activity.queryLogCtx().CTXLOG("RRAonstart");
  3354. #endif
  3355. sentsome.reinit();
  3356. ruid = getNextRuid();
  3357. rowManager = &ctx->queryRowManager();
  3358. if (mergeOrder)
  3359. merger.init(mergeOrder, rowManager);
  3360. if (mc)
  3361. {
  3362. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3363. }
  3364. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3365. allread = false;
  3366. mu.clear();
  3367. contextCached = false;
  3368. processed = 0;
  3369. resendSequence = 0;
  3370. sentSequence = 0;
  3371. for (unsigned channel = 0; channel <= numChannels; channel++)
  3372. {
  3373. delete(buffers[channel]);
  3374. buffers[channel] = NULL;
  3375. }
  3376. flush();
  3377. parentExtractSize = _parentExtractSize;
  3378. parentExtract = _parentExtract;
  3379. }
  3380. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3381. {
  3382. #ifdef TRACE_STARTSTOP
  3383. if (traceStartStop)
  3384. activity.queryLogCtx().CTXLOG("RRAstart");
  3385. #endif
  3386. owner->start(parentExtractSize, parentExtract, paused);
  3387. }
  3388. void checkAbort()
  3389. {
  3390. owner->checkAbort();
  3391. }
  3392. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3393. {
  3394. if (ctx->queryProbeManager())
  3395. {
  3396. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3397. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3398. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3399. }
  3400. {
  3401. CriticalBlock b(pendingCrit);
  3402. if (pending.length())
  3403. {
  3404. #ifdef _DEBUG
  3405. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3406. #endif
  3407. assertex(pending.length()==0);
  3408. }
  3409. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3410. }
  3411. sentsome.signal();
  3412. rowLimit = _rowLimit;
  3413. keyedLimit = _keyedLimit;
  3414. stopAfter = _stopAfter;
  3415. }
  3416. virtual void stop(bool aborting)
  3417. {
  3418. #ifdef TRACE_STARTSTOP
  3419. if (traceStartStop)
  3420. activity.queryLogCtx().CTXLOG("RRAstop");
  3421. #endif
  3422. onStop(aborting);
  3423. owner->stop(aborting);
  3424. }
  3425. void onStop(bool aborting)
  3426. {
  3427. #ifdef TRACE_STARTSTOP
  3428. if (traceStartStop)
  3429. activity.queryLogCtx().CTXLOG("RRAonstop");
  3430. #endif
  3431. abortPending();
  3432. interruptBuffers(NULL);
  3433. sentsome.interrupt();
  3434. if (mc) // May not be set if start() chain threw exception
  3435. mc->interrupt();
  3436. }
  3437. virtual void reset()
  3438. {
  3439. #ifdef TRACE_STARTSTOP
  3440. if (traceStartStop)
  3441. activity.queryLogCtx().CTXLOG("RRAreset");
  3442. #endif
  3443. owner->reset();
  3444. onReset();
  3445. }
  3446. virtual void resetEOF()
  3447. {
  3448. throwUnexpected();
  3449. }
  3450. virtual void onReset()
  3451. {
  3452. #ifdef TRACE_STARTSTOP
  3453. if (traceStartStop)
  3454. activity.queryLogCtx().CTXLOG("RRAonreset");
  3455. #endif
  3456. if (mc)
  3457. ROQ->queryReceiveManager()->detachCollator(mc);
  3458. merger.reset();
  3459. pending.kill();
  3460. if (mc && ctx)
  3461. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3462. mc.clear(); // Or we won't free memory for graphs that get recreated
  3463. mu.clear(); //ditto
  3464. deferredStart = false;
  3465. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3466. }
  3467. virtual IOutputMetaData * queryOutputMeta() const
  3468. {
  3469. return helper.queryOutputMeta();
  3470. }
  3471. virtual unsigned __int64 queryTotalCycles() const
  3472. {
  3473. return totalCycles;
  3474. }
  3475. virtual unsigned __int64 queryLocalCycles() const
  3476. {
  3477. return owner->queryLocalCycles();
  3478. }
  3479. virtual IRoxieInput *queryInput(unsigned idx) const
  3480. {
  3481. return owner->queryInput(idx);
  3482. }
  3483. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3484. {
  3485. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3486. {
  3487. StringBuffer recstr;
  3488. unsigned i;
  3489. for (i = 0; i < seekLen; i++)
  3490. {
  3491. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3492. }
  3493. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3494. }
  3495. assertex(mergeOrder);
  3496. if (deferredStart)
  3497. {
  3498. CriticalBlock b(pendingCrit);
  3499. ForEachItemIn(idx, pending)
  3500. {
  3501. IRoxieServerQueryPacket &p = pending.item(idx);
  3502. if (p.isDelayed())
  3503. {
  3504. p.setDelayed(false);
  3505. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3506. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3507. MemoryBuffer serializedSkip;
  3508. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3509. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3510. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3511. sentsome.signal();
  3512. }
  3513. }
  3514. deferredStart = false;
  3515. }
  3516. SimpleActivityTimer t(totalCycles, timeActivities);
  3517. if (processed==stopAfter)
  3518. return NULL;
  3519. if (allread)
  3520. return NULL;
  3521. loop
  3522. {
  3523. if (merger.ready())
  3524. {
  3525. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3526. if (got)
  3527. {
  3528. processRow(got);
  3529. return got;
  3530. }
  3531. }
  3532. if (!reload()) // MORE - should pass the seek info here...
  3533. return NULL;
  3534. }
  3535. }
  3536. virtual const void *nextInGroup()
  3537. {
  3538. // If we are merging then we need to do a heapsort on all
  3539. SimpleActivityTimer t(totalCycles, timeActivities);
  3540. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3541. {
  3542. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3543. }
  3544. loop
  3545. {
  3546. checkDelayed();
  3547. if (processed==stopAfter)
  3548. return NULL;
  3549. if (allread)
  3550. return NULL;
  3551. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3552. const void *got = NULL;
  3553. if (mergeOrder && merger.ready())
  3554. {
  3555. bool matched = true;
  3556. got = merger.next(matched, dummySmartStepExtra);
  3557. }
  3558. else if (mu)
  3559. got = getRow(mu);
  3560. if (got)
  3561. {
  3562. processRow(got);
  3563. return got;
  3564. }
  3565. if (!reload())
  3566. return NULL;
  3567. }
  3568. }
  3569. bool reload()
  3570. {
  3571. // Wait for something to be returned from a slave....
  3572. mu.clear();
  3573. sentsome.wait();
  3574. // must be at least an endMarker on the queue since sentsome was signalled
  3575. {
  3576. CriticalBlock b(pendingCrit);
  3577. IRoxieServerQueryPacket &top = pending.item(0);
  3578. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3579. {
  3580. pending.remove(0);
  3581. return true;
  3582. }
  3583. else if (top.isEnd())
  3584. {
  3585. pending.remove(0);
  3586. allread = true;
  3587. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3588. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3589. return false;
  3590. }
  3591. else if (mergeOrder)
  3592. {
  3593. unsigned idx = 0;
  3594. bool added = false;
  3595. while (pending.isItem(idx))
  3596. {
  3597. IRoxieServerQueryPacket &item = pending.item(idx);
  3598. if (item.isEnd())
  3599. {
  3600. if (merger.noteEndSeen())
  3601. {
  3602. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3603. added = true;
  3604. }
  3605. break;
  3606. }
  3607. else if (item.hasResult())
  3608. {
  3609. merger.noteResult(&item, item.getSequence());
  3610. pending.remove(idx);
  3611. added = true;
  3612. }
  3613. else if (item.isContinuation())
  3614. idx++;
  3615. else
  3616. break;
  3617. }
  3618. if (added)
  3619. return true;
  3620. }
  3621. else if (top.hasResult())
  3622. {
  3623. mr.setown(pending.item(0).getResult());
  3624. mu.setown(mr->getCursor(rowManager));
  3625. pending.remove(0);
  3626. return true;
  3627. }
  3628. }
  3629. getNextUnpacker();
  3630. return true;
  3631. }
  3632. void getNextUnpacker()
  3633. {
  3634. mu.clear();
  3635. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3636. loop
  3637. {
  3638. checkDelayed();
  3639. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3640. owner->checkAbort();
  3641. bool anyActivity;
  3642. if (ctxTraceLevel > 5)
  3643. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3644. mr.setown(mc->getNextResult(timeout, anyActivity));
  3645. if (ctxTraceLevel > 6)
  3646. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3647. owner->checkAbort();
  3648. if (mr)
  3649. {
  3650. unsigned roxieHeaderLen;
  3651. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3652. #ifdef _DEBUG
  3653. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3654. #endif
  3655. if (ctxTraceLevel > 5)
  3656. {
  3657. StringBuffer s;
  3658. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3659. }
  3660. CriticalBlock b(pendingCrit);
  3661. unsigned idx = 0;
  3662. IRoxieServerQueryPacket *original = NULL;
  3663. IRoxieQueryPacket *op;
  3664. while (pending.isItem(idx))
  3665. {
  3666. original = &pending.item(idx);
  3667. op = original->queryPacket();
  3668. if (op && header.matchPacket(op->queryHeader()))
  3669. break;
  3670. original = NULL;
  3671. idx++;
  3672. }
  3673. if (!original || original->hasResult())
  3674. {
  3675. switch (header.activityId)
  3676. {
  3677. case ROXIE_FILECALLBACK:
  3678. {
  3679. // tell slave to abort
  3680. //if (ctxTraceLevel > 5)
  3681. {
  3682. StringBuffer s;
  3683. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3684. }
  3685. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3686. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3687. if (len)
  3688. {
  3689. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3690. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3691. const char *rowdata = (const char *) row.get();
  3692. // bool isOpt = * (bool *) rowdata;
  3693. // bool isLocal = * (bool *) (rowdata+1);
  3694. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3695. }
  3696. else
  3697. throwUnexpected();
  3698. break;
  3699. }
  3700. // MORE - ROXIE_ALIVE perhaps should go here too
  3701. default:
  3702. if (ctxTraceLevel > 3)
  3703. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3704. mr->discard();
  3705. break;
  3706. }
  3707. mr.clear();
  3708. }
  3709. else
  3710. {
  3711. atomic_inc(&resultsReceived);
  3712. switch (header.activityId)
  3713. {
  3714. case ROXIE_DEBUGCALLBACK:
  3715. {
  3716. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3717. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3718. if (len)
  3719. {
  3720. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3721. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3722. char *rowdata = (char *) row.get();
  3723. if (ctxTraceLevel > 5)
  3724. {
  3725. StringBuffer s;
  3726. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3727. }
  3728. MemoryBuffer slaveInfo;
  3729. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3730. unsigned debugSequence;
  3731. slaveInfo.read(debugSequence);
  3732. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3733. if (!reply)
  3734. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3735. if (reply)
  3736. {
  3737. original->setDebugResponse(debugSequence, reply);
  3738. ROQ->sendPacket(reply, activity.queryLogCtx());
  3739. }
  3740. }
  3741. else
  3742. throwUnexpected();
  3743. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3744. // Leave original message on pending queue in original location - this is not a reply to it.
  3745. break;
  3746. }
  3747. case ROXIE_FILECALLBACK:
  3748. {
  3749. // we need to send back to the slave a message containing the file info requested.
  3750. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3751. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3752. if (len)
  3753. {
  3754. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3755. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3756. const char *rowdata = (const char *) row.get();
  3757. bool isOpt = * (bool *) rowdata;
  3758. bool isLocal = * (bool *) (rowdata+1);
  3759. const char *lfn = rowdata+2;
  3760. if (ctxTraceLevel > 5)
  3761. {
  3762. StringBuffer s;
  3763. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3764. }
  3765. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3766. }
  3767. else
  3768. throwUnexpected();
  3769. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3770. // Leave original message on pending queue in original location - this is not a reply to it.
  3771. break;
  3772. }
  3773. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3774. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3775. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3776. throwUnexpected();
  3777. case ROXIE_LIMIT_EXCEEDED:
  3778. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3779. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3780. throwUnexpected();
  3781. case ROXIE_TRACEINFO:
  3782. {
  3783. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3784. loop
  3785. {
  3786. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3787. if (rowlen)
  3788. {
  3789. char *logInfo = (char *) extra->getNext(*rowlen);
  3790. MemoryBuffer buf;
  3791. buf.setBuffer(*rowlen, logInfo, false);
  3792. switch ((TracingCategory) *logInfo)
  3793. {
  3794. case LOG_TRACING:
  3795. case LOG_ERROR:
  3796. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3797. break;
  3798. case LOG_STATVALUES:
  3799. buf.skip(1);
  3800. activity.mergeStats(buf);
  3801. break;
  3802. case LOG_CHILDCOUNT:
  3803. case LOG_CHILDSTATS:
  3804. unsigned graphId, childId;
  3805. buf.skip(1);
  3806. buf.read(graphId);
  3807. buf.read(childId);
  3808. if (*logInfo == LOG_CHILDCOUNT)
  3809. {
  3810. unsigned childProcessed;
  3811. unsigned idx;
  3812. buf.read(childProcessed);
  3813. buf.read(idx);
  3814. if (traceLevel > 5)
  3815. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d for child %d subgraph %d", childProcessed, idx, childId, graphId);
  3816. activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed);
  3817. }
  3818. else
  3819. {
  3820. ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
  3821. CRuntimeStatisticCollection childStats(allStatistics);
  3822. childStats.deserialize(buf);
  3823. if (traceLevel > 5)
  3824. {
  3825. StringBuffer s;
  3826. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  3827. }
  3828. activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
  3829. }
  3830. }
  3831. ReleaseRoxieRow(rowlen);
  3832. ReleaseRoxieRow(logInfo);
  3833. }
  3834. else
  3835. break;
  3836. }
  3837. break;
  3838. }
  3839. case ROXIE_EXCEPTION:
  3840. if (ctxTraceLevel > 1)
  3841. {
  3842. StringBuffer s;
  3843. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3844. }
  3845. op->queryHeader().noteException(header.retries);
  3846. if (op->queryHeader().allChannelsFailed())
  3847. {
  3848. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3849. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3850. throwRemoteException(exceptionData);
  3851. }
  3852. // Leave it on pending queue in original location
  3853. break;
  3854. case ROXIE_ALIVE:
  3855. if (ctxTraceLevel > 4)
  3856. {
  3857. StringBuffer s;
  3858. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3859. }
  3860. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3861. // Leave it on pending queue in original location
  3862. break;
  3863. default:
  3864. if (header.retries & ROXIE_RETRIES_MASK)
  3865. atomic_inc(&retriesNeeded);
  3866. unsigned metaLen;
  3867. const void *metaData = mr->getMessageMetadata(metaLen);
  3868. if (metaLen)
  3869. {
  3870. // We got back first chunk but there is more.
  3871. // resend the packet, with the cursor info provided.
  3872. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3873. if (ctxTraceLevel > 1)
  3874. {
  3875. StringBuffer s;
  3876. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3877. }
  3878. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3879. {
  3880. StringBuffer s;
  3881. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3882. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3883. throwUnexpected();
  3884. }
  3885. MemoryBuffer nextQuery;
  3886. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3887. nextQuery.append(metaLen, metaData);
  3888. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3889. nextQuery.append(op->getContextLength(), op->queryContextData());
  3890. if (resendSequence == CONTINUESEQUENCE_MAX)
  3891. {
  3892. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3893. resendSequence = 1;
  3894. }
  3895. else
  3896. resendSequence++;
  3897. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3898. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3899. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3900. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3901. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3902. fqp->setSequence(original->getSequence());
  3903. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3904. original->setContinuation(LINK(fqp));
  3905. if (mergeOrder)
  3906. fqp->setDelayed(true);
  3907. else
  3908. {
  3909. ROQ->sendPacket(resend, activity.queryLogCtx());
  3910. sentsome.signal();
  3911. }
  3912. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3913. }
  3914. else
  3915. {
  3916. if (serverSideCache)
  3917. serverSideCache->noteCachedResult(original, mr);
  3918. }
  3919. unsigned channel = header.channel;
  3920. {
  3921. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3922. if (b)
  3923. b->signal();
  3924. }
  3925. original->setResult(mr.getClear());
  3926. sentsome.signal();
  3927. return;
  3928. }
  3929. }
  3930. }
  3931. else
  3932. {
  3933. if (!anyActivity && !localSlave)
  3934. {
  3935. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3936. retryPending();
  3937. }
  3938. }
  3939. }
  3940. }
  3941. inline unsigned headerLength() const
  3942. {
  3943. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3944. }
  3945. void copyHeader(byte *tgt, unsigned channel) const
  3946. {
  3947. unsigned len = logInfo.length();
  3948. memcpy(tgt, logInfo.toByteArray(), len);
  3949. tgt += len;
  3950. *(unsigned *) tgt = parentExtractSize;
  3951. tgt += sizeof(unsigned);
  3952. memcpy(tgt, parentExtract, parentExtractSize);
  3953. tgt += parentExtractSize;
  3954. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3955. tgt += cachedContext.length();
  3956. }
  3957. };
  3958. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3959. {
  3960. Owned <IException> exception;
  3961. bool skipping;
  3962. ConstPointerArray buff;
  3963. unsigned index;
  3964. bool pulled;
  3965. void pullInput()
  3966. {
  3967. try
  3968. {
  3969. if (exception)
  3970. throw exception.getClear();
  3971. unsigned __int64 count = 0;
  3972. loop
  3973. {
  3974. const void * next = CRemoteResultAdaptor::nextInGroup();
  3975. if (next == NULL)
  3976. {
  3977. next = CRemoteResultAdaptor::nextInGroup();
  3978. if(next == NULL)
  3979. break;
  3980. buff.append(NULL);
  3981. }
  3982. count++;
  3983. if (count > rowLimit)
  3984. {
  3985. ReleaseRoxieRow(next);
  3986. ReleaseRoxieRowSet(buff);
  3987. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3988. throwUnexpected();
  3989. }
  3990. else if (count > keyedLimit)
  3991. {
  3992. ReleaseRoxieRow(next);
  3993. ReleaseRoxieRowSet(buff);
  3994. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3995. throwUnexpected();
  3996. }
  3997. buff.append(next);
  3998. }
  3999. }
  4000. catch (IException *E)
  4001. {
  4002. if (QUERYINTERFACE(E, LimitSkipException))
  4003. {
  4004. Owned<IException> cleanup = E;
  4005. ReleaseRoxieRowSet(buff);
  4006. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4007. if (onfail)
  4008. buff.append(onfail);
  4009. }
  4010. else
  4011. throw;
  4012. }
  4013. pulled = true;
  4014. }
  4015. public:
  4016. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4017. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4018. {
  4019. skipping = _skipping;
  4020. index = 0;
  4021. pulled = false;
  4022. }
  4023. void setException(IException *E)
  4024. {
  4025. exception.setown(E);
  4026. }
  4027. virtual void onReset()
  4028. {
  4029. while (buff.isItem(index))
  4030. ReleaseRoxieRow(buff.item(index++));
  4031. buff.kill();
  4032. pulled = false;
  4033. exception.clear();
  4034. CRemoteResultAdaptor::onReset();
  4035. }
  4036. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4037. {
  4038. index = 0;
  4039. pulled = false;
  4040. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4041. }
  4042. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4043. {
  4044. // 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
  4045. if (exception)
  4046. throw exception.getClear();
  4047. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4048. }
  4049. virtual const void *nextInGroup()
  4050. {
  4051. if (skipping)
  4052. {
  4053. if(!pulled)
  4054. pullInput();
  4055. if(buff.isItem(index))
  4056. {
  4057. const void * next = buff.item(index++);
  4058. if(next)
  4059. processed++;
  4060. return next;
  4061. }
  4062. return NULL;
  4063. }
  4064. else
  4065. {
  4066. if (exception)
  4067. throw exception.getClear();
  4068. return CRemoteResultAdaptor::nextInGroup();
  4069. }
  4070. }
  4071. };
  4072. //=================================================================================
  4073. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4074. {
  4075. IHThorApplyArg &helper;
  4076. public:
  4077. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4078. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4079. {
  4080. }
  4081. virtual void onExecute()
  4082. {
  4083. helper.start();
  4084. loop
  4085. {
  4086. const void * next = input->nextInGroup();
  4087. if (!next)
  4088. {
  4089. next = input->nextInGroup();
  4090. if (!next)
  4091. break;
  4092. }
  4093. helper.apply(next);
  4094. ReleaseRoxieRow(next);
  4095. }
  4096. helper.end();
  4097. }
  4098. };
  4099. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4100. {
  4101. bool isRoot;
  4102. public:
  4103. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4104. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4105. {
  4106. }
  4107. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4108. {
  4109. return new CRoxieServerApplyActivity(this, _probeManager);
  4110. }
  4111. virtual bool isSink() const
  4112. {
  4113. return isRoot;
  4114. }
  4115. };
  4116. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4117. {
  4118. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4119. }
  4120. //=================================================================================
  4121. class CRoxieServerNullActivity : public CRoxieServerActivity
  4122. {
  4123. public:
  4124. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4125. : CRoxieServerActivity(_factory, _probeManager)
  4126. {
  4127. }
  4128. virtual const void *nextInGroup()
  4129. {
  4130. return NULL;
  4131. }
  4132. };
  4133. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4134. {
  4135. return new CRoxieServerNullActivity(_factory, _probeManager);
  4136. }
  4137. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4138. {
  4139. public:
  4140. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4141. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4142. {
  4143. }
  4144. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4145. {
  4146. return new CRoxieServerNullActivity(this, _probeManager);
  4147. }
  4148. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4149. {
  4150. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4151. }
  4152. };
  4153. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4154. {
  4155. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4156. }
  4157. //=================================================================================
  4158. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4159. {
  4160. public:
  4161. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4162. : CRoxieServerActivity(_factory, _probeManager)
  4163. {
  4164. }
  4165. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4166. {
  4167. return input->gatherConjunctions(collector);
  4168. }
  4169. virtual void resetEOF()
  4170. {
  4171. input->resetEOF();
  4172. }
  4173. virtual const void *nextInGroup()
  4174. {
  4175. const void * next = input->nextInGroup();
  4176. if (next)
  4177. processed++;
  4178. return next;
  4179. }
  4180. virtual bool isPassThrough()
  4181. {
  4182. return true;
  4183. }
  4184. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4185. {
  4186. ActivityTimer t(totalCycles, timeActivities);
  4187. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4188. if (next)
  4189. processed++;
  4190. return next;
  4191. }
  4192. IInputSteppingMeta * querySteppingMeta()
  4193. {
  4194. return input->querySteppingMeta();
  4195. }
  4196. };
  4197. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4198. {
  4199. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4200. }
  4201. //=================================================================================
  4202. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4203. {
  4204. protected:
  4205. bool eof;
  4206. bool first;
  4207. public:
  4208. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4209. : CRoxieServerActivity(_factory, _probeManager)
  4210. {
  4211. eof = false;
  4212. first = true;
  4213. }
  4214. ~CRoxieServerChildBaseActivity()
  4215. {
  4216. }
  4217. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4218. {
  4219. eof = false;
  4220. first = true;
  4221. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4222. }
  4223. };
  4224. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4225. {
  4226. public:
  4227. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4228. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4229. {
  4230. }
  4231. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4232. {
  4233. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4234. }
  4235. };
  4236. //=================================================================================
  4237. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4238. {
  4239. IHThorChildIteratorArg &helper;
  4240. public:
  4241. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4242. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4243. {
  4244. }
  4245. virtual bool needsAllocator() const { return true; }
  4246. virtual const void *nextInGroup()
  4247. {
  4248. ActivityTimer t(totalCycles, timeActivities);
  4249. if (eof)
  4250. return NULL;
  4251. bool ok;
  4252. if (first)
  4253. {
  4254. ok = helper.first();
  4255. first = false;
  4256. }
  4257. else
  4258. ok = helper.next();
  4259. try
  4260. {
  4261. while (ok)
  4262. {
  4263. processed++;
  4264. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4265. unsigned outSize = helper.transform(rowBuilder);
  4266. if (outSize)
  4267. return rowBuilder.finalizeRowClear(outSize);
  4268. ok = helper.next();
  4269. }
  4270. }
  4271. catch (IException *E)
  4272. {
  4273. throw makeWrappedException(E);
  4274. }
  4275. eof = true;
  4276. return NULL;
  4277. }
  4278. };
  4279. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4280. {
  4281. public:
  4282. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4283. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4284. {
  4285. }
  4286. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4287. {
  4288. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4289. }
  4290. };
  4291. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4292. {
  4293. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4294. }
  4295. //=================================================================================
  4296. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4297. {
  4298. IHThorChildNormalizeArg &helper;
  4299. public:
  4300. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4301. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4302. {
  4303. }
  4304. virtual bool needsAllocator() const { return true; }
  4305. virtual const void *nextInGroup()
  4306. {
  4307. ActivityTimer t(totalCycles, timeActivities);
  4308. if (eof)
  4309. return NULL;
  4310. bool ok;
  4311. if (first)
  4312. {
  4313. ok = helper.first();
  4314. first = false;
  4315. }
  4316. else
  4317. ok = helper.next();
  4318. if (ok)
  4319. {
  4320. try
  4321. {
  4322. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4323. do {
  4324. unsigned outSize = helper.transform(rowBuilder);
  4325. if (outSize)
  4326. {
  4327. processed++;
  4328. return rowBuilder.finalizeRowClear(outSize);
  4329. }
  4330. ok = helper.next();
  4331. }
  4332. while (ok);
  4333. }
  4334. catch (IException *E)
  4335. {
  4336. throw makeWrappedException(E);
  4337. }
  4338. }
  4339. eof = true;
  4340. return NULL;
  4341. }
  4342. };
  4343. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4344. {
  4345. public:
  4346. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4347. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4348. {
  4349. }
  4350. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4351. {
  4352. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4353. }
  4354. };
  4355. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4356. {
  4357. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4358. }
  4359. //=================================================================================
  4360. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4361. {
  4362. IHThorChildAggregateArg &helper;
  4363. public:
  4364. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4365. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4366. {
  4367. }
  4368. virtual bool needsAllocator() const { return true; }
  4369. virtual const void *nextInGroup()
  4370. {
  4371. ActivityTimer t(totalCycles, timeActivities);
  4372. if (eof)
  4373. return NULL;
  4374. eof = true;
  4375. processed++;
  4376. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4377. helper.clearAggregate(rowBuilder);
  4378. helper.processRows(rowBuilder);
  4379. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4380. return rowBuilder.finalizeRowClear(finalSize);
  4381. }
  4382. };
  4383. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4384. {
  4385. public:
  4386. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4387. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4388. {
  4389. }
  4390. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4391. {
  4392. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4393. }
  4394. };
  4395. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4396. {
  4397. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4398. }
  4399. //=================================================================================
  4400. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4401. {
  4402. IHThorChildGroupAggregateArg &helper;
  4403. RowAggregator aggregated;
  4404. public:
  4405. IMPLEMENT_IINTERFACE
  4406. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4407. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4408. aggregated(helper, helper)
  4409. {
  4410. }
  4411. void processRow(const void * next)
  4412. {
  4413. aggregated.addRow(next);
  4414. }
  4415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4416. {
  4417. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4418. aggregated.start(rowAllocator);
  4419. }
  4420. virtual void reset()
  4421. {
  4422. aggregated.reset();
  4423. CRoxieServerChildBaseActivity::reset();
  4424. }
  4425. virtual bool needsAllocator() const { return true; }
  4426. virtual const void *nextInGroup()
  4427. {
  4428. ActivityTimer t(totalCycles, timeActivities);
  4429. if (eof)
  4430. return NULL;
  4431. if (first)
  4432. {
  4433. helper.processRows(this);
  4434. first = false;
  4435. }
  4436. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4437. if (next)
  4438. {
  4439. processed++;
  4440. return next->finalizeRowClear();
  4441. }
  4442. eof = true;
  4443. return NULL;
  4444. }
  4445. };
  4446. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4447. {
  4448. public:
  4449. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4450. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4451. {
  4452. }
  4453. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4454. {
  4455. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4456. }
  4457. };
  4458. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4459. {
  4460. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4461. }
  4462. //=================================================================================
  4463. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4464. {
  4465. IHThorChildThroughNormalizeArg &helper;
  4466. const void * lastInput;
  4467. unsigned numProcessedLastGroup;
  4468. bool ok;
  4469. public:
  4470. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4471. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4472. {
  4473. lastInput = NULL;
  4474. numProcessedLastGroup = 0;
  4475. ok = false;
  4476. }
  4477. virtual void stop(bool aborting)
  4478. {
  4479. CRoxieServerChildBaseActivity::stop(aborting);
  4480. ReleaseRoxieRow(lastInput);
  4481. lastInput = NULL;
  4482. }
  4483. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4484. {
  4485. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4486. numProcessedLastGroup = processed;
  4487. ok = false;
  4488. }
  4489. virtual bool needsAllocator() const { return true; }
  4490. virtual const void *nextInGroup()
  4491. {
  4492. ActivityTimer t(totalCycles, timeActivities);
  4493. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4494. loop
  4495. {
  4496. if (ok)
  4497. ok = helper.next();
  4498. while (!ok)
  4499. {
  4500. ReleaseRoxieRow(lastInput);
  4501. lastInput = input->nextInGroup();
  4502. if (!lastInput)
  4503. {
  4504. if (numProcessedLastGroup != processed)
  4505. {
  4506. numProcessedLastGroup = processed;
  4507. return NULL;
  4508. }
  4509. lastInput = input->nextInGroup();
  4510. if (!lastInput)
  4511. return NULL;
  4512. }
  4513. ok = helper.first(lastInput);
  4514. }
  4515. try
  4516. {
  4517. do
  4518. {
  4519. unsigned outSize = helper.transform(rowBuilder);
  4520. if (outSize)
  4521. {
  4522. processed++;
  4523. return rowBuilder.finalizeRowClear(outSize);
  4524. }
  4525. ok = helper.next();
  4526. } while (ok);
  4527. }
  4528. catch (IException *E)
  4529. {
  4530. throw makeWrappedException(E);
  4531. }
  4532. }
  4533. }
  4534. };
  4535. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4536. {
  4537. public:
  4538. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4539. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4540. {
  4541. }
  4542. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4543. {
  4544. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4545. }
  4546. };
  4547. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4548. {
  4549. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4550. }
  4551. //=================================================================================
  4552. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  4553. {
  4554. IHThorDistributionArg &helper;
  4555. public:
  4556. CRoxieServerDistributionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4557. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  4558. {
  4559. }
  4560. virtual void onExecute()
  4561. {
  4562. MemoryAttr ma;
  4563. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  4564. helper.clearAggregate(accumulator);
  4565. OwnedConstRoxieRow nextrec(input->nextInGroup());
  4566. loop
  4567. {
  4568. if (!nextrec)
  4569. {
  4570. nextrec.setown(input->nextInGroup());
  4571. if (!nextrec)
  4572. break;
  4573. }
  4574. helper.process(accumulator, nextrec);
  4575. nextrec.setown(input->nextInGroup());
  4576. }
  4577. StringBuffer result;
  4578. result.append("<XML>");
  4579. helper.gatherResult(accumulator, result);
  4580. result.append("</XML>");
  4581. helper.sendResult(result.length(), result.str());
  4582. helper.destruct(accumulator);
  4583. }
  4584. };
  4585. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  4586. {
  4587. bool isRoot;
  4588. public:
  4589. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4590. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4591. {
  4592. }
  4593. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4594. {
  4595. return new CRoxieServerDistributionActivity(this, _probeManager);
  4596. }
  4597. virtual bool isSink() const
  4598. {
  4599. return isRoot;
  4600. }
  4601. };
  4602. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4603. {
  4604. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4605. }
  4606. //=================================================================================
  4607. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4608. {
  4609. IHThorLinkedRawIteratorArg &helper;
  4610. public:
  4611. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4612. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4613. {
  4614. }
  4615. virtual const void *nextInGroup()
  4616. {
  4617. ActivityTimer t(totalCycles, timeActivities);
  4618. const void *ret =helper.next();
  4619. if (ret)
  4620. {
  4621. LinkRoxieRow(ret);
  4622. processed++;
  4623. }
  4624. return ret;
  4625. }
  4626. };
  4627. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4628. {
  4629. public:
  4630. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4631. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4632. {
  4633. }
  4634. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4635. {
  4636. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4637. }
  4638. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4639. {
  4640. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4641. }
  4642. };
  4643. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4644. {
  4645. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4646. }
  4647. //=================================================================================
  4648. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4649. {
  4650. public:
  4651. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4652. : CRoxieServerActivity(_factory, _probeManager)
  4653. {
  4654. }
  4655. virtual const void *nextInGroup()
  4656. {
  4657. throwUnexpected();
  4658. }
  4659. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4660. {
  4661. try
  4662. {
  4663. start(parentExtractSize, parentExtract, false);
  4664. {
  4665. ActivityTimer t(totalCycles, timeActivities);
  4666. MemoryBuffer result;
  4667. IRecordSize * inputMeta = input->queryOutputMeta();
  4668. loop
  4669. {
  4670. const void *nextrec = input->nextInGroup();
  4671. if (!nextrec)
  4672. {
  4673. nextrec = input->nextInGroup();
  4674. if (!nextrec)
  4675. break;
  4676. }
  4677. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4678. ReleaseRoxieRow(nextrec);
  4679. }
  4680. retSize = result.length();
  4681. ret = result.detach();
  4682. }
  4683. stop(false);
  4684. reset();
  4685. }
  4686. catch(IException *E)
  4687. {
  4688. ctx->notifyAbort(E);
  4689. stop(true);
  4690. reset();
  4691. throw;
  4692. }
  4693. catch(...)
  4694. {
  4695. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4696. ctx->notifyAbort(E);
  4697. stop(true);
  4698. reset();
  4699. throw;
  4700. }
  4701. }
  4702. };
  4703. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4704. {
  4705. bool isRoot;
  4706. public:
  4707. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4708. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4709. {
  4710. }
  4711. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4712. {
  4713. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4714. }
  4715. virtual bool isSink() const
  4716. {
  4717. return isRoot;
  4718. }
  4719. };
  4720. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4721. {
  4722. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4723. }
  4724. //=================================================================================
  4725. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4726. {
  4727. IHThorInlineTableArg &helper;
  4728. __uint64 curRow;
  4729. __uint64 numRows;
  4730. public:
  4731. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4732. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4733. {
  4734. curRow = 0;
  4735. numRows = 0;
  4736. }
  4737. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4738. {
  4739. curRow = 0;
  4740. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4741. numRows = helper.numRows();
  4742. }
  4743. virtual bool needsAllocator() const { return true; }
  4744. virtual const void *nextInGroup()
  4745. {
  4746. ActivityTimer t(totalCycles, timeActivities);
  4747. // Filtering empty rows, returns the next valid row
  4748. while (curRow < numRows)
  4749. {
  4750. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4751. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4752. if (outSize)
  4753. {
  4754. processed++;
  4755. return rowBuilder.finalizeRowClear(outSize);
  4756. }
  4757. }
  4758. return NULL;
  4759. }
  4760. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4761. {
  4762. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4763. }
  4764. };
  4765. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4766. {
  4767. public:
  4768. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4769. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4770. {
  4771. }
  4772. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4773. {
  4774. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4775. }
  4776. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4777. {
  4778. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4779. }
  4780. };
  4781. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4782. {
  4783. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4784. }
  4785. //=================================================================================
  4786. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4787. {
  4788. IHThorWorkunitReadArg &helper;
  4789. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4790. public:
  4791. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4792. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4793. {
  4794. }
  4795. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4796. {
  4797. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4798. if (!ctx->queryServerContext())
  4799. {
  4800. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4801. }
  4802. }
  4803. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4804. {
  4805. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4806. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4807. OwnedRoxieString fromWuid(helper.getWUID());
  4808. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4809. // MORE _ should that be in onCreate?
  4810. }
  4811. virtual void reset()
  4812. {
  4813. wuReader.clear();
  4814. CRoxieServerActivity::reset();
  4815. };
  4816. virtual bool needsAllocator() const { return true; }
  4817. virtual const void *nextInGroup()
  4818. {
  4819. ActivityTimer t(totalCycles, timeActivities);
  4820. const void *ret = wuReader->nextInGroup();
  4821. if (ret)
  4822. processed++;
  4823. return ret;
  4824. }
  4825. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4826. {
  4827. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4828. }
  4829. };
  4830. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4831. {
  4832. public:
  4833. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4834. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4835. {
  4836. }
  4837. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4838. {
  4839. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4840. }
  4841. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4842. {
  4843. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4844. }
  4845. };
  4846. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4847. {
  4848. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4849. }
  4850. //=================================================================================
  4851. interface ILocalGraphEx : public IEclGraphResults
  4852. {
  4853. public:
  4854. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4855. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4856. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4857. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4858. };
  4859. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4860. {
  4861. public:
  4862. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4863. IMPLEMENT_IINTERFACE
  4864. virtual IOutputMetaData * queryOutputMeta() const
  4865. {
  4866. return input->queryOutputMeta();
  4867. }
  4868. virtual unsigned queryId() const
  4869. {
  4870. return input->queryId();
  4871. }
  4872. virtual unsigned __int64 queryTotalCycles() const
  4873. {
  4874. return input->queryTotalCycles();
  4875. }
  4876. virtual unsigned __int64 queryLocalCycles() const
  4877. {
  4878. return input->queryLocalCycles();
  4879. }
  4880. virtual IRoxieInput *queryInput(unsigned idx) const
  4881. {
  4882. return input->queryInput(idx);
  4883. }
  4884. virtual IRoxieServerActivity *queryActivity()
  4885. {
  4886. return input->queryActivity();
  4887. }
  4888. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4889. {
  4890. return input->queryIndexReadActivity();
  4891. }
  4892. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4893. {
  4894. CriticalBlock procedure(cs);
  4895. input->start(parentExtractSize, parentExtract, paused);
  4896. }
  4897. virtual void stop(bool aborting)
  4898. {
  4899. CriticalBlock procedure(cs);
  4900. input->stop(aborting);
  4901. }
  4902. virtual void reset()
  4903. {
  4904. CriticalBlock procedure(cs);
  4905. input->reset();
  4906. }
  4907. virtual void resetEOF()
  4908. {
  4909. CriticalBlock procedure(cs);
  4910. input->resetEOF();
  4911. }
  4912. virtual void checkAbort()
  4913. {
  4914. CriticalBlock procedure(cs);
  4915. input->checkAbort();
  4916. }
  4917. virtual const void *nextInGroup()
  4918. {
  4919. CriticalBlock procedure(cs);
  4920. return input->nextInGroup();
  4921. }
  4922. virtual bool nextGroup(ConstPointerArray & group)
  4923. {
  4924. CriticalBlock procedure(cs);
  4925. return input->nextGroup(group);
  4926. }
  4927. private:
  4928. CriticalSection cs;
  4929. Linked<IRoxieInput> input;
  4930. };
  4931. //=================================================================================
  4932. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4933. {
  4934. public:
  4935. IMPLEMENT_IINTERFACE;
  4936. CPseudoRoxieInput()
  4937. {
  4938. }
  4939. virtual unsigned __int64 queryTotalCycles() const
  4940. {
  4941. return 0;
  4942. }
  4943. virtual unsigned __int64 queryLocalCycles() const
  4944. {
  4945. return 0;
  4946. }
  4947. virtual IRoxieInput *queryInput(unsigned idx) const
  4948. {
  4949. return NULL;
  4950. }
  4951. virtual IRoxieServerActivity *queryActivity()
  4952. {
  4953. throwUnexpected();
  4954. }
  4955. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4956. {
  4957. throwUnexpected();
  4958. }
  4959. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4960. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4961. virtual void stop(bool aborting) { }
  4962. virtual void reset() { }
  4963. virtual void checkAbort() { }
  4964. virtual unsigned queryId() const { throwUnexpected(); }
  4965. virtual void resetEOF() { }
  4966. };
  4967. class CIndirectRoxieInput : public CPseudoRoxieInput
  4968. {
  4969. public:
  4970. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4971. {
  4972. }
  4973. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4974. {
  4975. input->start(parentExtractSize, parentExtract, paused);
  4976. }
  4977. virtual void stop(bool aborting)
  4978. {
  4979. input->stop(aborting);
  4980. }
  4981. virtual void reset()
  4982. {
  4983. input->reset();
  4984. }
  4985. virtual void checkAbort()
  4986. {
  4987. input->checkAbort();
  4988. }
  4989. virtual const void * nextInGroup()
  4990. {
  4991. return input->nextInGroup();
  4992. }
  4993. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4994. {
  4995. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4996. }
  4997. virtual unsigned __int64 queryTotalCycles() const
  4998. {
  4999. return input->queryTotalCycles();
  5000. }
  5001. virtual unsigned __int64 queryLocalCycles() const
  5002. {
  5003. return input->queryLocalCycles();
  5004. }
  5005. virtual IRoxieInput *queryInput(unsigned idx) const
  5006. {
  5007. return input->queryInput(idx);
  5008. }
  5009. virtual unsigned queryId() const
  5010. {
  5011. return input->queryId();
  5012. }
  5013. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5014. {
  5015. return input->gatherConjunctions(collector);
  5016. }
  5017. virtual void resetEOF()
  5018. {
  5019. input->resetEOF();
  5020. }
  5021. virtual unsigned numConcreteOutputs() const
  5022. {
  5023. return input->numConcreteOutputs();
  5024. }
  5025. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  5026. {
  5027. return input->queryConcreteInput(idx);
  5028. }
  5029. virtual IOutputMetaData * queryOutputMeta() const
  5030. {
  5031. return input->queryOutputMeta();
  5032. }
  5033. virtual IRoxieServerActivity *queryActivity()
  5034. {
  5035. return input->queryActivity();
  5036. }
  5037. void setInput(IRoxieInput * _input)
  5038. {
  5039. input = _input;
  5040. }
  5041. protected:
  5042. IRoxieInput * input;
  5043. };
  5044. class CExtractMapperInput : public CIndirectRoxieInput
  5045. {
  5046. unsigned savedParentExtractSize;
  5047. const byte * savedParentExtract;
  5048. public:
  5049. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  5050. {
  5051. savedParentExtractSize = 0;
  5052. savedParentExtract = NULL;
  5053. }
  5054. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5055. {
  5056. input->start(savedParentExtractSize, savedParentExtract, paused);
  5057. }
  5058. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5059. {
  5060. savedParentExtractSize = _savedParentExtractSize;
  5061. savedParentExtract = _savedParentExtract;
  5062. }
  5063. };
  5064. class CGraphResult : public CInterface, implements IGraphResult
  5065. {
  5066. CriticalSection cs;
  5067. byte **rowset;
  5068. size32_t count;
  5069. bool complete;
  5070. void clear()
  5071. {
  5072. CriticalBlock func(cs);
  5073. rtlReleaseRowset(count, rowset);
  5074. rowset = NULL;
  5075. count = 0;
  5076. complete = false;
  5077. }
  5078. public:
  5079. IMPLEMENT_IINTERFACE
  5080. CGraphResult()
  5081. {
  5082. complete = false; // dummy result is not supposed to be used...
  5083. rowset = NULL;
  5084. count = 0;
  5085. }
  5086. CGraphResult(size32_t _count, byte **_rowset)
  5087. : count(_count), rowset(_rowset)
  5088. {
  5089. complete = true;
  5090. }
  5091. ~CGraphResult()
  5092. {
  5093. clear();
  5094. }
  5095. // interface IGraphResult
  5096. virtual IRoxieInput * createIterator()
  5097. {
  5098. if (!complete)
  5099. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5100. return new CGraphResultIterator(this);
  5101. }
  5102. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5103. {
  5104. if (!complete)
  5105. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5106. result = rtlLinkRowset(rowset);
  5107. countResult = count;
  5108. }
  5109. virtual const void * getLinkedRowResult()
  5110. {
  5111. if (!complete)
  5112. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5113. if (count != 1)
  5114. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5115. const void * ret = rowset[0];
  5116. LinkRoxieRow(ret);
  5117. return ret;
  5118. }
  5119. //other
  5120. const void * getRow(unsigned i)
  5121. {
  5122. CriticalBlock func(cs);
  5123. if (i >= count)
  5124. return NULL;
  5125. const void * ret = rowset[i];
  5126. if (ret) LinkRoxieRow(ret);
  5127. return ret;
  5128. }
  5129. protected:
  5130. class CGraphResultIterator : public CPseudoRoxieInput
  5131. {
  5132. unsigned i;
  5133. Linked<CGraphResult> result;
  5134. public:
  5135. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5136. IMPLEMENT_IINTERFACE
  5137. public:
  5138. virtual const void * nextInGroup()
  5139. {
  5140. return result->getRow(i++);
  5141. }
  5142. };
  5143. };
  5144. //=================================================================================
  5145. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5146. {
  5147. IHThorLocalResultReadArg &helper;
  5148. Owned<IRoxieInput> iter;
  5149. ILocalGraphEx * graph;
  5150. unsigned graphId;
  5151. unsigned sequence;
  5152. public:
  5153. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5154. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5155. {
  5156. graph = NULL;
  5157. sequence = 0;
  5158. }
  5159. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5160. {
  5161. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5162. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5163. sequence = helper.querySequence();
  5164. }
  5165. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5166. {
  5167. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5168. iter.setown(graph->createResultIterator(sequence));
  5169. }
  5170. virtual void reset()
  5171. {
  5172. iter.clear();
  5173. CRoxieServerActivity::reset();
  5174. };
  5175. virtual const void *nextInGroup()
  5176. {
  5177. ActivityTimer t(totalCycles, timeActivities);
  5178. const void * next = iter->nextInGroup();
  5179. if (next)
  5180. {
  5181. processed++;
  5182. atomic_inc(&rowsIn);
  5183. }
  5184. return next;
  5185. }
  5186. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5187. {
  5188. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5189. }
  5190. };
  5191. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5192. {
  5193. unsigned graphId;
  5194. public:
  5195. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5196. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5197. {
  5198. }
  5199. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5200. {
  5201. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5202. }
  5203. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5204. {
  5205. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5206. }
  5207. };
  5208. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5209. {
  5210. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5211. }
  5212. //=================================================================================
  5213. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5214. {
  5215. IHThorLocalResultReadArg &helper;
  5216. Owned<IRoxieInput> streamInput;
  5217. unsigned sequence;
  5218. public:
  5219. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5220. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5221. {
  5222. sequence = 0;
  5223. }
  5224. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5225. {
  5226. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5227. sequence = helper.querySequence();
  5228. }
  5229. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5230. {
  5231. assertex(streamInput != NULL);
  5232. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5233. streamInput->start(parentExtractSize, parentExtract, paused);
  5234. }
  5235. virtual void stop(bool aborting)
  5236. {
  5237. CRoxieServerActivity::stop(aborting);
  5238. streamInput->stop(aborting);
  5239. }
  5240. virtual void reset()
  5241. {
  5242. streamInput->reset();
  5243. CRoxieServerActivity::reset();
  5244. };
  5245. virtual const void *nextInGroup()
  5246. {
  5247. ActivityTimer t(totalCycles, timeActivities);
  5248. const void * next = streamInput->nextInGroup();
  5249. if (next)
  5250. {
  5251. processed++;
  5252. atomic_inc(&rowsIn);
  5253. }
  5254. return next;
  5255. }
  5256. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5257. {
  5258. if (id == sequence)
  5259. {
  5260. streamInput.set(_input);
  5261. return true;
  5262. }
  5263. return false;
  5264. }
  5265. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5266. {
  5267. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5268. }
  5269. };
  5270. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5271. {
  5272. public:
  5273. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5274. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5275. {
  5276. }
  5277. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5278. {
  5279. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5280. }
  5281. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5282. {
  5283. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5284. }
  5285. };
  5286. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5287. {
  5288. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5289. }
  5290. //=====================================================================================================
  5291. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5292. {
  5293. IHThorLocalResultWriteArg &helper;
  5294. ILocalGraphEx * graph;
  5295. unsigned graphId;
  5296. public:
  5297. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5298. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5299. {
  5300. graph = NULL;
  5301. }
  5302. virtual bool needsAllocator() const { return true; }
  5303. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5304. {
  5305. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5306. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5307. }
  5308. virtual void onExecute()
  5309. {
  5310. RtlLinkedDatasetBuilder builder(rowAllocator);
  5311. input->readAll(builder);
  5312. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5313. graph->setResult(helper.querySequence(), result);
  5314. }
  5315. virtual const void *nextInGroup()
  5316. {
  5317. return input->nextInGroup(); // I can act as a passthrough input
  5318. }
  5319. IRoxieInput * querySelectOutput(unsigned id)
  5320. {
  5321. if (id == helper.querySequence())
  5322. {
  5323. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5324. return LINK(this);
  5325. }
  5326. return NULL;
  5327. }
  5328. };
  5329. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5330. {
  5331. unsigned graphId;
  5332. public:
  5333. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5334. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5335. {
  5336. isInternal = true;
  5337. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5338. }
  5339. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5340. {
  5341. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId, usageCount);
  5342. }
  5343. };
  5344. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5345. {
  5346. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5347. }
  5348. //=====================================================================================================
  5349. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5350. {
  5351. IHThorDictionaryResultWriteArg &helper;
  5352. ILocalGraphEx * graph;
  5353. unsigned graphId;
  5354. public:
  5355. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  5356. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5357. {
  5358. graph = NULL;
  5359. }
  5360. virtual bool needsAllocator() const { return true; }
  5361. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5362. {
  5363. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5364. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5365. }
  5366. virtual void onExecute()
  5367. {
  5368. unsigned sequence = helper.querySequence();
  5369. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5370. loop
  5371. {
  5372. const void *row = input->nextInGroup();
  5373. if (!row)
  5374. {
  5375. row = input->nextInGroup();
  5376. if (!row)
  5377. break;
  5378. }
  5379. builder.appendOwn(row);
  5380. processed++;
  5381. }
  5382. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5383. graph->setResult(helper.querySequence(), result);
  5384. }
  5385. virtual const void *nextInGroup()
  5386. {
  5387. return input->nextInGroup(); // I can act as a passthrough input
  5388. }
  5389. IRoxieInput * querySelectOutput(unsigned id)
  5390. {
  5391. if (id == helper.querySequence())
  5392. {
  5393. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  5394. return LINK(this);
  5395. }
  5396. return NULL;
  5397. }
  5398. };
  5399. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5400. {
  5401. unsigned graphId;
  5402. public:
  5403. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5404. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5405. {
  5406. isInternal = true;
  5407. }
  5408. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5409. {
  5410. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, usageCount, graphId);
  5411. }
  5412. };
  5413. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5414. {
  5415. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5416. }
  5417. //=================================================================================
  5418. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5419. {
  5420. protected:
  5421. IHThorGraphLoopResultReadArg &helper;
  5422. Owned<IRoxieInput> iter;
  5423. ILocalGraphEx * graph;
  5424. unsigned graphId;
  5425. unsigned sequence;
  5426. public:
  5427. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5428. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5429. {
  5430. graph = NULL;
  5431. sequence = 0;
  5432. }
  5433. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5434. {
  5435. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5436. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5437. }
  5438. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5439. {
  5440. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5441. if (iter)
  5442. iter->start(parentExtractSize, parentExtract, paused);
  5443. else
  5444. {
  5445. sequence = helper.querySequence();
  5446. if ((int)sequence >= 0)
  5447. {
  5448. try
  5449. {
  5450. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5451. }
  5452. catch (IException * E)
  5453. {
  5454. throw makeWrappedException(E);
  5455. }
  5456. }
  5457. }
  5458. }
  5459. virtual void stop(bool aborting)
  5460. {
  5461. if (iter)
  5462. iter->stop(aborting);
  5463. CRoxieServerActivity::stop(aborting);
  5464. }
  5465. virtual void reset()
  5466. {
  5467. if (iter)
  5468. iter->reset();
  5469. iter.clear();
  5470. CRoxieServerActivity::reset();
  5471. };
  5472. virtual const void *nextInGroup()
  5473. {
  5474. ActivityTimer t(totalCycles, timeActivities);
  5475. const void * next = iter ? iter->nextInGroup() : NULL;
  5476. if (next)
  5477. {
  5478. processed++;
  5479. atomic_inc(&rowsIn);
  5480. }
  5481. return next;
  5482. }
  5483. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5484. {
  5485. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5486. }
  5487. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5488. {
  5489. ensureCreated();
  5490. basehelper.onStart(parentExtract, NULL);
  5491. processor.noteUseIteration(helper.querySequence());
  5492. }
  5493. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5494. {
  5495. //helper already initialised from the gratherIterationUsage() call.
  5496. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5497. }
  5498. virtual IInputSteppingMeta * querySteppingMeta()
  5499. {
  5500. assertex(iter);
  5501. return iter->querySteppingMeta();
  5502. }
  5503. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5504. {
  5505. assertex(iter);
  5506. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5507. }
  5508. };
  5509. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5510. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5511. {
  5512. public:
  5513. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5514. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5515. {
  5516. sequence = _sequence;
  5517. }
  5518. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5519. {
  5520. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5521. if ((int)sequence >= 0)
  5522. {
  5523. try
  5524. {
  5525. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5526. }
  5527. catch (IException * E)
  5528. {
  5529. throw makeWrappedException(E);
  5530. }
  5531. }
  5532. }
  5533. };
  5534. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5535. {
  5536. unsigned graphId;
  5537. public:
  5538. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5539. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5540. {
  5541. }
  5542. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5543. {
  5544. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5545. }
  5546. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5547. {
  5548. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5549. }
  5550. };
  5551. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5552. {
  5553. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5554. }
  5555. //=====================================================================================================
  5556. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5557. {
  5558. IHThorGraphLoopResultWriteArg &helper;
  5559. ILocalGraphEx * graph;
  5560. unsigned graphId;
  5561. public:
  5562. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  5563. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5564. {
  5565. graph = NULL;
  5566. }
  5567. virtual bool needsAllocator() const { return true; }
  5568. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5569. {
  5570. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5571. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5572. }
  5573. virtual void onExecute()
  5574. {
  5575. RtlLinkedDatasetBuilder builder(rowAllocator);
  5576. input->readAll(builder);
  5577. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5578. graph->setGraphLoopResult(result);
  5579. }
  5580. virtual IRoxieInput *queryOutput(unsigned idx)
  5581. {
  5582. if (idx==0)
  5583. return this;
  5584. else
  5585. return NULL;
  5586. }
  5587. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5588. {
  5589. return input->gatherConjunctions(collector);
  5590. }
  5591. virtual void resetEOF()
  5592. {
  5593. input->resetEOF();
  5594. }
  5595. virtual const void *nextInGroup()
  5596. {
  5597. const void * next = input->nextInGroup();
  5598. if (next)
  5599. processed++;
  5600. return next;
  5601. }
  5602. virtual bool isPassThrough()
  5603. {
  5604. return true;
  5605. }
  5606. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5607. {
  5608. ActivityTimer t(totalCycles, timeActivities);
  5609. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5610. if (next)
  5611. processed++;
  5612. return next;
  5613. }
  5614. IInputSteppingMeta * querySteppingMeta()
  5615. {
  5616. return input->querySteppingMeta();
  5617. }
  5618. virtual IOutputMetaData * queryOutputMeta() const
  5619. {
  5620. return input->queryOutputMeta();
  5621. }
  5622. };
  5623. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5624. {
  5625. unsigned graphId;
  5626. public:
  5627. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5628. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5629. {
  5630. isInternal = true;
  5631. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5632. }
  5633. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5634. {
  5635. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId, usageCount);
  5636. }
  5637. };
  5638. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5639. {
  5640. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5641. }
  5642. #if 0
  5643. //=====================================================================================================
  5644. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5645. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5646. {
  5647. next = NULL;
  5648. }
  5649. void CHThorLocalResultSpillActivity::ready()
  5650. {
  5651. CHThorSimpleActivityBase::ready();
  5652. next = input->nextInGroup();
  5653. grouped = input->isGrouped();
  5654. rowdata.clear();
  5655. }
  5656. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5657. {
  5658. const void * ret = next;
  5659. next = input->nextInGroup();
  5660. if (!ret && !next)
  5661. return NULL;
  5662. if (ret)
  5663. {
  5664. size32_t thisSize = outputMeta->getRecordSize(ret);
  5665. rowdata.append(thisSize, ret);
  5666. if (grouped)
  5667. rowdata.append(next == NULL);
  5668. }
  5669. return ret;
  5670. }
  5671. void CHThorLocalResultSpillActivity::done()
  5672. {
  5673. loop
  5674. {
  5675. const void * ret = nextInGroup();
  5676. if (!ret)
  5677. {
  5678. ret = nextInGroup();
  5679. if (!ret)
  5680. break;
  5681. }
  5682. ReleaseRoxieRow(ret);
  5683. }
  5684. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5685. CHThorSimpleActivityBase::done();
  5686. }
  5687. #endif
  5688. //=================================================================================
  5689. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5690. {
  5691. protected:
  5692. IHThorDedupArg &helper;
  5693. unsigned numKept;
  5694. unsigned numToKeep;
  5695. public:
  5696. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5697. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5698. {
  5699. numKept = 0;
  5700. numToKeep = 0;
  5701. }
  5702. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5703. {
  5704. numKept = 0;
  5705. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5706. numToKeep = helper.numToKeep();
  5707. }
  5708. };
  5709. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5710. {
  5711. IRangeCompare * stepCompare;
  5712. const void *prev;
  5713. public:
  5714. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5715. : CRoxieServerDedupActivity(_factory, _probeManager)
  5716. {
  5717. prev = NULL;
  5718. stepCompare = NULL;
  5719. }
  5720. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5721. {
  5722. prev = NULL;
  5723. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5724. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5725. stepCompare = NULL;
  5726. if (stepMeta)
  5727. stepCompare = stepMeta->queryCompare();
  5728. }
  5729. virtual void reset()
  5730. {
  5731. ReleaseClearRoxieRow(prev);
  5732. CRoxieServerDedupActivity::reset();
  5733. }
  5734. virtual const void * nextInGroup()
  5735. {
  5736. ActivityTimer t(totalCycles, timeActivities);
  5737. const void * next;
  5738. loop
  5739. {
  5740. next = input->nextInGroup();
  5741. if (!prev || !next || !helper.matches(prev,next))
  5742. {
  5743. numKept = 0;
  5744. break;
  5745. }
  5746. if (numKept < numToKeep-1)
  5747. {
  5748. numKept++;
  5749. break;
  5750. }
  5751. ReleaseRoxieRow(next);
  5752. }
  5753. ReleaseRoxieRow(prev);
  5754. prev = next;
  5755. if (next)
  5756. {
  5757. LinkRoxieRow(next);
  5758. processed++;
  5759. }
  5760. return next;
  5761. }
  5762. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5763. {
  5764. ActivityTimer t(totalCycles, timeActivities);
  5765. const void * next;
  5766. loop
  5767. {
  5768. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5769. //If the record was an in-exact match from the index then return it immediately
  5770. //and don't cause it to dedup following legal records.
  5771. if (!wasCompleteMatch)
  5772. {
  5773. assertex(stepExtra.returnMismatches());
  5774. return next;
  5775. }
  5776. if (!prev || !next || !helper.matches(prev,next))
  5777. {
  5778. numKept = 0;
  5779. break;
  5780. }
  5781. if (numKept < numToKeep-1)
  5782. {
  5783. numKept++;
  5784. break;
  5785. }
  5786. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5787. if (stepExtra.returnMismatches())
  5788. {
  5789. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5790. //condition to advance
  5791. if (stepCompare->docompare(next, seek, numFields) != 0)
  5792. {
  5793. wasCompleteMatch = false;
  5794. break;
  5795. }
  5796. }
  5797. ReleaseRoxieRow(next);
  5798. }
  5799. ReleaseRoxieRow(prev);
  5800. prev = next;
  5801. if (next)
  5802. {
  5803. LinkRoxieRow(next);
  5804. processed++;
  5805. }
  5806. return next;
  5807. }
  5808. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5809. {
  5810. return input->gatherConjunctions(collector);
  5811. }
  5812. virtual void resetEOF()
  5813. {
  5814. input->resetEOF();
  5815. }
  5816. IInputSteppingMeta * querySteppingMeta()
  5817. {
  5818. return input->querySteppingMeta();
  5819. }
  5820. };
  5821. //=================================================================================
  5822. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5823. {
  5824. const void *kept;
  5825. bool first;
  5826. public:
  5827. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5828. : CRoxieServerDedupActivity(_factory, _probeManager)
  5829. {
  5830. kept = NULL;
  5831. first = true;
  5832. }
  5833. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5834. {
  5835. first = true;
  5836. kept = NULL;
  5837. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5838. }
  5839. virtual void reset()
  5840. {
  5841. ReleaseClearRoxieRow(kept);
  5842. CRoxieServerActivity::reset();
  5843. }
  5844. virtual const void * nextInGroup()
  5845. {
  5846. ActivityTimer t(totalCycles, timeActivities);
  5847. if (first)
  5848. {
  5849. kept = input->nextInGroup();
  5850. first = false;
  5851. }
  5852. const void * next;
  5853. loop
  5854. {
  5855. next = input->nextInGroup();
  5856. if (!kept || !next || !helper.matches(kept,next))
  5857. {
  5858. numKept = 0;
  5859. break;
  5860. }
  5861. if (numKept < numToKeep-1)
  5862. {
  5863. numKept++;
  5864. break;
  5865. }
  5866. ReleaseRoxieRow(kept);
  5867. kept = next;
  5868. }
  5869. const void * ret = kept;
  5870. kept = next;
  5871. // CTXLOG("dedup returns %p", ret);
  5872. if (ret) processed++;
  5873. return ret;
  5874. }
  5875. };
  5876. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5877. {
  5878. IHThorDedupArg &helper;
  5879. unsigned survivorIndex;
  5880. ConstPointerArray survivors;
  5881. bool keepLeft;
  5882. bool eof;
  5883. bool first;
  5884. ICompare *primaryCompare;
  5885. public:
  5886. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5887. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5888. {
  5889. keepLeft = _keepLeft;
  5890. primaryCompare = helper.queryComparePrimary();
  5891. eof = false;
  5892. first = true;
  5893. survivorIndex = 0;
  5894. }
  5895. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5896. {
  5897. eof = false;
  5898. first = true;
  5899. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5900. }
  5901. virtual void reset()
  5902. {
  5903. #ifdef _DEBUG
  5904. while (survivors.isItem(survivorIndex))
  5905. {
  5906. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5907. }
  5908. #endif
  5909. survivors.kill();
  5910. eof = false;
  5911. first = true;
  5912. CRoxieServerActivity::reset();
  5913. }
  5914. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5915. {
  5916. for (unsigned idxL = first; idxL < last; idxL++)
  5917. {
  5918. const void * left = group.item(idxL);
  5919. if (left)
  5920. {
  5921. for (unsigned idxR = first; idxR < last; idxR++)
  5922. {
  5923. const void * right = group.item(idxR);
  5924. if ((idxL != idxR) && right)
  5925. {
  5926. if (helper.matches(left, right))
  5927. {
  5928. if (keepLeft)
  5929. {
  5930. group.replace(NULL, idxR);
  5931. ReleaseRoxieRow(right);
  5932. }
  5933. else
  5934. {
  5935. group.replace(NULL, idxL);
  5936. ReleaseRoxieRow(left);
  5937. break;
  5938. }
  5939. }
  5940. }
  5941. }
  5942. }
  5943. }
  5944. }
  5945. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5946. {
  5947. for (unsigned idxL = first; idxL < last; idxL++)
  5948. {
  5949. void * left = *(index[idxL]);
  5950. if (left)
  5951. {
  5952. for (unsigned idxR = first; idxR < last; idxR++)
  5953. {
  5954. void * right = *(index[idxR]);
  5955. if ((idxL != idxR) && right)
  5956. {
  5957. if (helper.matches(left, right))
  5958. {
  5959. if (keepLeft)
  5960. {
  5961. *(index[idxR]) = NULL;
  5962. ReleaseRoxieRow(right);
  5963. }
  5964. else
  5965. {
  5966. *(index[idxL]) = NULL;
  5967. ReleaseRoxieRow(left);
  5968. break;
  5969. }
  5970. }
  5971. }
  5972. }
  5973. }
  5974. }
  5975. }
  5976. bool calcNextDedupAll()
  5977. {
  5978. survivors.kill();
  5979. survivorIndex = 0;
  5980. ConstPointerArray group;
  5981. if (eof || !input->nextGroup(group))
  5982. {
  5983. eof = true;
  5984. return false;
  5985. }
  5986. unsigned max = group.ordinality();
  5987. if (primaryCompare)
  5988. {
  5989. //hard, if not impossible, to hit this code once optimisations in place
  5990. MemoryAttr indexbuff(max*sizeof(void **));
  5991. void *** index = (void ***)indexbuff.bufferBase();
  5992. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  5993. unsigned first = 0;
  5994. for (unsigned idx = 1; idx < max; idx++)
  5995. {
  5996. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  5997. {
  5998. dedupRangeIndirect(first, idx, index);
  5999. first = idx;
  6000. }
  6001. }
  6002. dedupRangeIndirect(first, max, index);
  6003. for(unsigned idx2=0; idx2<max; ++idx2)
  6004. {
  6005. void * cur = *(index[idx2]);
  6006. if(cur)
  6007. survivors.append(cur);
  6008. }
  6009. }
  6010. else
  6011. {
  6012. dedupRange(0, max, group);
  6013. for(unsigned idx=0; idx<max; ++idx)
  6014. {
  6015. const void * cur = group.item(idx);
  6016. if(cur)
  6017. survivors.append(cur);
  6018. }
  6019. }
  6020. return true;
  6021. }
  6022. virtual const void *nextInGroup()
  6023. {
  6024. ActivityTimer t(totalCycles, timeActivities);
  6025. if (first)
  6026. {
  6027. calcNextDedupAll();
  6028. first = false;
  6029. }
  6030. while (survivors.isItem(survivorIndex))
  6031. {
  6032. const void *ret = survivors.item(survivorIndex++);
  6033. if (ret)
  6034. {
  6035. processed++;
  6036. return ret;
  6037. }
  6038. }
  6039. calcNextDedupAll();
  6040. return NULL;
  6041. }
  6042. };
  6043. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6044. {
  6045. bool compareAll;
  6046. bool keepLeft;
  6047. public:
  6048. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6049. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6050. {
  6051. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6052. compareAll = helper->compareAll();
  6053. keepLeft = helper->keepLeft();
  6054. }
  6055. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6056. {
  6057. if (compareAll)
  6058. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  6059. else if (keepLeft)
  6060. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  6061. else
  6062. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  6063. }
  6064. };
  6065. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6066. {
  6067. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6068. }
  6069. //=================================================================================
  6070. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6071. {
  6072. bool eof;
  6073. IHThorHashDedupArg &helper;
  6074. class HashDedupElement
  6075. {
  6076. public:
  6077. HashDedupElement(unsigned _hash, const void *_keyRow)
  6078. : hash(_hash), keyRow(_keyRow)
  6079. {
  6080. }
  6081. ~HashDedupElement()
  6082. {
  6083. ReleaseRoxieRow(keyRow);
  6084. }
  6085. inline unsigned queryHash() const
  6086. {
  6087. return hash;
  6088. }
  6089. inline const void *queryRow() const
  6090. {
  6091. return keyRow;
  6092. }
  6093. private:
  6094. unsigned hash;
  6095. const void *keyRow;
  6096. };
  6097. class HashDedupTable : public SuperHashTable
  6098. {
  6099. public:
  6100. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  6101. : helper(_helper),
  6102. activityId(_activityId),
  6103. keySize(helper.queryKeySize())
  6104. {
  6105. }
  6106. virtual ~HashDedupTable() { releaseAll(); }
  6107. virtual unsigned getHashFromElement(const void *et) const
  6108. {
  6109. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6110. return element->queryHash();
  6111. }
  6112. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6113. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6114. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6115. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6116. {
  6117. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6118. if (fphash != element->queryHash())
  6119. return false;
  6120. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6121. }
  6122. virtual void onAdd(void *et) {}
  6123. virtual void onRemove(void *et)
  6124. {
  6125. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6126. delete element;
  6127. }
  6128. void onCreate(IRoxieSlaveContext *ctx)
  6129. {
  6130. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6131. }
  6132. void reset()
  6133. {
  6134. kill();
  6135. }
  6136. bool insert(const void * row)
  6137. {
  6138. unsigned hash = helper.queryHash()->hash(row);
  6139. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6140. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6141. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6142. if (find(hash, keyRow.get()))
  6143. return false;
  6144. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6145. return true;
  6146. }
  6147. private:
  6148. IHThorHashDedupArg & helper;
  6149. CachedOutputMetaData keySize;
  6150. Owned<IEngineRowAllocator> keyRowAllocator;
  6151. unsigned activityId;
  6152. } table;
  6153. public:
  6154. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6155. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6156. {
  6157. eof = false;
  6158. }
  6159. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6160. {
  6161. eof = false;
  6162. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6163. }
  6164. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6165. {
  6166. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6167. table.onCreate(ctx);
  6168. }
  6169. virtual void reset()
  6170. {
  6171. table.reset();
  6172. eof = false;
  6173. CRoxieServerActivity::reset();
  6174. }
  6175. virtual const void *nextInGroup()
  6176. {
  6177. ActivityTimer t(totalCycles, timeActivities);
  6178. while(!eof)
  6179. {
  6180. const void * next = input->nextInGroup();
  6181. if(!next)
  6182. {
  6183. if (table.count() == 0)
  6184. eof = true;
  6185. table.reset();
  6186. return NULL;
  6187. }
  6188. if(table.insert(next))
  6189. return next;
  6190. else
  6191. ReleaseRoxieRow(next);
  6192. }
  6193. return NULL;
  6194. }
  6195. };
  6196. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6197. {
  6198. public:
  6199. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6200. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6201. {
  6202. }
  6203. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6204. {
  6205. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6206. }
  6207. };
  6208. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6209. {
  6210. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6211. }
  6212. //=================================================================================
  6213. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6214. {
  6215. IHThorRollupArg &helper;
  6216. OwnedConstRoxieRow left;
  6217. OwnedConstRoxieRow prev;
  6218. OwnedConstRoxieRow right;
  6219. bool readFirstRow;
  6220. public:
  6221. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6222. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6223. {
  6224. readFirstRow = false;
  6225. }
  6226. ~CRoxieServerRollupActivity()
  6227. {
  6228. }
  6229. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6230. {
  6231. readFirstRow = false;
  6232. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6233. }
  6234. virtual void reset()
  6235. {
  6236. left.clear();
  6237. prev.clear();
  6238. right.clear();
  6239. CRoxieServerActivity::reset();
  6240. }
  6241. virtual bool needsAllocator() const { return true; }
  6242. virtual const void * nextInGroup()
  6243. {
  6244. ActivityTimer t(totalCycles, timeActivities);
  6245. if (!readFirstRow)
  6246. {
  6247. left.setown(input->nextInGroup());
  6248. prev.set(left);
  6249. readFirstRow = true;
  6250. }
  6251. loop
  6252. {
  6253. right.setown(input->nextInGroup());
  6254. if(!prev || !right || !helper.matches(prev,right))
  6255. {
  6256. const void * ret = left.getClear();
  6257. if(ret)
  6258. processed++;
  6259. left.setown(right.getClear());
  6260. prev.set(left);
  6261. return ret;
  6262. }
  6263. try
  6264. {
  6265. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6266. unsigned outSize = helper.transform(rowBuilder, left, right);
  6267. if (outSize)
  6268. left.setown(rowBuilder.finalizeRowClear(outSize));
  6269. if (helper.getFlags() & RFrolledismatchleft)
  6270. prev.set(left);
  6271. else
  6272. prev.set(right);
  6273. }
  6274. catch(IException * E)
  6275. {
  6276. throw makeWrappedException(E);
  6277. }
  6278. }
  6279. }
  6280. };
  6281. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6282. {
  6283. public:
  6284. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6285. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6286. {
  6287. }
  6288. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6289. {
  6290. return new CRoxieServerRollupActivity(this, _probeManager);
  6291. }
  6292. };
  6293. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6294. {
  6295. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6296. }
  6297. //=================================================================================
  6298. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6299. {
  6300. IHThorNormalizeArg &helper;
  6301. unsigned numThisRow;
  6302. unsigned curRow;
  6303. const void *buffer;
  6304. unsigned numProcessedLastGroup;
  6305. public:
  6306. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6307. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6308. {
  6309. buffer = NULL;
  6310. numThisRow = 0;
  6311. curRow = 0;
  6312. numProcessedLastGroup = 0;
  6313. }
  6314. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6315. {
  6316. numThisRow = 0;
  6317. curRow = 0;
  6318. numProcessedLastGroup = 0;
  6319. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6320. }
  6321. virtual void reset()
  6322. {
  6323. ReleaseClearRoxieRow(buffer);
  6324. CRoxieServerActivity::reset();
  6325. }
  6326. virtual bool needsAllocator() const { return true; }
  6327. virtual const void * nextInGroup()
  6328. {
  6329. ActivityTimer t(totalCycles, timeActivities);
  6330. loop
  6331. {
  6332. while (curRow == numThisRow)
  6333. {
  6334. if (buffer)
  6335. ReleaseClearRoxieRow(buffer);
  6336. buffer = input->nextInGroup();
  6337. if (!buffer && (processed == numProcessedLastGroup))
  6338. buffer = input->nextInGroup();
  6339. if (!buffer)
  6340. {
  6341. numProcessedLastGroup = processed;
  6342. return NULL;
  6343. }
  6344. curRow = 0;
  6345. numThisRow = helper.numExpandedRows(buffer);
  6346. }
  6347. try
  6348. {
  6349. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6350. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6351. if (actualSize != 0)
  6352. {
  6353. processed++;
  6354. return rowBuilder.finalizeRowClear(actualSize);
  6355. }
  6356. }
  6357. catch (IException *E)
  6358. {
  6359. throw makeWrappedException(E);
  6360. }
  6361. }
  6362. }
  6363. };
  6364. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6365. {
  6366. public:
  6367. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6368. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6369. {
  6370. }
  6371. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6372. {
  6373. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6374. }
  6375. };
  6376. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6377. {
  6378. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6379. }
  6380. //=================================================================================
  6381. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6382. {
  6383. IHThorNormalizeChildArg &helper;
  6384. unsigned numThisRow;
  6385. unsigned curRow;
  6386. const void *buffer;
  6387. unsigned numProcessedLastGroup;
  6388. INormalizeChildIterator * cursor;
  6389. const void * curChildRow;
  6390. bool advanceInput()
  6391. {
  6392. loop
  6393. {
  6394. ReleaseClearRoxieRow(buffer);
  6395. buffer = input->nextInGroup();
  6396. if (!buffer && (processed == numProcessedLastGroup))
  6397. buffer = input->nextInGroup();
  6398. if (!buffer)
  6399. {
  6400. numProcessedLastGroup = processed;
  6401. return false;
  6402. }
  6403. curChildRow = cursor->first(buffer);
  6404. if (curChildRow)
  6405. {
  6406. curRow = 0;
  6407. return true;
  6408. }
  6409. }
  6410. }
  6411. public:
  6412. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6413. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6414. {
  6415. buffer = NULL;
  6416. cursor = NULL;
  6417. numThisRow = 0;
  6418. curRow = 0;
  6419. numProcessedLastGroup = 0;
  6420. curChildRow = NULL;
  6421. }
  6422. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6423. {
  6424. numThisRow = 0;
  6425. curRow = 0;
  6426. numProcessedLastGroup = 0;
  6427. curChildRow = NULL;
  6428. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6429. cursor = helper.queryIterator();
  6430. }
  6431. virtual void stop(bool aborting)
  6432. {
  6433. CRoxieServerActivity::stop(aborting);
  6434. }
  6435. virtual void reset()
  6436. {
  6437. cursor = NULL;
  6438. ReleaseClearRoxieRow(buffer);
  6439. CRoxieServerActivity::reset();
  6440. }
  6441. virtual bool needsAllocator() const { return true; }
  6442. const void *nextInGroup()
  6443. {
  6444. ActivityTimer t(totalCycles, timeActivities);
  6445. loop
  6446. {
  6447. if (!buffer)
  6448. {
  6449. if (!advanceInput())
  6450. return NULL;
  6451. }
  6452. try
  6453. {
  6454. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6455. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6456. curChildRow = cursor->next();
  6457. if (!curChildRow)
  6458. ReleaseClearRoxieRow(buffer);
  6459. if (outSize != 0)
  6460. {
  6461. processed++;
  6462. return rowBuilder.finalizeRowClear(outSize);
  6463. }
  6464. }
  6465. catch (IException *E)
  6466. {
  6467. throw makeWrappedException(E);
  6468. }
  6469. }
  6470. }
  6471. };
  6472. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6473. {
  6474. public:
  6475. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6476. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6477. {
  6478. }
  6479. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6480. {
  6481. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6482. }
  6483. };
  6484. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6485. {
  6486. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6487. }
  6488. //=================================================================================
  6489. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6490. {
  6491. IHThorNormalizeLinkedChildArg &helper;
  6492. OwnedConstRoxieRow curParent;
  6493. OwnedConstRoxieRow curChild;
  6494. unsigned numProcessedLastGroup;
  6495. bool advanceInput()
  6496. {
  6497. loop
  6498. {
  6499. curParent.setown(input->nextInGroup());
  6500. if (!curParent && (processed == numProcessedLastGroup))
  6501. curParent.setown(input->nextInGroup());
  6502. if (!curParent)
  6503. {
  6504. numProcessedLastGroup = processed;
  6505. return false;
  6506. }
  6507. curChild.set(helper.first(curParent));
  6508. if (curChild)
  6509. return true;
  6510. }
  6511. }
  6512. public:
  6513. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6514. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6515. {
  6516. numProcessedLastGroup = 0;
  6517. }
  6518. ~CRoxieServerNormalizeLinkedChildActivity()
  6519. {
  6520. }
  6521. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6522. {
  6523. numProcessedLastGroup = 0;
  6524. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6525. }
  6526. virtual void reset()
  6527. {
  6528. curParent.clear();
  6529. curChild.clear();
  6530. CRoxieServerActivity::reset();
  6531. }
  6532. const void *nextInGroup()
  6533. {
  6534. ActivityTimer t(totalCycles, timeActivities);
  6535. loop
  6536. {
  6537. if (!curParent)
  6538. {
  6539. if (!advanceInput())
  6540. return NULL;
  6541. }
  6542. try
  6543. {
  6544. const void *ret = curChild.getClear();
  6545. curChild.set(helper.next());
  6546. if (!curChild)
  6547. curParent.clear();
  6548. if (ret)
  6549. {
  6550. processed++;
  6551. return ret;
  6552. }
  6553. }
  6554. catch (IException *E)
  6555. {
  6556. throw makeWrappedException(E);
  6557. }
  6558. }
  6559. }
  6560. };
  6561. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6562. {
  6563. public:
  6564. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6565. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6566. {
  6567. }
  6568. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6569. {
  6570. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6571. }
  6572. };
  6573. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6574. {
  6575. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6576. }
  6577. //=================================================================================
  6578. interface ISortAlgorithm : extends IInterface
  6579. {
  6580. virtual void prepare(IRoxieInput *input) = 0;
  6581. virtual const void *next() = 0;
  6582. virtual void reset() = 0;
  6583. };
  6584. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6585. {
  6586. protected:
  6587. unsigned curIndex;
  6588. ConstPointerArray sorted;
  6589. ICompare *compare;
  6590. public:
  6591. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6592. {
  6593. curIndex = 0;
  6594. }
  6595. virtual void prepare(IRoxieInput *input)
  6596. {
  6597. curIndex = 0;
  6598. if (input->nextGroup(sorted))
  6599. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6600. }
  6601. virtual const void *next()
  6602. {
  6603. if (sorted.isItem(curIndex))
  6604. return sorted.item(curIndex++);
  6605. return NULL;
  6606. }
  6607. virtual void reset()
  6608. {
  6609. while (sorted.isItem(curIndex))
  6610. ReleaseRoxieRow(sorted.item(curIndex++));
  6611. curIndex = 0;
  6612. sorted.kill();
  6613. }
  6614. };
  6615. class CStableQuickSortAlgorithm : public CQuickSortAlgorithm
  6616. {
  6617. public:
  6618. CStableQuickSortAlgorithm(ICompare *_compare) : CQuickSortAlgorithm(_compare)
  6619. {
  6620. }
  6621. virtual void prepare(IRoxieInput *input)
  6622. {
  6623. curIndex = 0;
  6624. if (input->nextGroup(sorted))
  6625. {
  6626. unsigned numRows = sorted.ordinality();
  6627. void **rows = const_cast<void * *>(sorted.getArray());
  6628. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6629. void **temp = (void **) tempAttr.bufferBase();
  6630. memcpy(temp, rows, numRows*sizeof(void **));
  6631. qsortvecstable(temp, numRows, *compare, (void ***)rows);
  6632. for (unsigned i = 0; i < numRows; i++)
  6633. {
  6634. *rows = **((void ***)rows);
  6635. rows++;
  6636. }
  6637. }
  6638. }
  6639. };
  6640. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6641. {
  6642. enum {
  6643. InitialSortElements = 0,
  6644. //The number of rows that can be added without entering a critical section, and therefore also the number
  6645. //of rows that might not get freed when memory gets tight.
  6646. CommitStep=32
  6647. };
  6648. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6649. roxiemem::RoxieSimpleInputRowArray sorted;
  6650. ICompare *compare;
  6651. IRoxieSlaveContext * ctx;
  6652. Owned<IDiskMerger> diskMerger;
  6653. Owned<IRowStream> diskReader;
  6654. IOutputMetaData *rowMeta;
  6655. unsigned activityId;
  6656. bool stable;
  6657. public:
  6658. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId, bool _stable)
  6659. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep, _activityId),
  6660. ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId), stable(_stable)
  6661. {
  6662. ctx->queryRowManager().addRowBuffer(this);
  6663. }
  6664. ~CSpillingQuickSortAlgorithm()
  6665. {
  6666. ctx->queryRowManager().removeRowBuffer(this);
  6667. diskReader.clear();
  6668. }
  6669. virtual void prepare(IRoxieInput *input)
  6670. {
  6671. loop
  6672. {
  6673. const void * next = input->nextInGroup();
  6674. if (!next)
  6675. break;
  6676. if (!rowsToSort.append(next))
  6677. {
  6678. {
  6679. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6680. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6681. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6682. //rows first).
  6683. if (rowsToSort.numCommitted() != 0)
  6684. {
  6685. rowsToSort.flush();
  6686. spillRows();
  6687. }
  6688. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6689. //spillRows() cannot shift active row pointer since it can be called from any thread
  6690. rowsToSort.flush();
  6691. }
  6692. if (!rowsToSort.append(next))
  6693. {
  6694. ReleaseRoxieRow(next);
  6695. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6696. }
  6697. }
  6698. }
  6699. rowsToSort.flush();
  6700. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6701. if (diskMerger)
  6702. {
  6703. spillRows();
  6704. rowsToSort.kill();
  6705. diskReader.setown(diskMerger->merge(compare));
  6706. }
  6707. else
  6708. {
  6709. unsigned numRows = rowsToSort.numCommitted();
  6710. if (numRows)
  6711. {
  6712. void ** rows = const_cast<void * *>(rowsToSort.getBlock(numRows));
  6713. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6714. if (stable)
  6715. {
  6716. MemoryAttr tempAttr(numRows*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  6717. void **temp = (void **) tempAttr.bufferBase();
  6718. memcpy(temp, rows, numRows*sizeof(void **));
  6719. qsortvecstable(temp, numRows, *compare, (void ***)rows);
  6720. for (unsigned i = 0; i < numRows; i++)
  6721. {
  6722. *rows = **((void ***)rows);
  6723. rows++;
  6724. }
  6725. }
  6726. else
  6727. qsortvec(rows, numRows, *compare);
  6728. }
  6729. sorted.transferFrom(rowsToSort);
  6730. }
  6731. }
  6732. virtual const void *next()
  6733. {
  6734. if(diskReader)
  6735. return diskReader->nextRow();
  6736. return sorted.dequeue();
  6737. }
  6738. virtual void reset()
  6739. {
  6740. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6741. //fewer heap allocations with not freeing up the memory from large group sorts.
  6742. rowsToSort.clearRows();
  6743. sorted.kill();
  6744. //Disk reader must be cleared before the merger - or the files may still be locked.
  6745. diskReader.clear();
  6746. diskMerger.clear();
  6747. }
  6748. //interface roxiemem::IBufferedRowCallback
  6749. virtual unsigned getSpillCost() const
  6750. {
  6751. //Spill global sorts before grouped sorts
  6752. if (rowMeta->isGrouped())
  6753. return 20;
  6754. return 10;
  6755. }
  6756. virtual bool freeBufferedRows(bool critical)
  6757. {
  6758. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6759. return spillRows();
  6760. }
  6761. protected:
  6762. bool spillRows()
  6763. {
  6764. unsigned numRows = rowsToSort.numCommitted();
  6765. if (numRows == 0)
  6766. return false;
  6767. const void * * rows = rowsToSort.getBlock(numRows);
  6768. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6769. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6770. for (unsigned i= 0; i < numRows; i++)
  6771. {
  6772. out->putRow(rows[i]);
  6773. }
  6774. rowsToSort.noteSpilled(numRows);
  6775. return true;
  6776. }
  6777. IDiskMerger * queryMerger()
  6778. {
  6779. if (!diskMerger)
  6780. {
  6781. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6782. StringBuffer spillBasename;
  6783. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%" I64F "u", seq);
  6784. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6785. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6786. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6787. }
  6788. return diskMerger;
  6789. }
  6790. };
  6791. #define INSERTION_SORT_BLOCKSIZE 1024
  6792. class SortedBlock : public CInterface, implements IInterface
  6793. {
  6794. unsigned sequence;
  6795. const void **rows;
  6796. unsigned length;
  6797. unsigned pos;
  6798. SortedBlock(const SortedBlock &);
  6799. public:
  6800. IMPLEMENT_IINTERFACE;
  6801. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6802. {
  6803. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6804. length = 0;
  6805. pos = 0;
  6806. }
  6807. ~SortedBlock()
  6808. {
  6809. while (pos < length)
  6810. ReleaseRoxieRow(rows[pos++]);
  6811. ReleaseRoxieRow(rows);
  6812. }
  6813. int compareTo(SortedBlock *r, ICompare *compare)
  6814. {
  6815. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6816. if (!rc)
  6817. rc = sequence - r->sequence;
  6818. return rc;
  6819. }
  6820. const void *next()
  6821. {
  6822. if (pos < length)
  6823. return rows[pos++];
  6824. else
  6825. return NULL;
  6826. }
  6827. inline bool eof()
  6828. {
  6829. return pos==length;
  6830. }
  6831. bool insert(const void *next, ICompare *_compare )
  6832. {
  6833. unsigned b = length;
  6834. if (b == INSERTION_SORT_BLOCKSIZE)
  6835. return false;
  6836. else if (b < 7)
  6837. {
  6838. while (b)
  6839. {
  6840. if (_compare->docompare(next, rows[b-1]) >= 0)
  6841. break;
  6842. b--;
  6843. }
  6844. if (b != length)
  6845. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6846. rows[b] = next;
  6847. length++;
  6848. return true;
  6849. }
  6850. else
  6851. {
  6852. unsigned int a = 0;
  6853. while ((int)a<b)
  6854. {
  6855. int i = (a+b)/2;
  6856. int rc = _compare->docompare(next, rows[i]);
  6857. if (rc>=0)
  6858. a = i+1;
  6859. else
  6860. b = i;
  6861. }
  6862. if (a != length)
  6863. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6864. rows[a] = next;
  6865. length++;
  6866. return true;
  6867. }
  6868. }
  6869. };
  6870. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6871. {
  6872. SortedBlock *curBlock;
  6873. unsigned blockNo;
  6874. IArrayOf<SortedBlock> blocks;
  6875. unsigned activityId;
  6876. IRowManager *rowManager;
  6877. ICompare *compare;
  6878. void newBlock()
  6879. {
  6880. blocks.append(*curBlock);
  6881. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6882. }
  6883. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6884. {
  6885. return l.compareTo(&r, compare);
  6886. }
  6887. void makeHeap()
  6888. {
  6889. /* Permute blocks to establish the heap property
  6890. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6891. The children of p must both be greater than or equal to p
  6892. The parent of a child c is given by p = (c-1)/2
  6893. */
  6894. unsigned i;
  6895. unsigned n = blocks.length();
  6896. SortedBlock **s = blocks.getArray();
  6897. for (i=1; i<n; i++)
  6898. {
  6899. SortedBlock * r = s[i];
  6900. int c = i; /* child */
  6901. while (c > 0)
  6902. {
  6903. int p = (c-1)/2; /* parent */
  6904. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6905. break;
  6906. s[c] = s[p];
  6907. s[p] = r;
  6908. c = p;
  6909. }
  6910. }
  6911. }
  6912. void remakeHeap()
  6913. {
  6914. /* The row associated with block[0] will have changed
  6915. This code restores the heap property
  6916. */
  6917. unsigned p = 0; /* parent */
  6918. unsigned n = blocks.length();
  6919. SortedBlock **s = blocks.getArray();
  6920. while (1)
  6921. {
  6922. unsigned c = p*2 + 1; /* child */
  6923. if ( c >= n )
  6924. break;
  6925. /* Select smaller child */
  6926. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6927. /* If child is greater or equal than parent then we are done */
  6928. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6929. break;
  6930. /* Swap parent and child */
  6931. SortedBlock *r = s[c];
  6932. s[c] = s[p];
  6933. s[p] = r;
  6934. /* child becomes parent */
  6935. p = c;
  6936. }
  6937. }
  6938. public:
  6939. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6940. : compare(_compare)
  6941. {
  6942. rowManager = _rowManager;
  6943. activityId = _activityId;
  6944. curBlock = NULL;
  6945. blockNo = 0;
  6946. }
  6947. virtual void reset()
  6948. {
  6949. blocks.kill();
  6950. delete curBlock;
  6951. curBlock = NULL;
  6952. blockNo = 0;
  6953. }
  6954. virtual void prepare(IRoxieInput *input)
  6955. {
  6956. blockNo = 0;
  6957. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6958. loop
  6959. {
  6960. const void *next = input->nextInGroup();
  6961. if (!next)
  6962. break;
  6963. if (!curBlock->insert(next, compare))
  6964. {
  6965. newBlock();
  6966. curBlock->insert(next, compare);
  6967. }
  6968. }
  6969. if (blockNo > 1)
  6970. {
  6971. blocks.append(*curBlock);
  6972. curBlock = NULL;
  6973. makeHeap();
  6974. }
  6975. }
  6976. virtual const void * next()
  6977. {
  6978. const void *ret;
  6979. if (blockNo==1) // single block case..
  6980. {
  6981. ret = curBlock->next();
  6982. }
  6983. else if (blocks.length())
  6984. {
  6985. SortedBlock &top = blocks.item(0);
  6986. ret = top.next();
  6987. if (top.eof())
  6988. blocks.replace(blocks.popGet(), 0);
  6989. remakeHeap();
  6990. }
  6991. else
  6992. ret = NULL;
  6993. return ret;
  6994. }
  6995. };
  6996. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6997. {
  6998. unsigned curIndex;
  6999. ConstPointerArray sorted;
  7000. bool inputAlreadySorted;
  7001. IntArray sequences;
  7002. bool eof;
  7003. ICompare *compare;
  7004. #ifdef _CHECK_HEAPSORT
  7005. void checkHeap() const
  7006. {
  7007. unsigned n = sorted.ordinality();
  7008. if (n)
  7009. {
  7010. ICompare *_compare = compare;
  7011. void **s = sorted.getArray();
  7012. int *sq = sequences.getArray();
  7013. unsigned p;
  7014. #if 0
  7015. CTXLOG("------------------------%d entries-----------------", n);
  7016. for (p = 0; p < n; p++)
  7017. {
  7018. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  7019. }
  7020. #endif
  7021. for (p = 0; p < n; p++)
  7022. {
  7023. unsigned c = p*2+1;
  7024. if (c<n)
  7025. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7026. c++;
  7027. if (c<n)
  7028. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  7029. }
  7030. }
  7031. }
  7032. #else
  7033. inline void checkHeap() const {}
  7034. #endif
  7035. const void *removeHeap()
  7036. {
  7037. unsigned n = sorted.ordinality();
  7038. if (n)
  7039. {
  7040. const void *ret = sorted.item(0);
  7041. if (n > 1 && ret)
  7042. {
  7043. ICompare *_compare = compare;
  7044. const void **s = sorted.getArray();
  7045. int *sq = sequences.getArray();
  7046. unsigned v = 0; // vacancy
  7047. loop
  7048. {
  7049. unsigned c = 2*v + 1;
  7050. if (c < n)
  7051. {
  7052. unsigned f = c; // favourite to fill it
  7053. c++;
  7054. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  7055. f = c;
  7056. sq[v] = sq[f];
  7057. if ((s[v] = s[f]) != NULL)
  7058. v = f;
  7059. else
  7060. break;
  7061. }
  7062. else
  7063. {
  7064. s[v] = NULL;
  7065. break;
  7066. }
  7067. }
  7068. }
  7069. checkHeap();
  7070. return ret;
  7071. }
  7072. else
  7073. return NULL;
  7074. }
  7075. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  7076. {
  7077. int rc = _compare->docompare(s[l], s[r]);
  7078. if (!rc)
  7079. rc = sq[l] - sq[r];
  7080. return rc;
  7081. }
  7082. void insertHeap(const void *next)
  7083. {
  7084. // Upside-down heap sort
  7085. // Maintain a heap where every parent is lower than each of its children
  7086. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  7087. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  7088. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  7089. // Nice features:
  7090. // 1. Deterministic
  7091. // 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
  7092. // 3. Already sorted case can be spotted at zero cost while reading.
  7093. // 4. If you don't read all the results, you don't have to complete the sort
  7094. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  7095. unsigned n = sorted.ordinality();
  7096. sorted.append(next);
  7097. sequences.append(n);
  7098. if (!n)
  7099. return;
  7100. ICompare *_compare = compare;
  7101. const void **s = sorted.getArray();
  7102. if (inputAlreadySorted)
  7103. {
  7104. if (_compare->docompare(next, s[n-1]) >= 0)
  7105. return;
  7106. else
  7107. {
  7108. // MORE - could delay creating sequences until now...
  7109. inputAlreadySorted = false;
  7110. }
  7111. }
  7112. int *sq = sequences.getArray();
  7113. unsigned q = n;
  7114. while (n)
  7115. {
  7116. unsigned parent = (n-1) / 2;
  7117. const void *p = s[parent];
  7118. if (_compare->docompare(p, next) <= 0)
  7119. break;
  7120. s[n] = p;
  7121. sq[n] = sq[parent];
  7122. s[parent] = next;
  7123. sq[parent] = q;
  7124. n = parent;
  7125. }
  7126. }
  7127. public:
  7128. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  7129. {
  7130. inputAlreadySorted = true;
  7131. curIndex = 0;
  7132. eof = false;
  7133. }
  7134. virtual void reset()
  7135. {
  7136. eof = false;
  7137. if (inputAlreadySorted)
  7138. {
  7139. while (sorted.isItem(curIndex))
  7140. ReleaseRoxieRow(sorted.item(curIndex++));
  7141. sorted.kill();
  7142. }
  7143. else
  7144. {
  7145. ReleaseRoxieRowSet(sorted);
  7146. }
  7147. inputAlreadySorted = true;
  7148. sequences.kill();
  7149. }
  7150. virtual void prepare(IRoxieInput *input)
  7151. {
  7152. inputAlreadySorted = true;
  7153. curIndex = 0;
  7154. eof = false;
  7155. assertex(sorted.ordinality()==0);
  7156. const void *next = input->nextInGroup();
  7157. if (!next)
  7158. {
  7159. eof = true;
  7160. return;
  7161. }
  7162. loop
  7163. {
  7164. insertHeap(next);
  7165. next = input->nextInGroup();
  7166. if (!next)
  7167. break;
  7168. }
  7169. checkHeap();
  7170. }
  7171. virtual const void * next()
  7172. {
  7173. if (inputAlreadySorted)
  7174. {
  7175. if (sorted.isItem(curIndex))
  7176. {
  7177. return sorted.item(curIndex++);
  7178. }
  7179. else
  7180. return NULL;
  7181. }
  7182. else
  7183. return removeHeap();
  7184. }
  7185. };
  7186. typedef enum {heapSort, insertionSort, quickSort, stableQuickSort, spillingQuickSort, stableSpillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7187. class CRoxieServerSortActivity : public CRoxieServerActivity
  7188. {
  7189. protected:
  7190. IHThorSortArg &helper;
  7191. ICompare *compare;
  7192. Owned<ISortAlgorithm> sorter;
  7193. bool readInput;
  7194. RoxieSortAlgorithm sortAlgorithm;
  7195. unsigned sortFlags;
  7196. public:
  7197. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7198. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7199. {
  7200. compare = helper.queryCompare();
  7201. readInput = false;
  7202. }
  7203. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7204. {
  7205. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7206. switch (sortAlgorithm)
  7207. {
  7208. case heapSort:
  7209. sorter.setown(new CHeapSortAlgorithm(compare));
  7210. break;
  7211. case insertionSort:
  7212. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7213. break;
  7214. case quickSort:
  7215. sorter.setown(new CQuickSortAlgorithm(compare));
  7216. break;
  7217. case stableQuickSort:
  7218. sorter.setown(new CStableQuickSortAlgorithm(compare));
  7219. break;
  7220. case spillingQuickSort:
  7221. case stableSpillingQuickSort:
  7222. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, sortAlgorithm==stableSpillingQuickSort));
  7223. break;
  7224. case unknownSort:
  7225. sorter.clear(); // create it later....
  7226. break;
  7227. default:
  7228. throwUnexpected();
  7229. break;
  7230. }
  7231. }
  7232. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7233. {
  7234. assertex(!readInput);
  7235. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7236. }
  7237. virtual void reset()
  7238. {
  7239. if (sorter)
  7240. sorter->reset();
  7241. readInput = false;
  7242. CRoxieServerActivity::reset();
  7243. }
  7244. virtual const void * nextInGroup()
  7245. {
  7246. ActivityTimer t(totalCycles, timeActivities);
  7247. if (!readInput)
  7248. {
  7249. if (sortAlgorithm == unknownSort)
  7250. {
  7251. sorter.clear();
  7252. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7253. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7254. if (useAlgorithm)
  7255. {
  7256. if (stricmp(useAlgorithm, "quicksort")==0)
  7257. {
  7258. switch (sortFlags & (TAFstable|TAFspill))
  7259. {
  7260. case 0: sortAlgorithm = quickSort; break;
  7261. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7262. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7263. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7264. }
  7265. }
  7266. else if (stricmp(useAlgorithm, "heapsort")==0)
  7267. sorter.setown(new CHeapSortAlgorithm(compare));
  7268. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7269. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7270. else
  7271. {
  7272. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7273. if (sortFlags & TAFspill)
  7274. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId, (sortFlags & TAFstable) != 0));
  7275. else if (sortFlags & TAFunstable)
  7276. sorter.setown(new CQuickSortAlgorithm(compare));
  7277. else
  7278. sorter.setown(new CHeapSortAlgorithm(compare));
  7279. }
  7280. }
  7281. else
  7282. 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...
  7283. }
  7284. sorter->prepare(input);
  7285. readInput = true;
  7286. }
  7287. const void *ret = sorter->next();
  7288. if (ret)
  7289. processed++;
  7290. else
  7291. {
  7292. sorter->reset();
  7293. readInput = false; // ready for next group
  7294. }
  7295. return ret;
  7296. }
  7297. };
  7298. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7299. {
  7300. RoxieSortAlgorithm sortAlgorithm;
  7301. unsigned sortFlags;
  7302. bool forceSpill;
  7303. public:
  7304. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7305. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7306. {
  7307. forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  7308. if (forceSpill)
  7309. {
  7310. sortAlgorithm = stableSpillingQuickSort;
  7311. sortFlags = TAFstable|TAFspill;
  7312. }
  7313. else
  7314. {
  7315. sortAlgorithm = heapSort;
  7316. sortFlags = TAFstable;
  7317. }
  7318. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7319. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7320. if (sortMethod)
  7321. {
  7322. sortFlags = sortMethod->getAlgorithmFlags();
  7323. if (forceSpill)
  7324. sortFlags |= TAFspill;
  7325. if (sortFlags & TAFspill)
  7326. sortAlgorithm = stableSpillingQuickSort;
  7327. else if (sortFlags & TAFunstable)
  7328. sortAlgorithm = quickSort;
  7329. if (!(sortFlags & TAFconstant))
  7330. sortAlgorithm = unknownSort;
  7331. else
  7332. {
  7333. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7334. if (useAlgorithm)
  7335. {
  7336. if (stricmp(useAlgorithm, "quicksort")==0)
  7337. {
  7338. switch (sortFlags & (TAFstable|TAFspill))
  7339. {
  7340. case 0: sortAlgorithm = quickSort; break;
  7341. case TAFstable: sortAlgorithm = stableQuickSort; break;
  7342. case TAFspill: sortAlgorithm = spillingQuickSort; break;
  7343. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSort; break;
  7344. }
  7345. }
  7346. else if (stricmp(useAlgorithm, "heapsort")==0)
  7347. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7348. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7349. sortAlgorithm = insertionSort;
  7350. else
  7351. {
  7352. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7353. if (sortFlags & TAFunstable)
  7354. sortAlgorithm = quickSort;
  7355. else
  7356. sortAlgorithm = heapSort;
  7357. }
  7358. }
  7359. }
  7360. }
  7361. }
  7362. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7363. {
  7364. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7365. }
  7366. };
  7367. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7368. {
  7369. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7370. }
  7371. //=====================================================================================================
  7372. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7373. {
  7374. IHThorSortedArg &helper;
  7375. ICompare * compare;
  7376. const void *prev;
  7377. IRangeCompare * stepCompare;
  7378. public:
  7379. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7380. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7381. {
  7382. prev = NULL;
  7383. compare = helper.queryCompare();
  7384. stepCompare = NULL;
  7385. }
  7386. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7387. {
  7388. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7389. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7390. if (stepMeta)
  7391. stepCompare = stepMeta->queryCompare();
  7392. prev = NULL;
  7393. }
  7394. virtual void reset()
  7395. {
  7396. ReleaseClearRoxieRow(prev);
  7397. CRoxieServerActivity::reset();
  7398. }
  7399. virtual const void * nextInGroup()
  7400. {
  7401. ActivityTimer t(totalCycles, timeActivities);
  7402. const void *ret = input->nextInGroup();
  7403. if (ret && prev && compare->docompare(prev, ret) > 0)
  7404. {
  7405. // MORE - better to give mismatching rows that indexes?
  7406. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7407. }
  7408. ReleaseRoxieRow(prev);
  7409. prev = ret;
  7410. if (ret)
  7411. {
  7412. LinkRoxieRow(prev);
  7413. processed++;
  7414. }
  7415. return ret;
  7416. }
  7417. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7418. {
  7419. ActivityTimer t(totalCycles, timeActivities);
  7420. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7421. if (ret && prev && compare->docompare(prev, ret) > 0)
  7422. {
  7423. // MORE - better to give mismatching rows that indexes?
  7424. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7425. }
  7426. ReleaseRoxieRow(prev);
  7427. prev = ret;
  7428. if (ret)
  7429. {
  7430. LinkRoxieRow(prev);
  7431. processed++;
  7432. }
  7433. return ret;
  7434. }
  7435. IInputSteppingMeta * querySteppingMeta()
  7436. {
  7437. return input->querySteppingMeta();
  7438. }
  7439. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7440. {
  7441. return input->gatherConjunctions(collector);
  7442. }
  7443. virtual void resetEOF()
  7444. {
  7445. input->resetEOF();
  7446. }
  7447. };
  7448. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7449. {
  7450. public:
  7451. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7452. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7453. {
  7454. }
  7455. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7456. {
  7457. return new CRoxieServerSortedActivity(this, _probeManager);
  7458. }
  7459. };
  7460. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7461. {
  7462. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7463. }
  7464. //=====================================================================================================
  7465. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7466. {
  7467. /*
  7468. BE VERY CAREFUL - this code is tricky.
  7469. Note that starts and stops (and resets) can occur in strange orders
  7470. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7471. The last stop should call the upstream stop.
  7472. The first reset should call the upstream reset.
  7473. 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
  7474. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7475. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7476. ignored in the minIndex calculation
  7477. */
  7478. public:
  7479. IHThorArg &helper;
  7480. unsigned activeOutputs;
  7481. unsigned numOutputs;
  7482. unsigned numOriginalOutputs;
  7483. QueueOf<const void, true> buffer;
  7484. CriticalSection crit;
  7485. CriticalSection crit2;
  7486. unsigned tailIdx;
  7487. unsigned headIdx;
  7488. Owned<IException> error;
  7489. class OutputAdaptor : public CInterface, implements IRoxieInput
  7490. {
  7491. bool eof, eofpending, stopped;
  7492. public:
  7493. CRoxieServerThroughSpillActivity *parent;
  7494. unsigned idx;
  7495. unsigned oid;
  7496. unsigned processed;
  7497. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7498. public:
  7499. IMPLEMENT_IINTERFACE;
  7500. OutputAdaptor()
  7501. {
  7502. parent = NULL;
  7503. oid = 0;
  7504. idx = 0;
  7505. processed = 0;
  7506. totalCycles = 0;
  7507. eofpending = false;
  7508. eof = false;
  7509. stopped = false;
  7510. }
  7511. ~OutputAdaptor()
  7512. {
  7513. if (traceStartStop)
  7514. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7515. if (processed && parent && parent->factory)
  7516. {
  7517. parent->factory->noteProcessed(oid, processed);
  7518. if (parent->ctx)
  7519. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  7520. }
  7521. }
  7522. void init()
  7523. {
  7524. if (traceStartStop)
  7525. DBGLOG("%p init Input adaptor %d", this, oid);
  7526. idx = 0;
  7527. processed = 0;
  7528. eofpending = false;
  7529. eof = false;
  7530. stopped = false;
  7531. }
  7532. virtual unsigned queryId() const
  7533. {
  7534. return parent->queryId();
  7535. }
  7536. virtual IRoxieServerActivity *queryActivity()
  7537. {
  7538. return parent;
  7539. }
  7540. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7541. {
  7542. return parent->queryIndexReadActivity();
  7543. }
  7544. virtual unsigned __int64 queryTotalCycles() const
  7545. {
  7546. return totalCycles;
  7547. }
  7548. virtual unsigned __int64 queryLocalCycles() const
  7549. {
  7550. return 0; // Should never be called
  7551. }
  7552. virtual IRoxieInput *queryInput(unsigned idx) const
  7553. {
  7554. return parent->queryInput(idx);
  7555. }
  7556. virtual const void * nextInGroup()
  7557. {
  7558. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7559. if (eof)
  7560. return NULL;
  7561. const void *ret = parent->readBuffered(idx, oid);
  7562. #ifdef TRACE_SPLIT
  7563. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7564. #endif
  7565. if (ret)
  7566. {
  7567. processed++;
  7568. eofpending = false;
  7569. }
  7570. else if (eofpending)
  7571. eof = true;
  7572. else
  7573. eofpending = true;
  7574. return ret;
  7575. }
  7576. virtual IOutputMetaData * queryOutputMeta() const
  7577. {
  7578. return parent->queryOutputMeta();
  7579. }
  7580. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7581. {
  7582. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7583. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7584. // for minIndex to give the correct answers
  7585. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7586. if (traceStartStop)
  7587. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7588. parent->start(oid, parentExtractSize, parentExtract, paused);
  7589. }
  7590. virtual void stop(bool aborting)
  7591. {
  7592. if (traceStartStop)
  7593. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7594. if (!stopped)
  7595. {
  7596. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7597. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7598. }
  7599. };
  7600. virtual void reset()
  7601. {
  7602. if (traceStartStop)
  7603. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7604. parent->reset(oid);
  7605. idx = 0; // value should not be relevant really but this is the safest...
  7606. stopped = false;
  7607. };
  7608. virtual void resetEOF()
  7609. {
  7610. parent->resetEOF();
  7611. }
  7612. virtual void checkAbort()
  7613. {
  7614. parent->checkAbort();
  7615. }
  7616. } *adaptors;
  7617. bool *used;
  7618. unsigned nextFreeOutput()
  7619. {
  7620. unsigned i = numOutputs;
  7621. while (i)
  7622. {
  7623. i--;
  7624. if (!used[i])
  7625. return i;
  7626. }
  7627. throwUnexpected();
  7628. }
  7629. unsigned minIndex(unsigned exceptOid)
  7630. {
  7631. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7632. // this is trying to determine whether any of the adaptors will in the future read a given record
  7633. unsigned minIdx = (unsigned) -1;
  7634. for (unsigned i = 0; i < numOutputs; i++)
  7635. {
  7636. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7637. minIdx = adaptors[i].idx;
  7638. }
  7639. return minIdx;
  7640. }
  7641. inline bool isLastTailReader(unsigned exceptOid)
  7642. {
  7643. for (unsigned i = 0; i < numOutputs; i++)
  7644. {
  7645. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  7646. return false;
  7647. }
  7648. return true;
  7649. }
  7650. void initOutputs()
  7651. {
  7652. activeOutputs = numOutputs;
  7653. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7654. if (used[i])
  7655. adaptors[i].init();
  7656. state = STATEstarting;
  7657. }
  7658. public:
  7659. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7660. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7661. {
  7662. numOriginalOutputs = numOutputs;
  7663. adaptors = new OutputAdaptor[numOutputs];
  7664. used = new bool[numOutputs];
  7665. for (unsigned i = 0; i < numOutputs; i++)
  7666. {
  7667. adaptors[i].parent = this;
  7668. adaptors[i].oid = i;
  7669. used[i] = false;
  7670. }
  7671. tailIdx = 0;
  7672. headIdx = 0;
  7673. activeOutputs = numOutputs;
  7674. }
  7675. ~CRoxieServerThroughSpillActivity()
  7676. {
  7677. delete [] adaptors;
  7678. delete [] used;
  7679. }
  7680. const void *readBuffered(unsigned &idx, unsigned oid)
  7681. {
  7682. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  7683. const unsigned curIdx = idx;
  7684. if (curIdx == headIdx) // test once without getting the crit2 sec
  7685. {
  7686. CriticalBlock b2(crit2); // but only one puller gets to read the head
  7687. if (curIdx == headIdx) // test again now that we have it
  7688. {
  7689. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  7690. if (error)
  7691. throw error.getLink();
  7692. try
  7693. {
  7694. const void *row = input->nextInGroup();
  7695. if (activeOutputs==1)
  7696. {
  7697. #ifdef TRACE_SPLIT
  7698. CTXLOG("spill %d optimised return of %p", activityId, row);
  7699. #endif
  7700. headIdx++;
  7701. idx++;
  7702. return row; // optimization for the case where only one output still active.
  7703. }
  7704. CriticalBlock b(crit);
  7705. headIdx++;
  7706. idx++;
  7707. if (activeOutputs==1)
  7708. return row; // optimization for the case where only one output still active.
  7709. buffer.enqueue(row);
  7710. if (row) LinkRoxieRow(row);
  7711. return row;
  7712. }
  7713. catch (IException *E)
  7714. {
  7715. #ifdef TRACE_SPLIT
  7716. CTXLOG("spill %d caught exception", activityId);
  7717. #endif
  7718. error.set(E);
  7719. throw;
  7720. }
  7721. catch (...)
  7722. {
  7723. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7724. error.set(E);
  7725. throw E;
  7726. }
  7727. }
  7728. }
  7729. CriticalBlock b(crit);
  7730. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  7731. unsigned lidx = curIdx - tailIdx;
  7732. idx++;
  7733. if (!lidx)
  7734. {
  7735. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  7736. // The rationale is that I MUST be the last reader if there are only 2 - the other guy must have put the record there in the first place
  7737. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  7738. {
  7739. tailIdx++;
  7740. const void *ret = buffer.dequeue(); // no need to link - last puller
  7741. #ifdef TRACE_SPLIT
  7742. CTXLOG("last puller return of %p", ret);
  7743. #endif
  7744. return ret;
  7745. }
  7746. }
  7747. const void *ret = buffer.item(lidx);
  7748. if (ret) LinkRoxieRow(ret);
  7749. #ifdef TRACE_SPLIT
  7750. CTXLOG("standard return of %p", ret);
  7751. #endif
  7752. return ret;
  7753. }
  7754. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7755. {
  7756. CriticalBlock b(crit);
  7757. if (error)
  7758. throw error.getLink();
  7759. if (factory)
  7760. factory->noteStarted(oid);
  7761. if (traceStartStop)
  7762. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7763. if (state != STATEstarted)
  7764. {
  7765. if (state != STATEstarting)
  7766. initOutputs();
  7767. tailIdx = 0;
  7768. headIdx = 0;
  7769. error.clear();
  7770. try
  7771. {
  7772. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7773. }
  7774. catch (IException *E)
  7775. {
  7776. #ifdef TRACE_SPLIT
  7777. CTXLOG("spill %d caught exception in start", activityId);
  7778. #endif
  7779. error.set(E);
  7780. throw;
  7781. }
  7782. catch (...)
  7783. {
  7784. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7785. error.set(E);
  7786. throw E;
  7787. }
  7788. }
  7789. }
  7790. void stop(unsigned oid, unsigned & idx, bool aborting)
  7791. {
  7792. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7793. CriticalBlock b(crit);
  7794. #ifdef TRACE_STARTSTOP
  7795. if (traceStartStop)
  7796. {
  7797. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7798. if (watchActivityId && watchActivityId==activityId)
  7799. {
  7800. CTXLOG("WATCH: stop %d", activityId);
  7801. }
  7802. }
  7803. #endif
  7804. if (state != STATEstarting && state != STATEstarted)
  7805. initOutputs();
  7806. if (activeOutputs > 1)
  7807. {
  7808. if (tailIdx==idx)
  7809. {
  7810. // Discard all buffered rows that are there purely for this adaptor to read them
  7811. unsigned min = minIndex(oid);
  7812. if (min != (unsigned) -1)
  7813. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7814. // Should never happen though if there are still some active.
  7815. // there may be a small window where adaptors are blocked on the semaphore...
  7816. {
  7817. #ifdef TRACE_SPLIT
  7818. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7819. #endif
  7820. while (tailIdx < min)
  7821. {
  7822. ReleaseRoxieRow(buffer.dequeue());
  7823. tailIdx++;
  7824. }
  7825. }
  7826. }
  7827. activeOutputs--;
  7828. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7829. return;
  7830. }
  7831. #ifdef TRACE_SPLIT
  7832. CTXLOG("%p: All outputs done", this);
  7833. #endif
  7834. activeOutputs = numOutputs;
  7835. CRoxieServerActivity::stop(aborting);
  7836. };
  7837. void reset(unsigned oid)
  7838. {
  7839. if (traceStartStop)
  7840. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7841. activeOutputs = numOutputs;
  7842. while (buffer.ordinality())
  7843. ReleaseRoxieRow(buffer.dequeue());
  7844. error.clear();
  7845. if (state != STATEreset) // make sure input is only reset once
  7846. CRoxieServerActivity::reset();
  7847. };
  7848. virtual const void *nextInGroup()
  7849. {
  7850. throwUnexpected(); // Internal logic error - we are not anybody's input
  7851. }
  7852. virtual IOutputMetaData * queryOutputMeta() const
  7853. {
  7854. // if (outputMeta)
  7855. // return outputMeta;
  7856. // else
  7857. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7858. }
  7859. virtual IRoxieInput *queryOutput(unsigned idx)
  7860. {
  7861. if (idx==(unsigned)-1)
  7862. idx = nextFreeOutput(); // MORE - what is this used for?
  7863. assertex(idx < numOriginalOutputs);
  7864. assertex(!used[idx]);
  7865. used[idx] = true;
  7866. return &adaptors[idx];
  7867. }
  7868. virtual void resetOutputsUsed()
  7869. {
  7870. numOutputs = 1;
  7871. activeOutputs = 1;
  7872. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7873. }
  7874. virtual void noteOutputUsed()
  7875. {
  7876. assertex(numOutputs < numOriginalOutputs);
  7877. numOutputs++;
  7878. activeOutputs = numOutputs;
  7879. }
  7880. virtual bool isPassThrough()
  7881. {
  7882. return numOutputs==1;
  7883. }
  7884. };
  7885. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7886. {
  7887. public:
  7888. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7889. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7890. {
  7891. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7892. setNumOutputs(helper->getTempUsageCount() + 1);
  7893. }
  7894. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7895. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7896. {
  7897. setNumOutputs(_numOutputs);
  7898. }
  7899. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7900. {
  7901. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7902. }
  7903. };
  7904. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7905. {
  7906. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7907. }
  7908. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7909. {
  7910. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7911. }
  7912. //----------------------------------------------------------------------------------------------
  7913. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7914. {
  7915. public:
  7916. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7917. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7918. {
  7919. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7920. setNumOutputs(helper->numBranches());
  7921. }
  7922. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7923. {
  7924. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7925. }
  7926. };
  7927. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7928. {
  7929. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7930. }
  7931. //=====================================================================================================
  7932. #define PIPE_BUFSIZE 0x8000
  7933. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7934. {
  7935. StringBuffer msg;
  7936. if(pipe->hasError())
  7937. {
  7938. try
  7939. {
  7940. char error[512];
  7941. size32_t sz = pipe->readError(sizeof(error), error);
  7942. if(sz && sz!=(size32_t)-1)
  7943. msg.append(", stderr: '").append(sz, error).append("'");
  7944. }
  7945. catch (IException *e)
  7946. {
  7947. EXCLOG(e, "Error reading pipe stderr");
  7948. e->Release();
  7949. }
  7950. }
  7951. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7952. }
  7953. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7954. {
  7955. IHThorPipeReadArg &helper;
  7956. Owned<IPipeProcess> pipe;
  7957. StringAttr pipeCommand;
  7958. Owned<IOutputRowDeserializer> rowDeserializer;
  7959. Owned<IReadRowStream> readTransformer;
  7960. bool groupSignalled;
  7961. public:
  7962. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7963. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7964. {
  7965. groupSignalled = true;
  7966. }
  7967. virtual bool needsAllocator() const { return true; }
  7968. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7969. {
  7970. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7971. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7972. }
  7973. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7974. {
  7975. groupSignalled = true; // i.e. don't start with a NULL row
  7976. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7977. if (!readTransformer)
  7978. {
  7979. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7980. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7981. }
  7982. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7983. openPipe(pipeProgram);
  7984. }
  7985. virtual void stop(bool aborting)
  7986. {
  7987. CRoxieServerActivity::stop(aborting);
  7988. pipe.clear();
  7989. readTransformer->setStream(NULL);
  7990. }
  7991. virtual const void *nextInGroup()
  7992. {
  7993. ActivityTimer t(totalCycles, timeActivities);
  7994. while (!waitForPipe())
  7995. {
  7996. if (!pipe)
  7997. return NULL;
  7998. if (helper.getPipeFlags() & TPFgroupeachrow)
  7999. {
  8000. if (!groupSignalled)
  8001. {
  8002. groupSignalled = true;
  8003. return NULL;
  8004. }
  8005. }
  8006. }
  8007. const void *ret = readTransformer->next();
  8008. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8009. processed++;
  8010. groupSignalled = false;
  8011. return ret;
  8012. }
  8013. protected:
  8014. bool waitForPipe()
  8015. {
  8016. if (!pipe)
  8017. return false; // done
  8018. if (!readTransformer->eos())
  8019. return true;
  8020. verifyPipe();
  8021. return false;
  8022. }
  8023. void openPipe(char const * cmd)
  8024. {
  8025. pipeCommand.setown(cmd);
  8026. pipe.setown(createPipeProcess());
  8027. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8028. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8029. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8030. readTransformer->setStream(pipeReader.get());
  8031. }
  8032. void verifyPipe()
  8033. {
  8034. if (pipe)
  8035. {
  8036. unsigned err = pipe->wait();
  8037. if(err && !(helper.getPipeFlags() & TPFnofail))
  8038. {
  8039. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8040. }
  8041. pipe.clear();
  8042. }
  8043. }
  8044. };
  8045. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8046. {
  8047. IHThorPipeThroughArg &helper;
  8048. RecordPullerThread puller;
  8049. Owned<IPipeProcess> pipe;
  8050. StringAttr pipeCommand;
  8051. InterruptableSemaphore pipeVerified;
  8052. InterruptableSemaphore pipeOpened;
  8053. CachedOutputMetaData inputMeta;
  8054. Owned<IOutputRowSerializer> rowSerializer;
  8055. Owned<IOutputRowDeserializer> rowDeserializer;
  8056. Owned<IPipeWriteXformHelper> writeTransformer;
  8057. Owned<IReadRowStream> readTransformer;
  8058. bool firstRead;
  8059. bool recreate;
  8060. bool inputExhausted;
  8061. bool groupSignalled;
  8062. public:
  8063. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8064. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8065. {
  8066. recreate = helper.recreateEachRow();
  8067. groupSignalled = true;
  8068. firstRead = false;
  8069. inputExhausted = false;
  8070. }
  8071. virtual bool needsAllocator() const { return true; }
  8072. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8073. {
  8074. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8075. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8076. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8077. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8078. }
  8079. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8080. {
  8081. firstRead = true;
  8082. inputExhausted = false;
  8083. groupSignalled = true; // i.e. don't start with a NULL row
  8084. pipeVerified.reinit();
  8085. pipeOpened.reinit();
  8086. writeTransformer->ready();
  8087. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8088. if (!readTransformer)
  8089. {
  8090. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8091. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8092. }
  8093. if(!recreate)
  8094. {
  8095. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8096. openPipe(pipeProgram);
  8097. }
  8098. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8099. }
  8100. virtual void setInput(unsigned idx, IRoxieInput *_in)
  8101. {
  8102. if (idx)
  8103. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  8104. puller.setInput(this, _in);
  8105. inputMeta.set(_in->queryOutputMeta());
  8106. }
  8107. virtual void stop(bool aborting)
  8108. {
  8109. pipeVerified.interrupt(NULL);
  8110. pipeOpened.interrupt(NULL);
  8111. puller.stop(aborting);
  8112. CRoxieServerActivity::stop(aborting);
  8113. pipe.clear();
  8114. readTransformer->setStream(NULL);
  8115. }
  8116. virtual void reset()
  8117. {
  8118. puller.reset();
  8119. CRoxieServerActivity::reset();
  8120. }
  8121. virtual const void *nextInGroup()
  8122. {
  8123. ActivityTimer t(totalCycles, timeActivities);
  8124. while (!waitForPipe())
  8125. {
  8126. if (!pipe)
  8127. return NULL;
  8128. if (helper.getPipeFlags() & TPFgroupeachrow)
  8129. {
  8130. if (!groupSignalled)
  8131. {
  8132. groupSignalled = true;
  8133. return NULL;
  8134. }
  8135. }
  8136. }
  8137. const void *ret = readTransformer->next();
  8138. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8139. processed++;
  8140. groupSignalled = false;
  8141. return ret;
  8142. }
  8143. virtual void processRow(const void *row)
  8144. {
  8145. // called from puller thread
  8146. if(recreate)
  8147. openPipe(helper.getNameFromRow(row));
  8148. writeTransformer->writeTranslatedText(row, pipe);
  8149. ReleaseRoxieRow(row);
  8150. if(recreate)
  8151. {
  8152. closePipe();
  8153. pipeVerified.wait();
  8154. }
  8155. }
  8156. virtual void processDone()
  8157. {
  8158. // called from puller thread
  8159. if(recreate)
  8160. {
  8161. inputExhausted = true;
  8162. pipeOpened.signal();
  8163. }
  8164. else
  8165. {
  8166. closePipe();
  8167. pipeVerified.wait();
  8168. }
  8169. }
  8170. virtual void processEOG()
  8171. {
  8172. }
  8173. void processGroup(const ConstPointerArray &)
  8174. {
  8175. throwUnexpected();
  8176. }
  8177. virtual bool fireException(IException *e)
  8178. {
  8179. pipeOpened.interrupt(LINK(e));
  8180. pipeVerified.interrupt(e);
  8181. return true;
  8182. }
  8183. private:
  8184. bool waitForPipe()
  8185. {
  8186. if (firstRead)
  8187. {
  8188. pipeOpened.wait();
  8189. firstRead = false;
  8190. }
  8191. if (!pipe)
  8192. return false; // done
  8193. if (!readTransformer->eos())
  8194. return true;
  8195. verifyPipe();
  8196. if (recreate && !inputExhausted)
  8197. pipeOpened.wait();
  8198. return false;
  8199. }
  8200. void openPipe(char const * cmd)
  8201. {
  8202. pipeCommand.setown(cmd);
  8203. pipe.setown(createPipeProcess());
  8204. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8205. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8206. writeTransformer->writeHeader(pipe);
  8207. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8208. readTransformer->setStream(pipeReader.get());
  8209. pipeOpened.signal();
  8210. }
  8211. void closePipe()
  8212. {
  8213. writeTransformer->writeFooter(pipe);
  8214. pipe->closeInput();
  8215. }
  8216. void verifyPipe()
  8217. {
  8218. if (pipe)
  8219. {
  8220. unsigned err = pipe->wait();
  8221. if(err && !(helper.getPipeFlags() & TPFnofail))
  8222. {
  8223. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8224. }
  8225. pipe.clear();
  8226. pipeVerified.signal();
  8227. }
  8228. }
  8229. };
  8230. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8231. {
  8232. IHThorPipeWriteArg &helper;
  8233. Owned<IPipeProcess> pipe;
  8234. StringAttr pipeCommand;
  8235. CachedOutputMetaData inputMeta;
  8236. Owned<IOutputRowSerializer> rowSerializer;
  8237. Owned<IPipeWriteXformHelper> writeTransformer;
  8238. bool firstRead;
  8239. bool recreate;
  8240. bool inputExhausted;
  8241. public:
  8242. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8243. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8244. {
  8245. recreate = helper.recreateEachRow();
  8246. firstRead = false;
  8247. inputExhausted = false;
  8248. }
  8249. virtual bool needsAllocator() const { return true; }
  8250. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8251. {
  8252. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8253. inputMeta.set(input->queryOutputMeta());
  8254. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8255. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8256. }
  8257. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8258. {
  8259. firstRead = true;
  8260. inputExhausted = false;
  8261. writeTransformer->ready();
  8262. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8263. if(!recreate)
  8264. {
  8265. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8266. openPipe(pipeProgram);
  8267. }
  8268. }
  8269. virtual void stop(bool aborting)
  8270. {
  8271. if (!aborting && helper.getSequence() >= 0)
  8272. {
  8273. WorkunitUpdate wu = ctx->updateWorkUnit();
  8274. if (wu)
  8275. {
  8276. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8277. if (result)
  8278. {
  8279. result->setResultTotalRowCount(processed);
  8280. result->setResultStatus(ResultStatusCalculated);
  8281. }
  8282. }
  8283. }
  8284. CRoxieServerActivity::stop(aborting);
  8285. pipe.clear();
  8286. }
  8287. virtual void onExecute()
  8288. {
  8289. loop
  8290. {
  8291. const void *row = input->nextInGroup();
  8292. if (!row)
  8293. {
  8294. row = input->nextInGroup();
  8295. if (!row)
  8296. break;
  8297. }
  8298. processed++;
  8299. if(recreate)
  8300. openPipe(helper.getNameFromRow(row));
  8301. writeTransformer->writeTranslatedText(row, pipe);
  8302. ReleaseRoxieRow(row);
  8303. if(recreate)
  8304. closePipe();
  8305. }
  8306. closePipe();
  8307. }
  8308. private:
  8309. void openPipe(char const * cmd)
  8310. {
  8311. pipeCommand.setown(cmd);
  8312. pipe.setown(createPipeProcess());
  8313. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8314. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8315. writeTransformer->writeHeader(pipe);
  8316. }
  8317. void closePipe()
  8318. {
  8319. writeTransformer->writeFooter(pipe);
  8320. pipe->closeInput();
  8321. unsigned err = pipe->wait();
  8322. if(err && !(helper.getPipeFlags() & TPFnofail))
  8323. {
  8324. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8325. }
  8326. pipe.clear();
  8327. }
  8328. };
  8329. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8330. {
  8331. public:
  8332. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8333. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8334. {
  8335. }
  8336. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8337. {
  8338. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8339. }
  8340. };
  8341. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8342. {
  8343. public:
  8344. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8345. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8346. {
  8347. }
  8348. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8349. {
  8350. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8351. }
  8352. };
  8353. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8354. {
  8355. public:
  8356. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8357. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8358. {
  8359. }
  8360. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8361. {
  8362. return new CRoxieServerPipeWriteActivity(this, _probeManager, usageCount);
  8363. }
  8364. };
  8365. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8366. {
  8367. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8368. }
  8369. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8370. {
  8371. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8372. }
  8373. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8374. {
  8375. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8376. }
  8377. //=====================================================================================================
  8378. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8379. {
  8380. IHThorStreamedIteratorArg &helper;
  8381. Owned<IRowStream> rows;
  8382. public:
  8383. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8384. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8385. {
  8386. }
  8387. ~CRoxieServerStreamedIteratorActivity()
  8388. {
  8389. }
  8390. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8391. {
  8392. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8393. rows.setown(helper.createInput());
  8394. }
  8395. virtual void stop(bool aborting)
  8396. {
  8397. if (rows)
  8398. {
  8399. rows->stop();
  8400. rows.clear();
  8401. }
  8402. CRoxieServerActivity::stop(aborting);
  8403. }
  8404. virtual const void *nextInGroup()
  8405. {
  8406. ActivityTimer t(totalCycles, timeActivities);
  8407. assertex(rows != NULL);
  8408. const void * next = rows->nextRow();
  8409. if (next)
  8410. processed++;
  8411. return next;
  8412. }
  8413. };
  8414. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8415. {
  8416. public:
  8417. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8418. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8419. {
  8420. }
  8421. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8422. {
  8423. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8424. }
  8425. };
  8426. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8427. {
  8428. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8429. }
  8430. //=====================================================================================================
  8431. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8432. {
  8433. IHThorFilterArg &helper;
  8434. bool anyThisGroup;
  8435. IRangeCompare * stepCompare;
  8436. public:
  8437. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8438. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8439. {
  8440. anyThisGroup = false;
  8441. stepCompare = NULL;
  8442. }
  8443. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8444. {
  8445. anyThisGroup = false;
  8446. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8447. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8448. stepCompare = NULL;
  8449. if (!eof)
  8450. {
  8451. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8452. if (stepMeta)
  8453. stepCompare = stepMeta->queryCompare();
  8454. }
  8455. }
  8456. virtual const void * nextInGroup()
  8457. {
  8458. ActivityTimer t(totalCycles, timeActivities);
  8459. if (eof)
  8460. return NULL;
  8461. loop
  8462. {
  8463. const void * ret = input->nextInGroup();
  8464. if (!ret)
  8465. {
  8466. //stop returning two NULLs in a row.
  8467. if (anyThisGroup)
  8468. {
  8469. anyThisGroup = false;
  8470. return NULL;
  8471. }
  8472. ret = input->nextInGroup();
  8473. if (!ret)
  8474. {
  8475. eof = true;
  8476. return NULL; // eof...
  8477. }
  8478. }
  8479. if (helper.isValid(ret))
  8480. {
  8481. anyThisGroup = true;
  8482. processed++;
  8483. return ret;
  8484. }
  8485. ReleaseRoxieRow(ret);
  8486. }
  8487. }
  8488. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8489. {
  8490. //Could assert that this isn't grouped
  8491. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8492. ActivityTimer t(totalCycles, timeActivities);
  8493. if (eof)
  8494. return NULL;
  8495. loop
  8496. {
  8497. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8498. if (!ret)
  8499. {
  8500. eof = true;
  8501. return NULL;
  8502. }
  8503. if (!wasCompleteMatch)
  8504. {
  8505. anyThisGroup = false; // RKC->GH - is this right??
  8506. return ret;
  8507. }
  8508. if (helper.isValid(ret))
  8509. {
  8510. anyThisGroup = true;
  8511. processed++;
  8512. return ret;
  8513. }
  8514. if (!stepExtra.returnMismatches())
  8515. {
  8516. ReleaseRoxieRow(ret);
  8517. return nextInGroup();
  8518. }
  8519. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8520. //condition to advance
  8521. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8522. {
  8523. wasCompleteMatch = false;
  8524. anyThisGroup = false; // WHY?
  8525. return ret;
  8526. }
  8527. ReleaseRoxieRow(ret);
  8528. }
  8529. }
  8530. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8531. {
  8532. return input->gatherConjunctions(collector);
  8533. }
  8534. virtual void resetEOF()
  8535. {
  8536. eof = prefiltered;
  8537. anyThisGroup = false;
  8538. input->resetEOF();
  8539. }
  8540. IInputSteppingMeta * querySteppingMeta()
  8541. {
  8542. return input->querySteppingMeta();
  8543. }
  8544. };
  8545. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8546. {
  8547. public:
  8548. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8549. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8550. {
  8551. }
  8552. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8553. {
  8554. return new CRoxieServerFilterActivity(this, _probeManager);
  8555. }
  8556. };
  8557. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8558. {
  8559. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8560. }
  8561. //=====================================================================================================
  8562. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8563. {
  8564. IHThorFilterGroupArg &helper;
  8565. unsigned curIndex;
  8566. ConstPointerArray gathered;
  8567. IRangeCompare * stepCompare;
  8568. public:
  8569. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8570. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8571. {
  8572. curIndex = 0;
  8573. stepCompare = NULL;
  8574. }
  8575. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8576. {
  8577. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8578. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8579. assertex(eof == !helper.canMatchAny());
  8580. curIndex = 0;
  8581. stepCompare = NULL;
  8582. if (!eof)
  8583. {
  8584. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8585. if (inputStepping)
  8586. stepCompare = inputStepping->queryCompare();
  8587. }
  8588. }
  8589. virtual void reset()
  8590. {
  8591. releaseGathered();
  8592. CRoxieServerLateStartActivity::reset();
  8593. }
  8594. inline void releaseGathered()
  8595. {
  8596. while (gathered.isItem(curIndex))
  8597. ReleaseRoxieRow(gathered.item(curIndex++));
  8598. gathered.kill();
  8599. }
  8600. virtual const void * nextInGroup()
  8601. {
  8602. ActivityTimer t(totalCycles, timeActivities);
  8603. loop
  8604. {
  8605. if (eof)
  8606. return NULL;
  8607. if (gathered.ordinality())
  8608. {
  8609. if (gathered.isItem(curIndex))
  8610. {
  8611. const void * ret = gathered.item(curIndex++);
  8612. processed++;
  8613. return ret;
  8614. }
  8615. curIndex = 0;
  8616. gathered.kill();
  8617. return NULL;
  8618. }
  8619. const void * ret = input->nextInGroup();
  8620. while (ret)
  8621. {
  8622. gathered.append(ret);
  8623. ret = input->nextInGroup();
  8624. }
  8625. unsigned num = gathered.ordinality();
  8626. if (num != 0)
  8627. {
  8628. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8629. ReleaseRoxieRowSet(gathered); // read next group
  8630. }
  8631. else
  8632. eof = true;
  8633. }
  8634. }
  8635. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8636. {
  8637. ActivityTimer t(totalCycles, timeActivities);
  8638. if (eof)
  8639. return NULL;
  8640. if (gathered.ordinality())
  8641. {
  8642. while (gathered.isItem(curIndex))
  8643. {
  8644. const void * ret = gathered.item(curIndex++);
  8645. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8646. {
  8647. processed++;
  8648. return ret;
  8649. }
  8650. ReleaseRoxieRow(ret);
  8651. }
  8652. curIndex = 0;
  8653. gathered.kill();
  8654. //nextSteppedGE never returns an end of group marker.
  8655. }
  8656. //Not completely sure about this - it could lead the the start of a group being skipped,
  8657. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8658. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8659. //MORE: What do we do with wasCompleteMatch? something like the following????
  8660. #if 0
  8661. loop
  8662. {
  8663. const void * ret;
  8664. if (stepExtra.returnMismatches())
  8665. {
  8666. bool matchedCompletely = true;
  8667. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8668. if (!wasCompleteMatch)
  8669. return ret;
  8670. }
  8671. else
  8672. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8673. #endif
  8674. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8675. while (ret)
  8676. {
  8677. gathered.append(ret);
  8678. ret = input->nextInGroup();
  8679. }
  8680. unsigned num = gathered.ordinality();
  8681. if (num != 0)
  8682. {
  8683. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8684. ReleaseRoxieRowSet(gathered); // read next group
  8685. }
  8686. else
  8687. eof = true;
  8688. return nextUngrouped(this);
  8689. }
  8690. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8691. {
  8692. return input->gatherConjunctions(collector);
  8693. }
  8694. virtual void resetEOF()
  8695. {
  8696. eof = false;
  8697. releaseGathered();
  8698. input->resetEOF();
  8699. }
  8700. IInputSteppingMeta * querySteppingMeta()
  8701. {
  8702. return input->querySteppingMeta();
  8703. }
  8704. };
  8705. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8706. {
  8707. public:
  8708. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8709. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8710. {
  8711. }
  8712. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8713. {
  8714. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8715. }
  8716. };
  8717. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8718. {
  8719. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8720. }
  8721. //=================================================================================
  8722. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8723. {
  8724. IHThorSideEffectArg &helper;
  8725. CriticalSection ecrit;
  8726. Owned<IException> exception;
  8727. bool executed;
  8728. public:
  8729. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8730. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8731. {
  8732. executed = false;
  8733. }
  8734. virtual const void * nextInGroup()
  8735. {
  8736. ActivityTimer t(totalCycles, timeActivities);
  8737. CriticalBlock b(ecrit);
  8738. if (exception)
  8739. throw(exception.getLink());
  8740. if (!executed)
  8741. {
  8742. try
  8743. {
  8744. executed = true;
  8745. helper.action();
  8746. }
  8747. catch(IException *E)
  8748. {
  8749. exception.set(E);
  8750. throw;
  8751. }
  8752. }
  8753. return NULL;
  8754. }
  8755. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8756. {
  8757. CriticalBlock b(ecrit);
  8758. if (exception)
  8759. throw(exception.getLink());
  8760. if (!executed)
  8761. {
  8762. try
  8763. {
  8764. ActivityTimer t(totalCycles, timeActivities);
  8765. executed = true;
  8766. start(parentExtractSize, parentExtract, false);
  8767. helper.action();
  8768. stop(false);
  8769. }
  8770. catch(IException *E)
  8771. {
  8772. ctx->notifyAbort(E);
  8773. stop(true);
  8774. exception.set(E);
  8775. throw;
  8776. }
  8777. }
  8778. }
  8779. virtual void reset()
  8780. {
  8781. executed = false;
  8782. exception.clear();
  8783. CRoxieServerActivity::reset();
  8784. }
  8785. };
  8786. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8787. {
  8788. bool isRoot;
  8789. public:
  8790. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8791. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8792. {
  8793. }
  8794. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8795. {
  8796. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8797. }
  8798. virtual bool isSink() const
  8799. {
  8800. return isRoot && !meta.queryOriginal();
  8801. }
  8802. };
  8803. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8804. {
  8805. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8806. }
  8807. //=================================================================================
  8808. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8809. {
  8810. IHThorActionArg &helper;
  8811. public:
  8812. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8813. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  8814. {
  8815. }
  8816. virtual void onExecute()
  8817. {
  8818. helper.action();
  8819. }
  8820. };
  8821. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8822. {
  8823. public:
  8824. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8825. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8826. {
  8827. }
  8828. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8829. {
  8830. return new CRoxieServerActionActivity(this, _probeManager, usageCount);
  8831. }
  8832. };
  8833. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8834. {
  8835. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8836. }
  8837. //=================================================================================
  8838. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8839. {
  8840. IHThorSampleArg &helper;
  8841. unsigned numSamples;
  8842. unsigned numToSkip;
  8843. unsigned whichSample;
  8844. bool anyThisGroup;
  8845. bool eof;
  8846. public:
  8847. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8848. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8849. {
  8850. numSamples = 0;
  8851. numToSkip = 0;
  8852. whichSample = 0;
  8853. anyThisGroup = false;
  8854. eof = false;
  8855. }
  8856. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8857. {
  8858. anyThisGroup = false;
  8859. eof = false;
  8860. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8861. numSamples = helper.getProportion();
  8862. whichSample = helper.getSampleNumber();
  8863. numToSkip = (whichSample ? whichSample-1 : 0);
  8864. }
  8865. virtual const void * nextInGroup()
  8866. {
  8867. ActivityTimer t(totalCycles, timeActivities);
  8868. if (eof)
  8869. return NULL;
  8870. loop
  8871. {
  8872. const void * ret = input->nextInGroup();
  8873. if (!ret)
  8874. {
  8875. //this does work with groups - may or may not be useful...
  8876. //reset the sample for each group.... probably best.
  8877. numToSkip = (whichSample ? whichSample-1 : 0);
  8878. if (anyThisGroup)
  8879. {
  8880. anyThisGroup = false;
  8881. return NULL;
  8882. }
  8883. ret = input->nextInGroup();
  8884. if (!ret)
  8885. {
  8886. eof = true;
  8887. return NULL; // eof...
  8888. }
  8889. }
  8890. if (numToSkip == 0)
  8891. {
  8892. anyThisGroup = true;
  8893. numToSkip = numSamples-1;
  8894. processed++;
  8895. return ret;
  8896. }
  8897. numToSkip--;
  8898. ReleaseRoxieRow(ret);
  8899. }
  8900. }
  8901. };
  8902. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8903. {
  8904. public:
  8905. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8906. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8907. {
  8908. }
  8909. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8910. {
  8911. return new CRoxieServerSampleActivity(this, _probeManager);
  8912. }
  8913. };
  8914. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8915. {
  8916. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8917. }
  8918. //=================================================================================
  8919. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8920. {
  8921. IHThorChooseSetsArg &helper;
  8922. unsigned numSets;
  8923. unsigned * setCounts;
  8924. bool done;
  8925. public:
  8926. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8927. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8928. {
  8929. setCounts = NULL;
  8930. numSets = 0;
  8931. done = false;
  8932. }
  8933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8934. {
  8935. done = false;
  8936. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8937. numSets = helper.getNumSets();
  8938. setCounts = new unsigned[numSets];
  8939. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8940. helper.setCounts(setCounts);
  8941. }
  8942. virtual void reset()
  8943. {
  8944. delete [] setCounts;
  8945. setCounts = NULL;
  8946. CRoxieServerActivity::reset();
  8947. }
  8948. virtual const void * nextInGroup()
  8949. {
  8950. ActivityTimer t(totalCycles, timeActivities);
  8951. if (done)
  8952. return NULL;
  8953. loop
  8954. {
  8955. const void * ret = input->nextInGroup();
  8956. if (!ret)
  8957. {
  8958. ret = input->nextInGroup();
  8959. if (!ret)
  8960. {
  8961. done = true;
  8962. return NULL;
  8963. }
  8964. }
  8965. processed++;
  8966. switch (helper.getRecordAction(ret))
  8967. {
  8968. case 2:
  8969. done = true;
  8970. return ret;
  8971. case 1:
  8972. return ret;
  8973. }
  8974. ReleaseRoxieRow(ret);
  8975. }
  8976. }
  8977. };
  8978. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8979. {
  8980. public:
  8981. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8982. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8983. {
  8984. }
  8985. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8986. {
  8987. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8988. }
  8989. };
  8990. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8991. {
  8992. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8993. }
  8994. //=================================================================================
  8995. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  8996. {
  8997. protected:
  8998. IHThorChooseSetsExArg &helper;
  8999. unsigned numSets;
  9000. unsigned curIndex;
  9001. unsigned * setCounts;
  9002. count_t * limits;
  9003. bool done;
  9004. ConstPointerArray gathered;
  9005. virtual bool includeRow(const void * row) = 0;
  9006. virtual void calculateSelection() = 0;
  9007. public:
  9008. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9009. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9010. {
  9011. setCounts = NULL;
  9012. limits = NULL;
  9013. done = false;
  9014. curIndex = 0;
  9015. numSets = 0;
  9016. }
  9017. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9018. {
  9019. done = false;
  9020. curIndex = 0;
  9021. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9022. numSets = helper.getNumSets();
  9023. setCounts = new unsigned[numSets];
  9024. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9025. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9026. helper.getLimits(limits);
  9027. }
  9028. virtual void reset()
  9029. {
  9030. delete [] setCounts;
  9031. setCounts = NULL;
  9032. free(limits);
  9033. limits = NULL;
  9034. while (gathered.isItem(curIndex))
  9035. ReleaseRoxieRow(gathered.item(curIndex++));
  9036. gathered.kill();
  9037. CRoxieServerActivity::reset();
  9038. }
  9039. virtual const void * nextInGroup()
  9040. {
  9041. ActivityTimer t(totalCycles, timeActivities);
  9042. if (gathered.ordinality() == 0)
  9043. {
  9044. curIndex = 0;
  9045. if (!input->nextGroup(gathered))
  9046. {
  9047. done = true;
  9048. return NULL;
  9049. }
  9050. ForEachItemIn(idx1, gathered)
  9051. {
  9052. unsigned category = helper.getCategory(gathered.item(idx1));
  9053. if (category)
  9054. setCounts[category-1]++;
  9055. }
  9056. calculateSelection();
  9057. }
  9058. while (gathered.isItem(curIndex))
  9059. {
  9060. const void * row = gathered.item(curIndex);
  9061. gathered.replace(NULL, curIndex);
  9062. curIndex++;
  9063. if (includeRow(row))
  9064. {
  9065. processed++;
  9066. return row;
  9067. }
  9068. ReleaseRoxieRow(row);
  9069. }
  9070. gathered.kill();
  9071. return NULL;
  9072. }
  9073. };
  9074. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9075. {
  9076. unsigned * numToSkip;
  9077. public:
  9078. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9079. {
  9080. numToSkip = NULL;
  9081. }
  9082. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9083. {
  9084. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9085. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9086. }
  9087. virtual void reset()
  9088. {
  9089. free(numToSkip);
  9090. numToSkip = NULL;
  9091. CRoxieServerChooseSetsExActivity::reset();
  9092. }
  9093. protected:
  9094. virtual void calculateSelection()
  9095. {
  9096. for (unsigned idx=0; idx < numSets; idx++)
  9097. {
  9098. if (setCounts[idx] < limits[idx])
  9099. numToSkip[idx] = 0;
  9100. else
  9101. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9102. }
  9103. }
  9104. virtual bool includeRow(const void * row)
  9105. {
  9106. unsigned category = helper.getCategory(row);
  9107. if (category)
  9108. {
  9109. if (numToSkip[category-1] == 0)
  9110. return true;
  9111. numToSkip[category-1]--;
  9112. }
  9113. return false;
  9114. }
  9115. };
  9116. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9117. {
  9118. count_t * counter;
  9119. public:
  9120. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  9121. {
  9122. counter = NULL;
  9123. }
  9124. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9125. {
  9126. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9127. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9128. }
  9129. virtual void reset()
  9130. {
  9131. free(counter);
  9132. counter = NULL;
  9133. CRoxieServerChooseSetsExActivity::reset();
  9134. }
  9135. protected:
  9136. virtual void calculateSelection()
  9137. {
  9138. }
  9139. virtual bool includeRow(const void * row)
  9140. {
  9141. unsigned category = helper.getCategory(row);
  9142. if (category)
  9143. {
  9144. assertex(category <= numSets);
  9145. counter[category-1] += limits[category-1];
  9146. if(counter[category-1] >= setCounts[category-1])
  9147. {
  9148. counter[category-1] -= setCounts[category-1];
  9149. return true;
  9150. }
  9151. }
  9152. return false;
  9153. }
  9154. };
  9155. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9156. {
  9157. public:
  9158. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9159. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9160. {
  9161. }
  9162. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9163. {
  9164. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  9165. }
  9166. };
  9167. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9168. {
  9169. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9170. }
  9171. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9172. {
  9173. public:
  9174. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9175. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9176. {
  9177. }
  9178. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9179. {
  9180. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  9181. }
  9182. };
  9183. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9184. {
  9185. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9186. }
  9187. //=================================================================================
  9188. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9189. {
  9190. IHThorEnthArg &helper;
  9191. unsigned __int64 numerator;
  9192. unsigned __int64 denominator;
  9193. unsigned __int64 counter;
  9194. bool eof;
  9195. public:
  9196. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9197. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9198. {
  9199. eof = false;
  9200. numerator = denominator = counter = 0;
  9201. }
  9202. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9203. {
  9204. eof = false;
  9205. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9206. numerator = helper.getProportionNumerator();
  9207. denominator = helper.getProportionDenominator();
  9208. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9209. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9210. if (counter >= denominator)
  9211. counter %= denominator;
  9212. }
  9213. inline bool wanted()
  9214. {
  9215. counter += numerator;
  9216. if(counter >= denominator)
  9217. {
  9218. counter -= denominator;
  9219. return true;
  9220. }
  9221. return false;
  9222. }
  9223. virtual const void * nextInGroup()
  9224. {
  9225. ActivityTimer t(totalCycles, timeActivities);
  9226. if (eof)
  9227. return NULL;
  9228. const void * ret;
  9229. loop
  9230. {
  9231. ret = input->nextInGroup();
  9232. if(!ret) //end of group
  9233. ret = input->nextInGroup();
  9234. if(!ret) //eof
  9235. {
  9236. eof = true;
  9237. return ret;
  9238. }
  9239. if (wanted())
  9240. return ret;
  9241. ReleaseRoxieRow(ret);
  9242. }
  9243. }
  9244. };
  9245. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9246. {
  9247. public:
  9248. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9249. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9250. {
  9251. }
  9252. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9253. {
  9254. return new CRoxieServerEnthActivity(this, _probeManager);
  9255. }
  9256. };
  9257. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9258. {
  9259. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9260. }
  9261. //=================================================================================
  9262. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9263. {
  9264. IHThorAggregateArg &helper;
  9265. bool eof;
  9266. bool isInputGrouped;
  9267. bool abortEarly;
  9268. public:
  9269. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9270. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9271. {
  9272. eof = false;
  9273. isInputGrouped = false;
  9274. abortEarly = false;
  9275. }
  9276. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9277. {
  9278. eof = false;
  9279. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9280. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9281. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9282. }
  9283. virtual bool needsAllocator() const { return true; }
  9284. virtual const void * nextInGroup()
  9285. {
  9286. ActivityTimer t(totalCycles, timeActivities);
  9287. if (eof)
  9288. return NULL;
  9289. const void * next = input->nextInGroup();
  9290. if (!next && isInputGrouped)
  9291. {
  9292. eof = true;
  9293. return NULL;
  9294. }
  9295. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9296. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9297. if (next)
  9298. {
  9299. finalSize = helper.processFirst(rowBuilder, next);
  9300. ReleaseRoxieRow(next);
  9301. if (!abortEarly)
  9302. {
  9303. loop
  9304. {
  9305. next = input->nextInGroup();
  9306. if (!next)
  9307. break;
  9308. finalSize = helper.processNext(rowBuilder, next);
  9309. ReleaseRoxieRow(next);
  9310. }
  9311. }
  9312. }
  9313. if (!isInputGrouped) // either read all, or aborted early
  9314. eof = true;
  9315. processed++;
  9316. return rowBuilder.finalizeRowClear(finalSize);
  9317. }
  9318. };
  9319. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9320. {
  9321. public:
  9322. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9323. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9324. {
  9325. }
  9326. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9327. {
  9328. return new CRoxieServerAggregateActivity(this, _probeManager);
  9329. }
  9330. };
  9331. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9332. {
  9333. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9334. }
  9335. //=================================================================================
  9336. typedef unsigned t_hashPrefix;
  9337. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9338. {
  9339. IHThorHashAggregateArg &helper;
  9340. RowAggregator aggregated;
  9341. bool eof;
  9342. bool gathered;
  9343. bool isGroupedAggregate;
  9344. public:
  9345. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9346. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9347. isGroupedAggregate(_isGroupedAggregate),
  9348. aggregated(helper, helper)
  9349. {
  9350. eof = false;
  9351. gathered = false;
  9352. }
  9353. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9354. {
  9355. eof = false;
  9356. gathered = false;
  9357. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9358. }
  9359. virtual void reset()
  9360. {
  9361. aggregated.reset();
  9362. CRoxieServerActivity::reset();
  9363. }
  9364. virtual bool needsAllocator() const { return true; }
  9365. virtual const void * nextInGroup()
  9366. {
  9367. ActivityTimer t(totalCycles, timeActivities);
  9368. if (eof)
  9369. return NULL;
  9370. if (!gathered)
  9371. {
  9372. aggregated.start(rowAllocator);
  9373. bool eog = true;
  9374. loop
  9375. {
  9376. const void * next = input->nextInGroup();
  9377. if (!next)
  9378. {
  9379. if (isGroupedAggregate)
  9380. {
  9381. if (eog)
  9382. eof = true;
  9383. break;
  9384. }
  9385. next = input->nextInGroup();
  9386. if (!next)
  9387. break;
  9388. }
  9389. eog = false;
  9390. aggregated.addRow(next);
  9391. ReleaseRoxieRow(next);
  9392. }
  9393. gathered = true;
  9394. }
  9395. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9396. if (next)
  9397. {
  9398. processed++;
  9399. return next->finalizeRowClear();
  9400. }
  9401. if (!isGroupedAggregate)
  9402. eof = true;
  9403. aggregated.reset();
  9404. gathered = false;
  9405. return NULL;
  9406. }
  9407. };
  9408. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9409. {
  9410. public:
  9411. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9412. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9413. {
  9414. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9415. }
  9416. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9417. {
  9418. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9419. }
  9420. protected:
  9421. bool isGroupedAggregate;
  9422. };
  9423. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9424. {
  9425. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9426. }
  9427. //=================================================================================
  9428. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9429. {
  9430. IHThorDegroupArg &helper;
  9431. bool eof;
  9432. public:
  9433. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9434. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9435. {
  9436. eof = false;
  9437. }
  9438. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9439. {
  9440. eof = false;
  9441. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9442. }
  9443. virtual const void * nextInGroup()
  9444. {
  9445. ActivityTimer t(totalCycles, timeActivities);
  9446. if (eof)
  9447. return NULL;
  9448. const void * ret = input->nextInGroup();
  9449. if (!ret)
  9450. ret = input->nextInGroup();
  9451. if (ret)
  9452. processed++;
  9453. else
  9454. eof = true;
  9455. return ret;
  9456. }
  9457. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9458. {
  9459. ActivityTimer t(totalCycles, timeActivities);
  9460. if (eof)
  9461. return NULL;
  9462. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9463. if (ret)
  9464. processed++;
  9465. else
  9466. eof = true;
  9467. return ret;
  9468. }
  9469. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9470. {
  9471. return input->gatherConjunctions(collector);
  9472. }
  9473. virtual void resetEOF()
  9474. {
  9475. eof = false;
  9476. input->resetEOF();
  9477. }
  9478. IInputSteppingMeta * querySteppingMeta()
  9479. {
  9480. return input->querySteppingMeta();
  9481. }
  9482. };
  9483. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9484. {
  9485. public:
  9486. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9487. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9488. {
  9489. }
  9490. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9491. {
  9492. return new CRoxieServerDegroupActivity(this, _probeManager);
  9493. }
  9494. };
  9495. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9496. {
  9497. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9498. }
  9499. //=================================================================================
  9500. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9501. {
  9502. IHThorDiskReadArg &helper;
  9503. bool needTransform;
  9504. bool eof;
  9505. bool anyThisGroup;
  9506. unsigned __int64 rowLimit;
  9507. unsigned __int64 choosenLimit;
  9508. public:
  9509. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9510. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9511. {
  9512. needTransform = helper.needTransform();
  9513. rowLimit = (unsigned __int64) -1;
  9514. choosenLimit = 0;
  9515. eof = false;
  9516. anyThisGroup = false;
  9517. }
  9518. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9519. {
  9520. anyThisGroup = false;
  9521. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9522. if (helper.canMatchAny())
  9523. eof = false;
  9524. else
  9525. eof = true;
  9526. choosenLimit = helper.getChooseNLimit();
  9527. rowLimit = helper.getRowLimit();
  9528. helper.setCallback(NULL); // members should not be called - change if they are
  9529. }
  9530. virtual bool needsAllocator() const { return true; }
  9531. virtual const void * nextInGroup()
  9532. {
  9533. ActivityTimer t(totalCycles, timeActivities);
  9534. if (eof)
  9535. return NULL;
  9536. if (processed==choosenLimit)
  9537. {
  9538. eof = true;
  9539. return NULL;
  9540. }
  9541. if (needTransform)
  9542. {
  9543. loop
  9544. {
  9545. const void *in = input->nextInGroup();
  9546. if (!in)
  9547. {
  9548. if (anyThisGroup)
  9549. {
  9550. anyThisGroup = false;
  9551. return NULL;
  9552. }
  9553. in = input->nextInGroup();
  9554. if (!in)
  9555. {
  9556. eof = true;
  9557. return NULL; // eof...
  9558. }
  9559. }
  9560. unsigned outSize;
  9561. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9562. try
  9563. {
  9564. outSize = helper.transform(rowBuilder, in);
  9565. ReleaseRoxieRow(in);
  9566. }
  9567. catch (IException *E)
  9568. {
  9569. throw makeWrappedException(E);
  9570. }
  9571. if (outSize)
  9572. {
  9573. anyThisGroup = true;
  9574. processed++;
  9575. if (processed==rowLimit)
  9576. {
  9577. if (traceLevel > 4)
  9578. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9579. helper.onLimitExceeded();
  9580. }
  9581. return rowBuilder.finalizeRowClear(outSize);
  9582. }
  9583. }
  9584. }
  9585. else
  9586. {
  9587. const void *ret = input->nextInGroup();
  9588. if (ret)
  9589. {
  9590. processed++;
  9591. if (processed==rowLimit)
  9592. {
  9593. if (traceLevel > 4)
  9594. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9595. ReleaseClearRoxieRow(ret);
  9596. helper.onLimitExceeded(); // should not return
  9597. throwUnexpected();
  9598. }
  9599. }
  9600. return ret;
  9601. }
  9602. }
  9603. };
  9604. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9605. {
  9606. public:
  9607. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9608. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9609. {
  9610. }
  9611. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9612. {
  9613. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9614. }
  9615. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9616. {
  9617. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9618. setInput(0, source, sourceIdx);
  9619. else
  9620. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9621. }
  9622. };
  9623. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9624. {
  9625. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9626. }
  9627. //=================================================================================
  9628. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9629. {
  9630. public:
  9631. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9632. : CRoxieServerActivity(_factory, _probeManager)
  9633. {
  9634. }
  9635. ~CRoxieServerSpillWriteActivity()
  9636. {
  9637. }
  9638. virtual const void *nextInGroup()
  9639. {
  9640. ActivityTimer t(totalCycles, timeActivities);
  9641. return input->nextInGroup();
  9642. }
  9643. };
  9644. //==================================================================================
  9645. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9646. {
  9647. protected:
  9648. Owned<IExtRowWriter> outSeq;
  9649. Owned<IOutputRowSerializer> rowSerializer;
  9650. Linked<IFileIOStream> diskout;
  9651. bool blockcompressed;
  9652. bool extend;
  9653. bool overwrite;
  9654. bool encrypted;
  9655. bool grouped;
  9656. IHThorDiskWriteArg &helper;
  9657. CachedOutputMetaData diskmeta;
  9658. Owned<IRoxieWriteHandler> writer;
  9659. bool tallycrc;
  9660. unsigned __int64 uncompressedBytesWritten;
  9661. CRC32 crc;
  9662. void updateWorkUnitResult(unsigned __int64 reccount)
  9663. {
  9664. assertex(writer);
  9665. // MORE - a lot of this is common with hthor
  9666. WorkunitUpdate wu = ctx->updateWorkUnit();
  9667. if (wu)
  9668. {
  9669. OwnedRoxieString rawLogicalName = helper.getFileName();
  9670. StringBuffer lfn; // logical filename
  9671. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  9672. if (lfn.length())
  9673. {
  9674. unsigned flags = helper.getFlags();
  9675. WUFileKind fileKind;
  9676. if (TDXtemporary & flags)
  9677. fileKind = WUFileTemporary;
  9678. else if(TDXjobtemp & flags)
  9679. fileKind = WUFileJobOwned;
  9680. else if(TDWowned & flags)
  9681. fileKind = WUFileOwned;
  9682. else
  9683. fileKind = WUFileStandard;
  9684. StringArray clusters;
  9685. writer->getClusters(clusters);
  9686. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9687. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9688. {
  9689. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9690. if (result)
  9691. {
  9692. result->setResultTotalRowCount(reccount);
  9693. result->setResultStatus(ResultStatusCalculated);
  9694. if (helper.getFlags() & TDWresult)
  9695. result->setResultFilename(lfn.str());
  9696. else
  9697. result->setResultLogicalName(lfn.str());
  9698. }
  9699. }
  9700. }
  9701. }
  9702. }
  9703. void resolve()
  9704. {
  9705. OwnedRoxieString rawLogicalName = helper.getFileName();
  9706. assertex(rawLogicalName);
  9707. assertex((helper.getFlags() & TDXtemporary) == 0);
  9708. StringArray clusters;
  9709. unsigned clusterIdx = 0;
  9710. while(true)
  9711. {
  9712. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9713. if(!cluster)
  9714. break;
  9715. clusters.append(cluster);
  9716. clusterIdx++;
  9717. }
  9718. if (clusters.length())
  9719. {
  9720. if (extend)
  9721. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9722. }
  9723. else
  9724. {
  9725. if (roxieName.length())
  9726. clusters.append(roxieName.str());
  9727. else
  9728. clusters.append(".");
  9729. }
  9730. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  9731. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9732. }
  9733. public:
  9734. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9735. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
  9736. {
  9737. extend = ((helper.getFlags() & TDWextend) != 0);
  9738. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9739. grouped = false; // don't think we need to support it...
  9740. diskmeta.set(helper.queryDiskRecordSize());
  9741. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9742. encrypted = false; // set later
  9743. tallycrc = true;
  9744. uncompressedBytesWritten = 0;
  9745. }
  9746. ~CRoxieServerDiskWriteActivity()
  9747. {
  9748. }
  9749. virtual bool needsAllocator() const
  9750. {
  9751. return true;
  9752. }
  9753. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9754. {
  9755. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9756. resolve();
  9757. Owned<IFileIO> io;
  9758. void *ekey;
  9759. size32_t ekeylen;
  9760. helper.getEncryptKey(ekeylen, ekey);
  9761. Owned<ICompressor> ecomp;
  9762. if (ekeylen!=0)
  9763. {
  9764. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9765. memset(ekey,0,ekeylen);
  9766. rtlFree(ekey);
  9767. encrypted = true;
  9768. blockcompressed = true;
  9769. }
  9770. if (blockcompressed)
  9771. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9772. else
  9773. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9774. if (!io)
  9775. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9776. diskout.setown(createBufferedIOStream(io));
  9777. if (extend)
  9778. diskout->seek(0, IFSend);
  9779. tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9780. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9781. rowSerializer.set(rowIf->queryRowSerializer());
  9782. unsigned rwFlags = rw_autoflush;
  9783. if(grouped)
  9784. rwFlags |= rw_grouped;
  9785. if(tallycrc)
  9786. rwFlags |= rw_crc;
  9787. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9788. }
  9789. virtual void stop(bool aborting)
  9790. {
  9791. if (aborting)
  9792. {
  9793. if (writer)
  9794. writer->finish(false, this);
  9795. }
  9796. else
  9797. {
  9798. if (outSeq)
  9799. outSeq->flush(&crc);
  9800. if (outSeq)
  9801. uncompressedBytesWritten = outSeq->getPosition();
  9802. if (writer)
  9803. {
  9804. updateWorkUnitResult(processed);
  9805. writer->finish(true, this);
  9806. }
  9807. }
  9808. writer.clear();
  9809. CRoxieServerActivity::stop(aborting);
  9810. }
  9811. virtual void reset()
  9812. {
  9813. CRoxieServerActivity::reset();
  9814. diskout.clear();
  9815. outSeq.clear();
  9816. writer.clear();
  9817. uncompressedBytesWritten = 0;
  9818. crc.reset();
  9819. }
  9820. virtual void onExecute()
  9821. {
  9822. loop
  9823. {
  9824. const void *nextrec = input->nextInGroup();
  9825. if (!nextrec)
  9826. {
  9827. nextrec = input->nextInGroup();
  9828. if (!nextrec)
  9829. break;
  9830. }
  9831. processed++;
  9832. outSeq->putRow(nextrec);
  9833. }
  9834. }
  9835. virtual void setFileProperties(IFileDescriptor *desc) const
  9836. {
  9837. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9838. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9839. if (blockcompressed)
  9840. {
  9841. // caller has already set @size from file size...
  9842. fileProps.setPropBool("@blockCompressed", true);
  9843. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9844. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9845. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9846. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9847. }
  9848. else if (tallycrc)
  9849. partProps.setPropInt64("@fileCrc", crc.get());
  9850. if (encrypted)
  9851. fileProps.setPropBool("@encrypted", true);
  9852. fileProps.setPropInt64("@recordCount", processed);
  9853. unsigned flags = helper.getFlags();
  9854. if (flags & TDWpersist)
  9855. fileProps.setPropBool("@persistent", true);
  9856. if (grouped)
  9857. fileProps.setPropBool("@grouped", true);
  9858. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9859. fileProps.setPropBool("@owned", true);
  9860. if (flags & TDWresult)
  9861. fileProps.setPropBool("@result", true);
  9862. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9863. if (workUnit)
  9864. {
  9865. SCMStringBuffer owner, wuid, job;
  9866. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9867. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9868. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9869. }
  9870. if (flags & TDWexpires)
  9871. setExpiryTime(fileProps, helper.getExpiryDays());
  9872. if (flags & TDWupdate)
  9873. {
  9874. unsigned eclCRC;
  9875. unsigned __int64 totalCRC;
  9876. helper.getUpdateCRCs(eclCRC, totalCRC);
  9877. fileProps.setPropInt("@eclCRC", eclCRC);
  9878. fileProps.setPropInt64("@totalCRC", totalCRC);
  9879. }
  9880. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9881. IRecordSize * inputMeta = input->queryOutputMeta();
  9882. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9883. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9884. const char *recordECL = helper.queryRecordECL();
  9885. if (recordECL && *recordECL)
  9886. fileProps.setProp("ECL", recordECL);
  9887. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9888. }
  9889. virtual IUserDescriptor *queryUserDescriptor() const
  9890. {
  9891. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9892. if (workUnit)
  9893. return workUnit->queryUserDescriptor();
  9894. else
  9895. return NULL;
  9896. }
  9897. virtual bool isOutputTransformed() const { return false; }
  9898. };
  9899. //=================================================================================
  9900. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9901. {
  9902. IHThorCsvWriteArg &csvHelper;
  9903. CSVOutputStream csvOutput;
  9904. public:
  9905. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9906. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9907. {
  9908. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9909. }
  9910. virtual void onExecute()
  9911. {
  9912. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9913. if (header)
  9914. {
  9915. csvOutput.beginLine();
  9916. csvOutput.writeHeaderLn(strlen(header), header);
  9917. diskout->write(csvOutput.length(), csvOutput.str());
  9918. }
  9919. loop
  9920. {
  9921. const void *nextrec = input->nextInGroup();
  9922. if (!nextrec)
  9923. {
  9924. nextrec = input->nextInGroup();
  9925. if (!nextrec)
  9926. break;
  9927. }
  9928. processed++;
  9929. csvOutput.beginLine();
  9930. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9931. csvOutput.endLine();
  9932. diskout->write(csvOutput.length(), csvOutput.str());
  9933. ReleaseRoxieRow(nextrec);
  9934. }
  9935. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9936. if (footer)
  9937. {
  9938. csvOutput.beginLine();
  9939. csvOutput.writeHeaderLn(strlen(footer), footer);
  9940. diskout->write(csvOutput.length(), csvOutput.str());
  9941. }
  9942. }
  9943. virtual void setFileProperties(IFileDescriptor *desc) const
  9944. {
  9945. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9946. IPropertyTree &props = desc->queryProperties();
  9947. props.setProp("@format","utf8n");
  9948. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9949. StringBuffer separator;
  9950. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9951. const char *s = rs;
  9952. while (s && *s)
  9953. {
  9954. if (',' == *s)
  9955. separator.append("\\,");
  9956. else
  9957. separator.append(*s);
  9958. ++s;
  9959. }
  9960. props.setProp("@csvSeparate", separator.str());
  9961. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9962. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9963. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9964. props.setProp("@kind", "csv");
  9965. }
  9966. virtual bool isOutputTransformed() const { return true; }
  9967. };
  9968. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9969. {
  9970. IHThorXmlWriteArg &xmlHelper;
  9971. StringAttr rowTag;
  9972. ThorActivityKind kind;
  9973. unsigned headerLength;
  9974. unsigned footerLength;
  9975. public:
  9976. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  9977. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  9978. {
  9979. }
  9980. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9981. {
  9982. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9983. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9984. if (!xmlpath)
  9985. rowTag.set("Row");
  9986. else
  9987. {
  9988. const char *path = xmlpath;
  9989. if (*path == '/') path++;
  9990. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  9991. rowTag.set(path);
  9992. }
  9993. }
  9994. virtual void onExecute()
  9995. {
  9996. StringBuffer header;
  9997. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  9998. if (kind==TAKjsonwrite)
  9999. {
  10000. buildJsonHeader(header, suppliedHeader, rowTag);
  10001. headerLength = header.length();
  10002. }
  10003. else if (suppliedHeader)
  10004. header.set(suppliedHeader);
  10005. else
  10006. header.set("<Dataset>\n");
  10007. diskout->write(header.length(), header.str());
  10008. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
  10009. writer->outputBeginArray(rowTag); //need to set this
  10010. writer->clear(); //but not output it
  10011. loop
  10012. {
  10013. OwnedConstRoxieRow nextrec = input->nextInGroup();
  10014. if (!nextrec)
  10015. {
  10016. nextrec.setown(input->nextInGroup());
  10017. if (!nextrec)
  10018. break;
  10019. }
  10020. processed++;
  10021. writer->clear().outputBeginNested(rowTag, false);
  10022. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10023. writer->outputEndNested(rowTag);
  10024. diskout->write(writer->length(), writer->str());
  10025. }
  10026. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10027. StringBuffer footer;
  10028. if (kind==TAKjsonwrite)
  10029. {
  10030. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10031. footerLength=footer.length();
  10032. }
  10033. else if (suppliedFooter)
  10034. footer.append(suppliedFooter);
  10035. else
  10036. footer.append("</Dataset>");
  10037. diskout->write(footer.length(), footer);
  10038. }
  10039. virtual void reset()
  10040. {
  10041. CRoxieServerDiskWriteActivity::reset();
  10042. rowTag.clear();
  10043. }
  10044. virtual void setFileProperties(IFileDescriptor *desc) const
  10045. {
  10046. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10047. desc->queryProperties().setProp("@format","utf8n");
  10048. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10049. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10050. if (headerLength)
  10051. desc->queryProperties().setPropInt("@headerLength", headerLength);
  10052. if (footerLength)
  10053. desc->queryProperties().setPropInt("@footerLength", footerLength);
  10054. }
  10055. virtual bool isOutputTransformed() const { return true; }
  10056. };
  10057. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10058. {
  10059. bool isRoot;
  10060. bool isTemp;
  10061. public:
  10062. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10063. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  10064. {
  10065. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10066. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10067. setNumOutputs(helper->getTempUsageCount());
  10068. if (_kind!=TAKdiskwrite)
  10069. assertex(numOutputs == 0);
  10070. }
  10071. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10072. {
  10073. switch (numOutputs)
  10074. {
  10075. case 0:
  10076. switch (kind)
  10077. {
  10078. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  10079. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  10080. case TAKxmlwrite:
  10081. case TAKjsonwrite:
  10082. return new CRoxieServerXmlWriteActivity(this, _probeManager, kind);
  10083. };
  10084. throwUnexpected();
  10085. case 1:
  10086. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  10087. default:
  10088. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  10089. }
  10090. }
  10091. virtual bool isSink() const
  10092. {
  10093. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10094. }
  10095. };
  10096. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10097. {
  10098. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10099. }
  10100. //=================================================================================
  10101. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10102. {
  10103. IHThorIndexWriteArg &helper;
  10104. bool overwrite;
  10105. Owned<ClusterWriteHandler> clusterHandler;
  10106. Owned<IRoxieWriteHandler> writer;
  10107. unsigned __int64 reccount;
  10108. unsigned int fileCrc;
  10109. StringBuffer filename;
  10110. void updateWorkUnitResult()
  10111. {
  10112. // MORE - a lot of this is common with hthor
  10113. WorkunitUpdate wu = ctx->updateWorkUnit();
  10114. if (wu)
  10115. {
  10116. OwnedRoxieString rawLogicalName = helper.getFileName();
  10117. StringBuffer lfn; // logical filename
  10118. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10119. if (lfn.length())
  10120. {
  10121. if (helper.getSequence() >= 0)
  10122. {
  10123. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10124. if (result)
  10125. {
  10126. result->setResultTotalRowCount(reccount);
  10127. result->setResultStatus(ResultStatusCalculated);
  10128. result->setResultLogicalName(lfn.str());
  10129. }
  10130. }
  10131. if(clusterHandler)
  10132. clusterHandler->finish(writer->queryFile());
  10133. CTXLOG("Created roxie index file %s", lfn.str());
  10134. }
  10135. }
  10136. }
  10137. virtual void resolve()
  10138. {
  10139. StringArray clusters;
  10140. unsigned clusterIdx = 0;
  10141. while(true)
  10142. {
  10143. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10144. if(!cluster)
  10145. break;
  10146. clusters.append(cluster);
  10147. clusterIdx++;
  10148. }
  10149. if (roxieName.length())
  10150. clusters.append(roxieName.str());
  10151. else
  10152. clusters.append(".");
  10153. OwnedRoxieString fname(helper.getFileName());
  10154. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10155. filename.set(writer->queryFile()->queryFilename());
  10156. if (writer->queryFile()->exists())
  10157. {
  10158. if (overwrite)
  10159. {
  10160. CTXLOG("Removing existing %s from DFS",filename.str());
  10161. writer->queryFile()->remove();
  10162. }
  10163. else
  10164. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10165. }
  10166. }
  10167. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10168. {
  10169. size32_t nameLen;
  10170. char * nameBuff;
  10171. size32_t valueLen;
  10172. char * valueBuff;
  10173. unsigned idx = 0;
  10174. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10175. {
  10176. StringBuffer name(nameLen, nameBuff);
  10177. StringBuffer value(valueLen, valueBuff);
  10178. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10179. {
  10180. OwnedRoxieString fname(helper.getFileName());
  10181. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10182. }
  10183. if(!validateXMLTag(name.str()))
  10184. {
  10185. OwnedRoxieString fname(helper.getFileName());
  10186. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10187. }
  10188. if(!metadata)
  10189. metadata.setown(createPTree("metadata"));
  10190. metadata->setProp(name.str(), value.str());
  10191. }
  10192. }
  10193. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10194. {
  10195. if(!metadata)
  10196. metadata.setown(createPTree("metadata"));
  10197. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10198. void * layoutMetaBuff;
  10199. size32_t layoutMetaSize;
  10200. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10201. {
  10202. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10203. rtlFree(layoutMetaBuff);
  10204. }
  10205. }
  10206. public:
  10207. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10208. : CRoxieServerInternalSinkActivity(_factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10209. {
  10210. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10211. reccount = 0;
  10212. fileCrc = 0;
  10213. }
  10214. ~CRoxieServerIndexWriteActivity()
  10215. {
  10216. }
  10217. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10218. {
  10219. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10220. resolve();
  10221. }
  10222. virtual void onExecute()
  10223. {
  10224. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10225. size32_t maxDiskRecordSize;
  10226. if (isVariable)
  10227. {
  10228. if (helper.getFlags() & TIWmaxlength)
  10229. maxDiskRecordSize = helper.getMaxKeySize();
  10230. else
  10231. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10232. }
  10233. else
  10234. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  10235. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10236. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10237. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10238. fileCrc = -1;
  10239. {
  10240. Owned<IFileIO> io;
  10241. try
  10242. {
  10243. io.setown(writer->queryFile()->open(IFOcreate));
  10244. }
  10245. catch(IException * e)
  10246. {
  10247. e->Release();
  10248. clearKeyStoreCache(false);
  10249. io.setown(writer->queryFile()->open(IFOcreate));
  10250. }
  10251. if(!io)
  10252. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10253. Owned<IFileIOStream> out = createIOStream(io);
  10254. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10255. if (helper.getFlags() & TIWrowcompress)
  10256. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10257. else if (!(helper.getFlags() & TIWnolzwcompress))
  10258. flags |= HTREE_COMPRESSED_KEY;
  10259. if (isVariable)
  10260. flags |= HTREE_VARSIZE;
  10261. Owned<IPropertyTree> metadata;
  10262. buildUserMetadata(metadata);
  10263. buildLayoutMetadata(metadata);
  10264. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10265. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
  10266. class BcWrapper : implements IBlobCreator
  10267. {
  10268. IKeyBuilder *builder;
  10269. public:
  10270. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10271. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10272. {
  10273. return builder->createBlob(size, (const char *) ptr);
  10274. }
  10275. } bc(builder);
  10276. // Loop thru the results
  10277. loop
  10278. {
  10279. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10280. if (!nextrec)
  10281. {
  10282. nextrec.setown(input->nextInGroup());
  10283. if (!nextrec)
  10284. break;
  10285. }
  10286. try
  10287. {
  10288. unsigned __int64 fpos;
  10289. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10290. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10291. builder->processKeyData(rowBuffer, fpos, thisSize);
  10292. }
  10293. catch(IException * e)
  10294. {
  10295. throw makeWrappedException(e);
  10296. }
  10297. reccount++;
  10298. }
  10299. if(metadata)
  10300. builder->finish(metadata,&fileCrc);
  10301. else
  10302. builder->finish(&fileCrc);
  10303. }
  10304. }
  10305. virtual void stop(bool aborting)
  10306. {
  10307. if (writer)
  10308. {
  10309. if (!aborting)
  10310. updateWorkUnitResult();
  10311. writer->finish(!aborting, this);
  10312. writer.clear();
  10313. }
  10314. CRoxieServerActivity::stop(aborting);
  10315. }
  10316. virtual void reset()
  10317. {
  10318. CRoxieServerActivity::reset();
  10319. writer.clear();
  10320. }
  10321. //interface IRoxiePublishCallback
  10322. virtual void setFileProperties(IFileDescriptor *desc) const
  10323. {
  10324. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10325. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10326. // Now publish to name services
  10327. StringBuffer dir,base;
  10328. offset_t indexFileSize = writer->queryFile()->size();
  10329. if(clusterHandler)
  10330. clusterHandler->splitPhysicalFilename(dir, base);
  10331. else
  10332. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10333. desc->setDefaultDir(dir.str());
  10334. //properties of the first file part.
  10335. Owned<IPropertyTree> attrs;
  10336. if(clusterHandler)
  10337. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10338. else
  10339. {
  10340. // add cluster
  10341. StringBuffer mygroupname;
  10342. desc->setNumParts(1);
  10343. desc->setPartMask(base.str());
  10344. attrs.set(&desc->queryPart(0)->queryProperties());
  10345. }
  10346. attrs->setPropInt64("@size", indexFileSize);
  10347. CDateTime createTime, modifiedTime, accessedTime;
  10348. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10349. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10350. unsigned hour, min, sec, nanosec;
  10351. modifiedTime.getTime(hour, min, sec, nanosec);
  10352. modifiedTime.setTime(hour, min, sec, 0);
  10353. StringBuffer timestr;
  10354. modifiedTime.getString(timestr);
  10355. if(timestr.length())
  10356. attrs->setProp("@modified", timestr.str());
  10357. if(clusterHandler)
  10358. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10359. // properties of the logical file
  10360. IPropertyTree & properties = desc->queryProperties();
  10361. properties.setProp("@kind", "key");
  10362. properties.setPropInt64("@size", indexFileSize);
  10363. properties.setPropInt64("@recordCount", reccount);
  10364. SCMStringBuffer info;
  10365. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10366. if (workUnit)
  10367. {
  10368. properties.setProp("@owner", workUnit->getUser(info).str());
  10369. info.clear();
  10370. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10371. info.clear();
  10372. properties.setProp("@job", workUnit->getJobName(info).str());
  10373. }
  10374. char const * rececl = helper.queryRecordECL();
  10375. if(rececl && *rececl)
  10376. properties.setProp("ECL", rececl);
  10377. if (helper.getFlags() & TIWexpires)
  10378. setExpiryTime(properties, helper.getExpiryDays());
  10379. if (helper.getFlags() & TIWupdate)
  10380. {
  10381. unsigned eclCRC;
  10382. unsigned __int64 totalCRC;
  10383. helper.getUpdateCRCs(eclCRC, totalCRC);
  10384. properties.setPropInt("@eclCRC", eclCRC);
  10385. properties.setPropInt64("@totalCRC", totalCRC);
  10386. }
  10387. properties.setPropInt("@fileCrc", fileCrc);
  10388. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10389. void * layoutMetaBuff;
  10390. size32_t layoutMetaSize;
  10391. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10392. {
  10393. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10394. rtlFree(layoutMetaBuff);
  10395. }
  10396. }
  10397. IUserDescriptor *queryUserDescriptor() const
  10398. {
  10399. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10400. if (workUnit)
  10401. return workUnit->queryUserDescriptor();
  10402. else
  10403. return NULL;
  10404. }
  10405. };
  10406. //=================================================================================
  10407. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10408. {
  10409. public:
  10410. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10411. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10412. {
  10413. setNumOutputs(0);
  10414. }
  10415. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10416. {
  10417. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10418. }
  10419. virtual bool isSink() const
  10420. {
  10421. return true;
  10422. }
  10423. };
  10424. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10425. {
  10426. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10427. }
  10428. //=================================================================================
  10429. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10430. {
  10431. if((flags & JFmatchAbortLimitSkips) != 0)
  10432. {
  10433. limitFail = false;
  10434. limitOnFail = false;
  10435. }
  10436. else
  10437. {
  10438. limitOnFail = ((flags & JFonfail) != 0);
  10439. limitFail = !limitOnFail;
  10440. }
  10441. }
  10442. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10443. {
  10444. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10445. IHThorJoinArg &helper;
  10446. ICompare * collate;
  10447. ICompare * collateupper;
  10448. ThorActivityKind activityKind;
  10449. bool leftOuterJoin;
  10450. bool rightOuterJoin;
  10451. bool exclude;
  10452. bool limitFail;
  10453. bool limitOnFail;
  10454. unsigned keepLimit;
  10455. unsigned joinLimit;
  10456. unsigned atmostLimit;
  10457. unsigned abortLimit;
  10458. unsigned atmostsTriggered;
  10459. bool betweenjoin;
  10460. OwnedRowArray right;
  10461. const void * left;
  10462. const void * pendingRight;
  10463. unsigned rightIndex;
  10464. unsigned joinCounter;
  10465. BoolArray matchedRight;
  10466. bool matchedLeft;
  10467. Owned<IException> failingLimit;
  10468. ConstPointerArray filteredRight;
  10469. Owned<IRHLimitedCompareHelper> limitedhelper;
  10470. OwnedConstRoxieRow defaultLeft;
  10471. OwnedConstRoxieRow defaultRight;
  10472. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10473. Owned<IEngineRowAllocator> defaultRightAllocator;
  10474. bool cloneLeft;
  10475. void createDefaultLeft()
  10476. {
  10477. if (!defaultLeft)
  10478. {
  10479. if (!defaultLeftAllocator)
  10480. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10481. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10482. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10483. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10484. }
  10485. }
  10486. void createDefaultRight()
  10487. {
  10488. if (!defaultRight)
  10489. {
  10490. if (!defaultRightAllocator)
  10491. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10492. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10493. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10494. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10495. }
  10496. }
  10497. public:
  10498. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10499. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10500. {
  10501. // MORE - some of this should be done in factory
  10502. unsigned joinFlags = helper.getJoinFlags();
  10503. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10504. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10505. exclude = (joinFlags & JFexclude) != 0;
  10506. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10507. getLimitType(joinFlags, limitFail, limitOnFail);
  10508. if (joinFlags & JFslidingmatch)
  10509. {
  10510. betweenjoin = true;
  10511. collate = helper.queryCompareLeftRightLower();
  10512. collateupper = helper.queryCompareLeftRightUpper();
  10513. }
  10514. else
  10515. {
  10516. betweenjoin = false;
  10517. collate = collateupper = helper.queryCompareLeftRight();
  10518. }
  10519. rightIndex = 0;
  10520. joinCounter = 0;
  10521. state = JSfill;
  10522. matchedLeft = false;
  10523. joinLimit = 0;
  10524. keepLimit = 0; // wait until ctx available
  10525. atmostLimit = 0; // wait until ctx available
  10526. abortLimit = 0; // wait until ctx available
  10527. atmostsTriggered = 0;
  10528. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10529. left = NULL;
  10530. pendingRight = NULL;
  10531. activityKind = _factory->getKind();
  10532. }
  10533. virtual bool needsAllocator() const { return true; }
  10534. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10535. {
  10536. left = NULL;
  10537. rightIndex = 0;
  10538. joinCounter = 0;
  10539. state = JSfill;
  10540. matchedLeft = false;
  10541. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10542. keepLimit = helper.getKeepLimit();
  10543. if (keepLimit == 0)
  10544. keepLimit = (unsigned)-1;
  10545. atmostsTriggered = 0;
  10546. atmostLimit = helper.getJoinLimit();
  10547. if(atmostLimit == 0)
  10548. atmostLimit = (unsigned)-1;
  10549. else
  10550. assertex(!rightOuterJoin && !betweenjoin);
  10551. abortLimit = helper.getMatchAbortLimit();
  10552. if (abortLimit == 0)
  10553. abortLimit = (unsigned)-1;
  10554. if (rightOuterJoin)
  10555. createDefaultLeft();
  10556. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10557. createDefaultRight();
  10558. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10559. { //limited match join (s[1..n])
  10560. limitedhelper.setown(createRHLimitedCompareHelper());
  10561. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10562. }
  10563. }
  10564. virtual void reset()
  10565. {
  10566. if (atmostsTriggered)
  10567. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  10568. right.clear();
  10569. ReleaseClearRoxieRow(left);
  10570. ReleaseClearRoxieRow(pendingRight);
  10571. defaultRight.clear();
  10572. defaultLeft.clear();
  10573. CRoxieServerTwoInputActivity::reset();
  10574. }
  10575. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10576. {
  10577. switch(idx)
  10578. {
  10579. case 0:
  10580. if ((helper.getJoinFlags() & JFparallel) != 0)
  10581. {
  10582. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10583. puller->setInput(0, _in);
  10584. _in = puller;
  10585. }
  10586. input = _in;
  10587. break;
  10588. case 1:
  10589. input1 = _in;
  10590. break;
  10591. default:
  10592. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10593. }
  10594. }
  10595. virtual IRoxieInput *queryOutput(unsigned idx)
  10596. {
  10597. if (idx==(unsigned)-1)
  10598. idx = 0;
  10599. return idx ? NULL : this;
  10600. }
  10601. void fillLeft()
  10602. {
  10603. matchedLeft = false;
  10604. left = input->nextInGroup();
  10605. if (!left)
  10606. left = input->nextInGroup();
  10607. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10608. fillRight();
  10609. if (limitedhelper && 0==rightIndex)
  10610. {
  10611. rightIndex = 0;
  10612. joinCounter = 0;
  10613. right.clear();
  10614. matchedRight.kill();
  10615. if (left)
  10616. {
  10617. limitedhelper->getGroup(right,left);
  10618. ForEachItemIn(idx, right)
  10619. matchedRight.append(false);
  10620. }
  10621. }
  10622. }
  10623. void fillRight()
  10624. {
  10625. if (limitedhelper)
  10626. return;
  10627. failingLimit.clear();
  10628. if(betweenjoin && left)
  10629. {
  10630. aindex_t start = 0;
  10631. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10632. start++;
  10633. if(start>0)
  10634. right.clearPart(0, start);
  10635. }
  10636. else
  10637. right.clear();
  10638. rightIndex = 0;
  10639. joinCounter = 0;
  10640. unsigned groupCount = 0;
  10641. const void * next;
  10642. while(true)
  10643. {
  10644. if(pendingRight)
  10645. {
  10646. next = pendingRight;
  10647. pendingRight = NULL;
  10648. }
  10649. else
  10650. {
  10651. next = input1->nextInGroup();
  10652. }
  10653. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10654. {
  10655. while(next)
  10656. {
  10657. ReleaseClearRoxieRow(next);
  10658. next = input1->nextInGroup();
  10659. }
  10660. continue;
  10661. }
  10662. while(next)
  10663. {
  10664. if(groupCount==abortLimit)
  10665. {
  10666. if(limitFail)
  10667. failLimit();
  10668. if (ctx->queryDebugContext())
  10669. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10670. if(limitOnFail)
  10671. {
  10672. assertex(!failingLimit);
  10673. try
  10674. {
  10675. failLimit();
  10676. }
  10677. catch(IException * except)
  10678. {
  10679. failingLimit.setown(except);
  10680. }
  10681. assertex(failingLimit != NULL);
  10682. }
  10683. right.append(next);
  10684. do
  10685. {
  10686. next = input1->nextInGroup();
  10687. ReleaseRoxieRow(next);
  10688. } while(next);
  10689. break;
  10690. }
  10691. else if(groupCount==atmostLimit)
  10692. {
  10693. atmostsTriggered++;
  10694. right.clear();
  10695. groupCount = 0;
  10696. while(next)
  10697. {
  10698. ReleaseRoxieRow(next);
  10699. next = input1->nextInGroup();
  10700. }
  10701. }
  10702. else
  10703. {
  10704. right.append(next);
  10705. groupCount++;
  10706. }
  10707. next = input1->nextInGroup();
  10708. }
  10709. // 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
  10710. if(betweenjoin && left)
  10711. {
  10712. pendingRight = input1->nextInGroup();
  10713. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10714. break;
  10715. }
  10716. else
  10717. break;
  10718. }
  10719. matchedRight.kill();
  10720. ForEachItemIn(idx, right)
  10721. matchedRight.append(false);
  10722. }
  10723. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
  10724. {
  10725. if (cloneLeft)
  10726. {
  10727. LinkRoxieRow(curLeft);
  10728. return curLeft;
  10729. }
  10730. try
  10731. {
  10732. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10733. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
  10734. if (thisSize)
  10735. return rowBuilder.finalizeRowClear(thisSize);
  10736. else
  10737. return NULL;
  10738. }
  10739. catch (IException *E)
  10740. {
  10741. throw makeWrappedException(E);
  10742. }
  10743. }
  10744. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10745. {
  10746. try
  10747. {
  10748. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10749. unsigned numRows = rows.ordinality();
  10750. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10751. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10752. if (thisSize)
  10753. return rowBuilder.finalizeRowClear(thisSize);
  10754. else
  10755. return NULL;
  10756. }
  10757. catch (IException *E)
  10758. {
  10759. throw makeWrappedException(E);
  10760. }
  10761. }
  10762. const void * joinException(const void * curLeft, IException * except)
  10763. {
  10764. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10765. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10766. return rowBuilder.finalizeRowClear(thisSize);
  10767. }
  10768. void failLimit()
  10769. {
  10770. helper.onMatchAbortLimitExceeded();
  10771. CommonXmlWriter xmlwrite(0);
  10772. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10773. {
  10774. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10775. }
  10776. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10777. }
  10778. virtual const void * nextInGroup()
  10779. {
  10780. ActivityTimer t(totalCycles, timeActivities);
  10781. loop
  10782. {
  10783. switch (state)
  10784. {
  10785. case JSfill:
  10786. fillLeft();
  10787. state = JSfillright;
  10788. break;
  10789. case JSfillright:
  10790. fillRight();
  10791. state = JScollate;
  10792. break;
  10793. case JSfillleft:
  10794. fillLeft();
  10795. state = JScollate;
  10796. break;
  10797. case JScollate:
  10798. if (right.ordinality() == 0)
  10799. {
  10800. if (left == NULL)
  10801. return NULL;
  10802. state = JSleftonly;
  10803. }
  10804. else
  10805. {
  10806. if (!left)
  10807. state = JSrightonly;
  10808. else
  10809. {
  10810. int diff;
  10811. if(betweenjoin)
  10812. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10813. else
  10814. diff = collate->docompare(left, right.item(0));
  10815. bool limitExceeded = right.ordinality()>abortLimit;
  10816. if (diff == 0)
  10817. {
  10818. if (limitExceeded)
  10819. {
  10820. const void * ret = NULL;
  10821. if(failingLimit)
  10822. ret = joinException(left, failingLimit);
  10823. ReleaseRoxieRow(left);
  10824. left = NULL;
  10825. state = JSfillleft;
  10826. ForEachItemIn(idx, right)
  10827. matchedRight.replace(true, idx);
  10828. if(ret)
  10829. {
  10830. processed++;
  10831. return ret;
  10832. }
  10833. }
  10834. else
  10835. {
  10836. state = JScompare;
  10837. joinLimit = keepLimit;
  10838. }
  10839. }
  10840. else if (diff < 0)
  10841. state = JSleftonly;
  10842. else if (limitExceeded)
  10843. {
  10844. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10845. state = JSfillright;
  10846. }
  10847. else
  10848. state = JSrightonly;
  10849. }
  10850. }
  10851. break;
  10852. case JSrightonly:
  10853. if (rightOuterJoin)
  10854. {
  10855. switch (activityKind)
  10856. {
  10857. case TAKjoin:
  10858. {
  10859. while (right.isItem(rightIndex))
  10860. {
  10861. if (!matchedRight.item(rightIndex))
  10862. {
  10863. const void * rhs = right.item(rightIndex++);
  10864. const void *ret = joinRecords(defaultLeft, rhs, 0);
  10865. if (ret)
  10866. {
  10867. processed++;
  10868. return ret;
  10869. }
  10870. }
  10871. else
  10872. rightIndex++;
  10873. }
  10874. break;
  10875. }
  10876. //Probably excessive to implement the following, but possibly useful
  10877. case TAKdenormalize:
  10878. {
  10879. OwnedConstRoxieRow newLeft;
  10880. newLeft.set(defaultLeft);
  10881. unsigned rowSize = 0;
  10882. unsigned leftCount = 0;
  10883. while (right.isItem(rightIndex))
  10884. {
  10885. if (!matchedRight.item(rightIndex))
  10886. {
  10887. const void * rhs = right.item(rightIndex);
  10888. try
  10889. {
  10890. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10891. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10892. if (thisSize)
  10893. {
  10894. rowSize = thisSize;
  10895. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10896. }
  10897. }
  10898. catch (IException *E)
  10899. {
  10900. throw makeWrappedException(E);
  10901. }
  10902. }
  10903. rightIndex++;
  10904. }
  10905. state = JSfillright;
  10906. if (rowSize)
  10907. {
  10908. processed++;
  10909. return newLeft.getClear();
  10910. }
  10911. break;
  10912. }
  10913. case TAKdenormalizegroup:
  10914. {
  10915. filteredRight.kill();
  10916. while (right.isItem(rightIndex))
  10917. {
  10918. if (!matchedRight.item(rightIndex))
  10919. filteredRight.append(right.item(rightIndex));
  10920. rightIndex++;
  10921. }
  10922. state = JSfillright;
  10923. if (filteredRight.ordinality())
  10924. {
  10925. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10926. filteredRight.kill();
  10927. if (ret)
  10928. {
  10929. processed++;
  10930. return ret;
  10931. }
  10932. }
  10933. break;
  10934. }
  10935. }
  10936. }
  10937. state = JSfillright;
  10938. break;
  10939. case JSleftonly:
  10940. {
  10941. const void * ret = NULL;
  10942. if (!matchedLeft && leftOuterJoin)
  10943. {
  10944. switch (activityKind)
  10945. {
  10946. case TAKjoin:
  10947. ret = joinRecords(left, defaultRight, 0);
  10948. break;
  10949. case TAKdenormalize:
  10950. ret = left;
  10951. left = NULL;
  10952. break;
  10953. case TAKdenormalizegroup:
  10954. filteredRight.kill();
  10955. ret = denormalizeRecords(left, filteredRight);
  10956. break;
  10957. }
  10958. }
  10959. ReleaseRoxieRow(left);
  10960. left = NULL;
  10961. state = JSfillleft;
  10962. if (ret)
  10963. {
  10964. processed++;
  10965. return ret;
  10966. }
  10967. break;
  10968. }
  10969. case JScompare:
  10970. if (joinLimit != 0)
  10971. {
  10972. switch (activityKind)
  10973. {
  10974. case TAKjoin:
  10975. {
  10976. while (right.isItem(rightIndex))
  10977. {
  10978. const void * rhs = right.item(rightIndex++);
  10979. if (helper.match(left, rhs))
  10980. {
  10981. matchedRight.replace(true, rightIndex-1);
  10982. matchedLeft = true;
  10983. if (!exclude)
  10984. {
  10985. const void *ret = joinRecords(left, rhs, ++joinCounter);
  10986. if (ret)
  10987. {
  10988. processed++;
  10989. joinLimit--;
  10990. return ret;
  10991. }
  10992. }
  10993. }
  10994. }
  10995. break;
  10996. }
  10997. case TAKdenormalize:
  10998. {
  10999. OwnedConstRoxieRow newLeft;
  11000. newLeft.set(left);
  11001. unsigned rowSize = 0;
  11002. unsigned leftCount = 0;
  11003. while (right.isItem(rightIndex) && joinLimit)
  11004. {
  11005. try
  11006. {
  11007. const void * rhs = right.item(rightIndex++);
  11008. if (helper.match(left, rhs))
  11009. {
  11010. matchedRight.replace(true, rightIndex-1);
  11011. matchedLeft = true;
  11012. if (!exclude)
  11013. {
  11014. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11015. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  11016. if (thisSize)
  11017. {
  11018. rowSize = thisSize;
  11019. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11020. joinLimit--;
  11021. }
  11022. }
  11023. }
  11024. }
  11025. catch (IException *E)
  11026. {
  11027. throw makeWrappedException(E);
  11028. }
  11029. }
  11030. state = JSleftonly;
  11031. rightIndex = 0;
  11032. if (rowSize)
  11033. {
  11034. processed++;
  11035. return newLeft.getClear();
  11036. }
  11037. break;
  11038. }
  11039. case TAKdenormalizegroup:
  11040. {
  11041. filteredRight.kill();
  11042. while (right.isItem(rightIndex))
  11043. {
  11044. const void * rhs = right.item(rightIndex++);
  11045. if (helper.match(left, rhs))
  11046. {
  11047. matchedRight.replace(true, rightIndex-1);
  11048. filteredRight.append(rhs);
  11049. matchedLeft = true;
  11050. if (filteredRight.ordinality()==joinLimit)
  11051. break;
  11052. }
  11053. }
  11054. state = JSleftonly;
  11055. rightIndex = 0;
  11056. if (!exclude && filteredRight.ordinality())
  11057. {
  11058. const void * ret = denormalizeRecords(left, filteredRight);
  11059. filteredRight.kill();
  11060. if (ret)
  11061. {
  11062. processed++;
  11063. return ret;
  11064. }
  11065. }
  11066. break;
  11067. }
  11068. }
  11069. }
  11070. state = JSleftonly;
  11071. rightIndex = 0;
  11072. joinCounter = 0;
  11073. break;
  11074. }
  11075. }
  11076. }
  11077. };
  11078. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11079. {
  11080. unsigned input2;
  11081. unsigned input2idx;
  11082. public:
  11083. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11084. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11085. {
  11086. input2 = 0;
  11087. input2idx = 0;
  11088. }
  11089. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11090. {
  11091. return new CRoxieServerJoinActivity(this, _probeManager);
  11092. }
  11093. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11094. {
  11095. if (idx==1)
  11096. {
  11097. input2 = source;
  11098. input2idx = sourceidx;
  11099. }
  11100. else
  11101. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11102. }
  11103. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11104. {
  11105. switch (idx)
  11106. {
  11107. case 1:
  11108. sourceidx = input2idx;
  11109. return input2;
  11110. case 0:
  11111. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11112. default:
  11113. return (unsigned) -1;
  11114. }
  11115. }
  11116. virtual unsigned numInputs() const { return 2; }
  11117. virtual const StatisticsMapping &queryStatsMapping() const
  11118. {
  11119. return joinStatistics;
  11120. }
  11121. };
  11122. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11123. {
  11124. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11125. }
  11126. //=================================================================================
  11127. #define CONCAT_READAHEAD 1000
  11128. class CRoxieThreadedConcatReader : public CInterface, implements IRecordPullerCallback
  11129. {
  11130. public:
  11131. IMPLEMENT_IINTERFACE;
  11132. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11133. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11134. {
  11135. }
  11136. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11137. {
  11138. space.reinit(CONCAT_READAHEAD);
  11139. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11140. }
  11141. void stop(bool aborting)
  11142. {
  11143. space.interrupt();
  11144. puller.stop(aborting);
  11145. }
  11146. IRoxieInput *queryInput() const
  11147. {
  11148. return puller.queryInput();
  11149. }
  11150. void reset()
  11151. {
  11152. puller.reset();
  11153. ForEachItemIn(idx, buffer)
  11154. ReleaseRoxieRow(buffer.item(idx));
  11155. buffer.clear();
  11156. eof = false;
  11157. atEog = true;
  11158. }
  11159. void setInput(IRoxieInput *_in)
  11160. {
  11161. puller.setInput(this, _in);
  11162. }
  11163. virtual void processRow(const void *row)
  11164. {
  11165. buffer.enqueue(row);
  11166. ready.signal();
  11167. space.wait();
  11168. }
  11169. virtual void processGroup(const ConstPointerArray &rows)
  11170. {
  11171. // We use record-by-record input mode of the puller thread even in grouped mode.
  11172. throwUnexpected();
  11173. }
  11174. virtual void processEOG()
  11175. {
  11176. if (grouped)
  11177. processRow(NULL);
  11178. }
  11179. virtual void processDone()
  11180. {
  11181. processRow(NULL);
  11182. }
  11183. virtual bool fireException(IException *e)
  11184. {
  11185. // called from puller thread on failure
  11186. ready.interrupt(LINK(e));
  11187. space.interrupt(e);
  11188. return true;
  11189. }
  11190. bool peek(const void * &row, bool &anyActive)
  11191. {
  11192. if (!eof)
  11193. {
  11194. if (buffer.ordinality())
  11195. {
  11196. space.signal();
  11197. row = buffer.dequeue();
  11198. if (row==NULL)
  11199. {
  11200. if (atEog)
  11201. {
  11202. eof = true;
  11203. return false;
  11204. }
  11205. else
  11206. atEog = true;
  11207. }
  11208. else if (grouped)
  11209. atEog = false;
  11210. return true;
  11211. }
  11212. anyActive = true;
  11213. }
  11214. return false;
  11215. }
  11216. protected:
  11217. RecordPullerThread puller;
  11218. InterruptableSemaphore space;
  11219. InterruptableSemaphore &ready;
  11220. SafeQueueOf<const void, true> buffer;
  11221. bool atEog;
  11222. bool eof;
  11223. bool grouped;
  11224. };
  11225. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11226. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11227. {
  11228. InterruptableSemaphore ready;
  11229. ReaderArray pullers;
  11230. unsigned numInputs;
  11231. unsigned nextPuller; // for round robin
  11232. unsigned readyPending;
  11233. bool eof;
  11234. bool inGroup;
  11235. bool grouped;
  11236. public:
  11237. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11238. : CRoxieServerActivity(_factory, _probeManager), grouped(_grouped)
  11239. {
  11240. numInputs = _numInputs;
  11241. eof = (numInputs==0);
  11242. inGroup = false;
  11243. nextPuller = 0;
  11244. readyPending = 0;
  11245. for (unsigned i = 0; i < numInputs; i++)
  11246. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11247. }
  11248. ~CRoxieServerThreadedConcatActivity()
  11249. {
  11250. ForEachItemIn(idx, pullers)
  11251. delete &pullers.item(idx);
  11252. }
  11253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11254. {
  11255. eof = (numInputs==0);
  11256. inGroup = false;
  11257. nextPuller = 0;
  11258. readyPending = 0;
  11259. ready.reinit();
  11260. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11261. ForEachItemIn(idx, pullers)
  11262. {
  11263. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11264. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11265. // in the part of the subgraph that the thread uses has been started.
  11266. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11267. }
  11268. }
  11269. virtual void stop(bool aborting)
  11270. {
  11271. ready.interrupt();
  11272. ForEachItemIn(idx, pullers)
  11273. pullers.item(idx).stop(aborting);
  11274. CRoxieServerActivity::stop(aborting);
  11275. }
  11276. virtual unsigned __int64 queryLocalCycles() const
  11277. {
  11278. return 0;
  11279. }
  11280. virtual IRoxieInput *queryInput(unsigned idx) const
  11281. {
  11282. if (pullers.isItem(idx))
  11283. return pullers.item(idx).queryInput();
  11284. else
  11285. return NULL;
  11286. }
  11287. virtual void reset()
  11288. {
  11289. CRoxieServerActivity::reset();
  11290. ForEachItemIn(idx, pullers)
  11291. pullers.item(idx).reset();
  11292. eof = false;
  11293. inGroup = false;
  11294. nextPuller = 0;
  11295. readyPending = 0;
  11296. }
  11297. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11298. {
  11299. if (pullers.isItem(idx))
  11300. pullers.item(idx).setInput(_in);
  11301. else
  11302. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11303. }
  11304. virtual const void * nextInGroup()
  11305. {
  11306. ActivityTimer t(totalCycles, timeActivities);
  11307. if (eof)
  11308. return NULL;
  11309. loop
  11310. {
  11311. if (readyPending && !inGroup)
  11312. {
  11313. if (readyPending > 1)
  11314. ready.signal(readyPending-1);
  11315. readyPending = 0;
  11316. }
  11317. else
  11318. ready.wait();
  11319. bool anyActive = false;
  11320. ForEachItemIn(unused_index, pullers)
  11321. {
  11322. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  11323. const void *ret;
  11324. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  11325. if (fetched)
  11326. {
  11327. inGroup = (ret != NULL);
  11328. return ret;
  11329. }
  11330. if (inGroup && grouped)
  11331. {
  11332. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  11333. readyPending++;
  11334. anyActive = true;
  11335. break;
  11336. }
  11337. nextPuller++;
  11338. if (nextPuller==pullers.ordinality())
  11339. nextPuller = 0;
  11340. }
  11341. if (!anyActive)
  11342. break;
  11343. // A ready signal without anything being ready means someone reached end-of-file.
  11344. }
  11345. eof = true;
  11346. return NULL;
  11347. }
  11348. };
  11349. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11350. {
  11351. IRoxieInput *curInput;
  11352. bool eogSeen;
  11353. bool anyThisGroup;
  11354. bool grouped;
  11355. unsigned numInputs;
  11356. unsigned inputIdx;
  11357. IRoxieInput **inputArray;
  11358. public:
  11359. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11360. : CRoxieServerActivity(_factory, _probeManager)
  11361. {
  11362. eogSeen = false;
  11363. anyThisGroup = false;
  11364. grouped = _grouped;
  11365. numInputs = _numInputs;
  11366. inputIdx = 0;
  11367. inputArray = new IRoxieInput*[numInputs];
  11368. for (unsigned i = 0; i < numInputs; i++)
  11369. inputArray[i] = NULL;
  11370. curInput = NULL;
  11371. }
  11372. ~CRoxieServerOrderedConcatActivity()
  11373. {
  11374. delete [] inputArray;
  11375. }
  11376. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11377. {
  11378. inputIdx = 0;
  11379. curInput = inputArray[inputIdx];
  11380. eogSeen = false;
  11381. anyThisGroup = false;
  11382. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11383. for (unsigned i = 0; i < numInputs; i++)
  11384. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11385. }
  11386. virtual void stop(bool aborting)
  11387. {
  11388. for (unsigned i = 0; i < numInputs; i++)
  11389. inputArray[i]->stop(aborting);
  11390. CRoxieServerActivity::stop(aborting);
  11391. }
  11392. virtual unsigned __int64 queryLocalCycles() const
  11393. {
  11394. return 0;
  11395. }
  11396. virtual IRoxieInput *queryInput(unsigned idx) const
  11397. {
  11398. if (idx < numInputs)
  11399. return inputArray[idx];
  11400. else
  11401. return NULL;
  11402. }
  11403. virtual void reset()
  11404. {
  11405. CRoxieServerActivity::reset();
  11406. for (unsigned i = 0; i < numInputs; i++)
  11407. inputArray[i]->reset();
  11408. }
  11409. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11410. {
  11411. inputArray[idx] = _in;
  11412. }
  11413. virtual const void * nextInGroup()
  11414. {
  11415. ActivityTimer t(totalCycles, timeActivities);
  11416. if (!curInput)
  11417. return NULL; // eof
  11418. const void * next = curInput->nextInGroup();
  11419. if (next)
  11420. {
  11421. anyThisGroup = true;
  11422. eogSeen = false;
  11423. processed++;
  11424. return next;
  11425. }
  11426. else if (!eogSeen)
  11427. {
  11428. eogSeen = true;
  11429. if (grouped)
  11430. {
  11431. if (anyThisGroup)
  11432. {
  11433. anyThisGroup = false;
  11434. return NULL;
  11435. }
  11436. else
  11437. return nextInGroup();
  11438. }
  11439. else
  11440. return nextInGroup();
  11441. }
  11442. else if (inputIdx < numInputs-1)
  11443. {
  11444. inputIdx++;
  11445. curInput = inputArray[inputIdx];
  11446. eogSeen = false;
  11447. return nextInGroup();
  11448. }
  11449. else
  11450. {
  11451. curInput = NULL;
  11452. return NULL;
  11453. }
  11454. }
  11455. };
  11456. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11457. {
  11458. bool ordered;
  11459. bool grouped;
  11460. public:
  11461. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11462. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11463. {
  11464. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11465. ordered = helper->isOrdered();
  11466. grouped = helper->queryOutputMeta()->isGrouped();
  11467. }
  11468. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11469. {
  11470. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11471. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11472. else
  11473. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11474. }
  11475. };
  11476. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11477. {
  11478. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11479. }
  11480. //=================================================================================
  11481. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11482. {
  11483. IRoxieInput * selectedInput;
  11484. unsigned savedParentExtractSize;
  11485. const byte * savedParentExtract;
  11486. bool foundInput;
  11487. public:
  11488. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11489. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11490. {
  11491. foundInput = false;
  11492. selectedInput = NULL;
  11493. savedParentExtractSize = 0;;
  11494. savedParentExtract = NULL;
  11495. }
  11496. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11497. {
  11498. //Don't start the inputs yet so we can short-circuit...
  11499. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11500. savedParentExtractSize = parentExtractSize;
  11501. savedParentExtract = parentExtract;
  11502. }
  11503. virtual void stop(bool aborting)
  11504. {
  11505. if (foundInput)
  11506. {
  11507. if (selectedInput)
  11508. selectedInput->stop(aborting);
  11509. }
  11510. else
  11511. {
  11512. for (unsigned i = 0; i < numInputs; i++)
  11513. inputArray[i]->stop(aborting);
  11514. }
  11515. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11516. }
  11517. virtual void reset()
  11518. {
  11519. CRoxieServerMultiInputBaseActivity::reset();
  11520. foundInput = false;
  11521. selectedInput = NULL;
  11522. }
  11523. virtual unsigned __int64 queryLocalCycles() const
  11524. {
  11525. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11526. }
  11527. virtual const void * nextInGroup()
  11528. {
  11529. ActivityTimer t(totalCycles, timeActivities);
  11530. if (!foundInput)
  11531. {
  11532. foundInput = true;
  11533. //If we get an exception in this loop then stop() will stop any started inputs
  11534. for (unsigned i=0; i < numInputs; i++)
  11535. {
  11536. selectedInput = inputArray[i];
  11537. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11538. const void * next = selectedInput->nextInGroup();
  11539. if (next)
  11540. {
  11541. //Found a row so stop remaining
  11542. for (unsigned j=i+1; j < numInputs; j++)
  11543. inputArray[j]->stop(false);
  11544. processed++;
  11545. return next;
  11546. }
  11547. selectedInput->stop(false);
  11548. }
  11549. selectedInput = NULL;
  11550. return NULL;
  11551. }
  11552. if (!selectedInput)
  11553. return NULL;
  11554. const void * next = selectedInput->nextInGroup();
  11555. if (next)
  11556. processed++;
  11557. return next;
  11558. }
  11559. };
  11560. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11561. {
  11562. public:
  11563. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11564. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11565. {
  11566. }
  11567. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11568. {
  11569. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11570. }
  11571. };
  11572. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11573. {
  11574. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11575. }
  11576. //=================================================================================
  11577. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11578. {
  11579. IHThorMergeArg &helper;
  11580. unsigned *mergeheap;
  11581. unsigned activeInputs;
  11582. unsigned numInputs;
  11583. IRoxieInput **inputArray;
  11584. const void **pending;
  11585. bool first;
  11586. ICompare *compare;
  11587. bool dedup;
  11588. void permute()
  11589. {
  11590. assertex(activeInputs == 0);
  11591. for(unsigned i = 0; i < numInputs; i++)
  11592. if(pullInput(i))
  11593. mergeheap[activeInputs++] = i;
  11594. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11595. // the heap property: no element should be smaller than its parent
  11596. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11597. // 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
  11598. if (activeInputs >= 2)
  11599. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11600. siftDown(p);
  11601. if(dedup)
  11602. siftDownDedupTop();
  11603. else
  11604. siftDown(0);
  11605. }
  11606. void readNext()
  11607. {
  11608. if(!pullInput(mergeheap[0]))
  11609. if(!promote(0))
  11610. return;
  11611. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11612. if(dedup)
  11613. siftDownDedupTop();
  11614. else
  11615. siftDown(0);
  11616. }
  11617. bool pullInput(unsigned i)
  11618. {
  11619. const void *next = inputArray[i]->nextInGroup();
  11620. if (!next)
  11621. next = inputArray[i]->nextInGroup();
  11622. pending[i] = next;
  11623. return (next != NULL);
  11624. }
  11625. bool promote(unsigned p)
  11626. {
  11627. activeInputs--;
  11628. if(activeInputs == p)
  11629. return false;
  11630. mergeheap[p] = mergeheap[activeInputs];
  11631. return true;
  11632. }
  11633. bool siftDown(unsigned p)
  11634. {
  11635. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11636. bool nochange = true;
  11637. while(1)
  11638. {
  11639. unsigned c = p*2 + 1;
  11640. if(c >= activeInputs)
  11641. return nochange;
  11642. if(c+1 < activeInputs)
  11643. {
  11644. int childcmp = BuffCompare(c+1, c);
  11645. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11646. ++c;
  11647. }
  11648. int cmp = BuffCompare(c, p);
  11649. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11650. return nochange;
  11651. nochange = false;
  11652. unsigned r = mergeheap[c];
  11653. mergeheap[c] = mergeheap[p];
  11654. mergeheap[p] = r;
  11655. p = c;
  11656. }
  11657. }
  11658. void siftDownDedupTop()
  11659. {
  11660. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11661. if(activeInputs < 2)
  11662. return;
  11663. unsigned c = 1;
  11664. int childcmp = 1;
  11665. if(activeInputs >= 3)
  11666. {
  11667. childcmp = BuffCompare(2, 1);
  11668. if(childcmp < 0)
  11669. c = 2;
  11670. }
  11671. int cmp = BuffCompare(c, 0);
  11672. if(cmp > 0)
  11673. return;
  11674. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11675. while(cmp <= 0)
  11676. {
  11677. if(cmp == 0)
  11678. {
  11679. if(mergeheap[c] < mergeheap[0])
  11680. {
  11681. unsigned r = mergeheap[c];
  11682. mergeheap[c] = mergeheap[0];
  11683. mergeheap[0] = r;
  11684. }
  11685. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11686. if(!pullInput(mergeheap[c]))
  11687. if(!promote(c))
  11688. break;
  11689. siftDown(c);
  11690. }
  11691. else
  11692. {
  11693. unsigned r = mergeheap[c];
  11694. mergeheap[c] = mergeheap[0];
  11695. mergeheap[0] = r;
  11696. if(siftDown(c))
  11697. break;
  11698. }
  11699. cmp = BuffCompare(c, 0);
  11700. }
  11701. // the following loop ensures the uniqueness property holds on the other branch too
  11702. c = 3-c;
  11703. if(activeInputs <= c)
  11704. return;
  11705. while(childcmp == 0)
  11706. {
  11707. if(mergeheap[c] < mergeheap[0])
  11708. {
  11709. unsigned r = mergeheap[c];
  11710. mergeheap[c] = mergeheap[0];
  11711. mergeheap[0] = r;
  11712. }
  11713. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11714. if(!pullInput(mergeheap[c]))
  11715. if(!promote(c))
  11716. break;
  11717. siftDown(c);
  11718. childcmp = BuffCompare(c, 0);
  11719. }
  11720. }
  11721. inline int BuffCompare(unsigned a, unsigned b)
  11722. {
  11723. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11724. }
  11725. public:
  11726. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11727. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11728. {
  11729. activeInputs = 0;
  11730. first = true;
  11731. mergeheap = new unsigned[numInputs];
  11732. inputArray = new IRoxieInput*[numInputs];
  11733. pending = new const void *[numInputs];
  11734. compare = helper.queryCompare();
  11735. dedup = helper.dedup();
  11736. for (unsigned i = 0; i < numInputs; i++)
  11737. {
  11738. inputArray[i] = NULL;
  11739. pending[i] = NULL;
  11740. }
  11741. }
  11742. ~CRoxieServerMergeActivity()
  11743. {
  11744. delete [] mergeheap;
  11745. delete [] inputArray;
  11746. delete [] pending;
  11747. }
  11748. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11749. {
  11750. activeInputs = 0;
  11751. first = true;
  11752. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11753. for (unsigned i = 0; i < numInputs; i++)
  11754. {
  11755. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11756. }
  11757. }
  11758. virtual void stop(bool aborting)
  11759. {
  11760. for (unsigned i = 0; i < numInputs; i++)
  11761. {
  11762. inputArray[i]->stop(aborting);
  11763. }
  11764. CRoxieServerActivity::stop(aborting);
  11765. }
  11766. virtual void reset()
  11767. {
  11768. for (unsigned i = 0; i < numInputs; i++)
  11769. {
  11770. ReleaseClearRoxieRow(pending[i]);
  11771. inputArray[i]->reset();
  11772. }
  11773. CRoxieServerActivity::reset();
  11774. }
  11775. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11776. {
  11777. inputArray[idx] = _in;
  11778. }
  11779. virtual const void * nextInGroup()
  11780. {
  11781. ActivityTimer t(totalCycles, timeActivities);
  11782. if (first)
  11783. {
  11784. permute();
  11785. first = false;
  11786. }
  11787. if (activeInputs)
  11788. {
  11789. const void *next = pending[mergeheap[0]];
  11790. readNext();
  11791. if (next)
  11792. processed++;
  11793. return next;
  11794. }
  11795. else
  11796. return NULL;
  11797. }
  11798. };
  11799. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11800. {
  11801. public:
  11802. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11803. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11804. {
  11805. }
  11806. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11807. {
  11808. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11809. }
  11810. };
  11811. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11812. {
  11813. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11814. }
  11815. //=================================================================================
  11816. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11817. {
  11818. IHThorRegroupArg &helper;
  11819. unsigned inputIndex;
  11820. bool eof;
  11821. unsigned __int64 numProcessedLastGroup;
  11822. public:
  11823. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11824. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11825. {
  11826. inputIndex = 0;
  11827. eof = false;
  11828. numProcessedLastGroup = 0;
  11829. }
  11830. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11831. {
  11832. inputIndex = 0;
  11833. eof = false;
  11834. numProcessedLastGroup = processed;
  11835. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11836. }
  11837. const void * nextFromInputs()
  11838. {
  11839. unsigned initialInput = inputIndex;
  11840. while (inputIndex < numInputs)
  11841. {
  11842. const void * next = inputArray[inputIndex]->nextInGroup();
  11843. if (next)
  11844. {
  11845. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11846. {
  11847. ReleaseRoxieRow(next);
  11848. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11849. }
  11850. return next;
  11851. }
  11852. inputIndex++;
  11853. }
  11854. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11855. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11856. inputIndex = 0;
  11857. return NULL;
  11858. }
  11859. virtual const void * nextInGroup()
  11860. {
  11861. ActivityTimer t(totalCycles, timeActivities);
  11862. if (eof)
  11863. return NULL;
  11864. const void * ret = nextFromInputs();
  11865. if (ret)
  11866. {
  11867. processed++;
  11868. return ret;
  11869. }
  11870. if (numProcessedLastGroup != processed)
  11871. {
  11872. numProcessedLastGroup = processed;
  11873. return NULL;
  11874. }
  11875. eof = true;
  11876. return NULL;
  11877. }
  11878. #if 0
  11879. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11880. {
  11881. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11882. if (idx)
  11883. {
  11884. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11885. puller->setInput(0, _in);
  11886. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11887. }
  11888. else
  11889. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11890. }
  11891. #endif
  11892. };
  11893. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11894. {
  11895. public:
  11896. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11897. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11898. {
  11899. }
  11900. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11901. {
  11902. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11903. }
  11904. };
  11905. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11906. {
  11907. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11908. }
  11909. //=================================================================================
  11910. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11911. {
  11912. IHThorCombineArg &helper;
  11913. unsigned __int64 numProcessedLastGroup;
  11914. public:
  11915. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11916. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11917. {
  11918. numProcessedLastGroup = 0;
  11919. }
  11920. ~CRoxieServerCombineActivity()
  11921. {
  11922. }
  11923. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11924. {
  11925. numProcessedLastGroup = processed;
  11926. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11927. }
  11928. void nextInputs(ConstPointerArray & out)
  11929. {
  11930. for (unsigned i=0; i < numInputs; i++)
  11931. {
  11932. const void * next = inputArray[i]->nextInGroup();
  11933. if (next)
  11934. out.append(next);
  11935. }
  11936. }
  11937. virtual bool needsAllocator() const { return true; }
  11938. virtual const void * nextInGroup()
  11939. {
  11940. ActivityTimer t(totalCycles, timeActivities);
  11941. loop
  11942. {
  11943. ConstPointerArray group;
  11944. nextInputs(group);
  11945. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11946. nextInputs(group);
  11947. if (group.ordinality() == 0)
  11948. {
  11949. numProcessedLastGroup = processed;
  11950. return NULL;
  11951. }
  11952. else if (group.ordinality() != numInputs)
  11953. {
  11954. ReleaseRoxieRowSet(group);
  11955. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11956. }
  11957. try
  11958. {
  11959. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11960. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11961. ReleaseRoxieRowSet(group);
  11962. if (outSize)
  11963. {
  11964. processed++;
  11965. return rowBuilder.finalizeRowClear(outSize);
  11966. }
  11967. }
  11968. catch (IException *E)
  11969. {
  11970. ReleaseRoxieRowSet(group);
  11971. throw makeWrappedException(E);
  11972. }
  11973. }
  11974. }
  11975. };
  11976. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11977. {
  11978. public:
  11979. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11980. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11981. {
  11982. }
  11983. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11984. {
  11985. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11986. }
  11987. };
  11988. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11989. {
  11990. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11991. }
  11992. //=================================================================================
  11993. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  11994. {
  11995. IHThorCombineGroupArg &helper;
  11996. unsigned __int64 numProcessedLastGroup;
  11997. public:
  11998. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11999. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12000. {
  12001. numProcessedLastGroup = 0;
  12002. }
  12003. ~CRoxieServerCombineGroupActivity()
  12004. {
  12005. }
  12006. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12007. {
  12008. numProcessedLastGroup = processed;
  12009. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12010. }
  12011. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12012. {
  12013. switch(idx)
  12014. {
  12015. case 0:
  12016. #if 0
  12017. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  12018. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  12019. puller->setInput(0, _in);
  12020. _in = puller;
  12021. #endif
  12022. input = _in;
  12023. break;
  12024. case 1:
  12025. input1 = _in;
  12026. break;
  12027. default:
  12028. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12029. }
  12030. }
  12031. virtual IRoxieInput *queryOutput(unsigned idx)
  12032. {
  12033. if (idx==(unsigned)-1)
  12034. idx = 0;
  12035. return idx ? NULL : this;
  12036. }
  12037. virtual bool needsAllocator() const { return true; }
  12038. virtual const void * nextInGroup()
  12039. {
  12040. ActivityTimer t(totalCycles, timeActivities);
  12041. loop
  12042. {
  12043. const void * left = input->nextInGroup();
  12044. if (!left && (numProcessedLastGroup == processed))
  12045. left = input->nextInGroup();
  12046. if (!left)
  12047. {
  12048. if (numProcessedLastGroup == processed)
  12049. {
  12050. const void * nextRight = input1->nextInGroup();
  12051. if (nextRight)
  12052. {
  12053. ReleaseRoxieRow(nextRight);
  12054. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12055. }
  12056. }
  12057. else
  12058. numProcessedLastGroup = processed;
  12059. return NULL;
  12060. }
  12061. ConstPointerArray group;
  12062. loop
  12063. {
  12064. const void * in = input1->nextInGroup();
  12065. if (!in)
  12066. break;
  12067. group.append(in);
  12068. }
  12069. if (group.ordinality() == 0)
  12070. {
  12071. ReleaseRoxieRow(left);
  12072. ReleaseRoxieRowSet(group);
  12073. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12074. }
  12075. try
  12076. {
  12077. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12078. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12079. ReleaseRoxieRow(left);
  12080. ReleaseRoxieRowSet(group);
  12081. if (outSize)
  12082. {
  12083. processed++;
  12084. return rowBuilder.finalizeRowClear(outSize);
  12085. }
  12086. }
  12087. catch (IException *E)
  12088. {
  12089. ReleaseRoxieRow(left);
  12090. ReleaseRoxieRowSet(group);
  12091. throw makeWrappedException(E);
  12092. }
  12093. }
  12094. }
  12095. };
  12096. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12097. {
  12098. unsigned input2;
  12099. unsigned input2idx;
  12100. public:
  12101. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12102. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12103. {
  12104. input2 = 0;
  12105. input2idx = 0;
  12106. }
  12107. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12108. {
  12109. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  12110. }
  12111. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12112. {
  12113. if (idx==1)
  12114. {
  12115. input2 = source;
  12116. input2idx = sourceidx;
  12117. }
  12118. else
  12119. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12120. }
  12121. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12122. {
  12123. switch (idx)
  12124. {
  12125. case 1:
  12126. sourceidx = input2idx;
  12127. return input2;
  12128. case 0:
  12129. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12130. default:
  12131. return (unsigned) -1;
  12132. }
  12133. }
  12134. virtual unsigned numInputs() const { return 2; }
  12135. };
  12136. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12137. {
  12138. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12139. }
  12140. //=================================================================================
  12141. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12142. {
  12143. IHThorRollupGroupArg &helper;
  12144. bool eof;
  12145. public:
  12146. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12147. : CRoxieServerActivity(_factory, _probeManager),
  12148. helper((IHThorRollupGroupArg &)basehelper)
  12149. {
  12150. eof = false;
  12151. }
  12152. ~CRoxieServerRollupGroupActivity()
  12153. {
  12154. }
  12155. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12156. {
  12157. eof = false;
  12158. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12159. }
  12160. virtual bool needsAllocator() const { return true; }
  12161. virtual const void * nextInGroup()
  12162. {
  12163. ActivityTimer t(totalCycles, timeActivities);
  12164. if (eof)
  12165. return NULL;
  12166. loop
  12167. {
  12168. ConstPointerArray group;
  12169. loop
  12170. {
  12171. const void * in = input->nextInGroup();
  12172. if (!in)
  12173. break;
  12174. group.append(in);
  12175. }
  12176. if (group.ordinality() == 0)
  12177. {
  12178. eof = true;
  12179. return NULL;
  12180. }
  12181. try
  12182. {
  12183. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12184. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12185. ReleaseRoxieRowSet(group);
  12186. if (outSize)
  12187. {
  12188. processed++;
  12189. return rowBuilder.finalizeRowClear(outSize);
  12190. }
  12191. }
  12192. catch (IException * E)
  12193. {
  12194. ReleaseRoxieRowSet(group);
  12195. throw makeWrappedException(E);
  12196. }
  12197. }
  12198. }
  12199. };
  12200. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12201. {
  12202. public:
  12203. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12204. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12205. {
  12206. }
  12207. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12208. {
  12209. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  12210. }
  12211. };
  12212. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12213. {
  12214. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12215. }
  12216. //=================================================================================
  12217. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12218. {
  12219. IHThorFilterProjectArg &helper;
  12220. unsigned numProcessedLastGroup;
  12221. unsigned __int64 recordCount;
  12222. public:
  12223. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12224. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12225. {
  12226. numProcessedLastGroup = 0;
  12227. recordCount = 0;
  12228. }
  12229. ~CRoxieServerFilterProjectActivity()
  12230. {
  12231. }
  12232. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12233. {
  12234. numProcessedLastGroup = 0;
  12235. recordCount = 0;
  12236. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12237. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12238. }
  12239. virtual bool needsAllocator() const { return true; }
  12240. virtual const void * nextInGroup()
  12241. {
  12242. ActivityTimer t(totalCycles, timeActivities);
  12243. if (eof)
  12244. return NULL;
  12245. loop
  12246. {
  12247. const void * in = input->nextInGroup();
  12248. if (!in)
  12249. {
  12250. recordCount = 0;
  12251. if (numProcessedLastGroup == processed)
  12252. in = input->nextInGroup();
  12253. if (!in)
  12254. {
  12255. numProcessedLastGroup = processed;
  12256. return NULL;
  12257. }
  12258. }
  12259. try
  12260. {
  12261. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12262. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12263. ReleaseRoxieRow(in);
  12264. if (outSize)
  12265. {
  12266. processed++;
  12267. return rowBuilder.finalizeRowClear(outSize);
  12268. }
  12269. }
  12270. catch (IException *E)
  12271. {
  12272. throw makeWrappedException(E);
  12273. }
  12274. }
  12275. }
  12276. };
  12277. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  12278. {
  12279. public:
  12280. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12281. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12282. {
  12283. }
  12284. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12285. {
  12286. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  12287. }
  12288. };
  12289. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12290. {
  12291. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12292. }
  12293. //=================================================================================
  12294. class CRoxieServerProjectActivity : public CRoxieServerActivity
  12295. {
  12296. unsigned numProcessedLastGroup;
  12297. bool count;
  12298. unsigned __int64 recordCount;
  12299. public:
  12300. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12301. : CRoxieServerActivity(_factory, _probeManager),
  12302. count(_count)
  12303. {
  12304. numProcessedLastGroup = 0;
  12305. recordCount = 0;
  12306. }
  12307. ~CRoxieServerProjectActivity()
  12308. {
  12309. }
  12310. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12311. {
  12312. numProcessedLastGroup = 0;
  12313. recordCount = 0;
  12314. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12315. }
  12316. virtual bool needsAllocator() const { return true; }
  12317. virtual const void * nextInGroup()
  12318. {
  12319. ActivityTimer t(totalCycles, timeActivities);
  12320. loop
  12321. {
  12322. OwnedConstRoxieRow in = input->nextInGroup();
  12323. if (!in)
  12324. {
  12325. recordCount = 0;
  12326. if (numProcessedLastGroup == processed)
  12327. in.setown(input->nextInGroup());
  12328. if (!in)
  12329. {
  12330. numProcessedLastGroup = processed;
  12331. return NULL;
  12332. }
  12333. }
  12334. try
  12335. {
  12336. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12337. size32_t outSize;
  12338. if (count)
  12339. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12340. else
  12341. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12342. if (outSize)
  12343. {
  12344. processed++;
  12345. return rowBuilder.finalizeRowClear(outSize);
  12346. }
  12347. }
  12348. catch (IException *E)
  12349. {
  12350. throw makeWrappedException(E);
  12351. }
  12352. }
  12353. }
  12354. };
  12355. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12356. {
  12357. protected:
  12358. bool count;
  12359. public:
  12360. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12361. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12362. {
  12363. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12364. }
  12365. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12366. {
  12367. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12368. }
  12369. };
  12370. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12371. {
  12372. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12373. }
  12374. //=================================================================================
  12375. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12376. {
  12377. unsigned numProcessedLastGroup;
  12378. bool count;
  12379. bool eof;
  12380. bool allPulled;
  12381. bool isThreaded;
  12382. unsigned preload;
  12383. unsigned __int64 recordCount;
  12384. IHThorPrefetchProjectArg &helper;
  12385. RecordPullerThread puller;
  12386. InterruptableSemaphore ready;
  12387. InterruptableSemaphore space;
  12388. class PrefetchInfo : public CInterface
  12389. {
  12390. public:
  12391. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12392. {
  12393. if (helper.preTransform(extract, _in, _recordCount))
  12394. {
  12395. in.setown(_in);
  12396. recordCount = _recordCount;
  12397. }
  12398. else
  12399. ReleaseRoxieRow(_in);
  12400. }
  12401. OwnedConstRoxieRow in;
  12402. unsigned __int64 recordCount;
  12403. rtlRowBuilder extract;
  12404. };
  12405. QueueOf<PrefetchInfo, true> pulled;
  12406. CriticalSection pulledCrit;
  12407. public:
  12408. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12409. : CRoxieServerActivity(_factory, _probeManager),
  12410. helper((IHThorPrefetchProjectArg &) basehelper),
  12411. puller(false),
  12412. count(_count)
  12413. {
  12414. numProcessedLastGroup = 0;
  12415. recordCount = 0;
  12416. eof = false;
  12417. allPulled = false;
  12418. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12419. preload = 0;
  12420. }
  12421. ~CRoxieServerPrefetchProjectActivity()
  12422. {
  12423. while (pulled.ordinality())
  12424. ::Release(pulled.dequeue());
  12425. }
  12426. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12427. {
  12428. if (idx)
  12429. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12430. puller.setInput(this, _in);
  12431. }
  12432. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12433. {
  12434. numProcessedLastGroup = 0;
  12435. recordCount = 0;
  12436. eof = false;
  12437. allPulled = false;
  12438. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12439. preload = helper.getLookahead();
  12440. if (!preload)
  12441. preload = ctx->queryOptions().prefetchProjectPreload;
  12442. space.reinit(preload);
  12443. ready.reinit();
  12444. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12445. }
  12446. virtual void stop(bool aborting)
  12447. {
  12448. space.interrupt();
  12449. ready.interrupt();
  12450. CRoxieServerActivity::stop(aborting);
  12451. puller.stop(aborting);
  12452. }
  12453. virtual void reset()
  12454. {
  12455. CRoxieServerActivity::reset();
  12456. puller.reset();
  12457. allPulled = false;
  12458. while (pulled.ordinality())
  12459. ::Release(pulled.dequeue());
  12460. }
  12461. virtual PrefetchInfo *readNextRecord()
  12462. {
  12463. if (!isThreaded)
  12464. {
  12465. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12466. puller.pullRecords(1);
  12467. }
  12468. else
  12469. ready.wait();
  12470. CriticalBlock b(pulledCrit);
  12471. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12472. space.signal();
  12473. return ret;
  12474. }
  12475. virtual bool needsAllocator() const { return true; }
  12476. virtual const void * nextInGroup()
  12477. {
  12478. ActivityTimer t(totalCycles, timeActivities);
  12479. if (eof)
  12480. return NULL;
  12481. loop
  12482. {
  12483. Owned<PrefetchInfo> in = readNextRecord();
  12484. if (!in)
  12485. {
  12486. recordCount = 0;
  12487. if (numProcessedLastGroup == processed)
  12488. in.setown(readNextRecord());
  12489. if (!in)
  12490. {
  12491. numProcessedLastGroup = processed;
  12492. eof = true;
  12493. return NULL;
  12494. }
  12495. }
  12496. try
  12497. {
  12498. if (in->in)
  12499. {
  12500. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12501. size32_t outSize;
  12502. IThorChildGraph *child = helper.queryChild();
  12503. Owned<IEclGraphResults> results;
  12504. if (child)
  12505. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12506. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12507. if (outSize)
  12508. {
  12509. processed++;
  12510. return rowBuilder.finalizeRowClear(outSize);
  12511. }
  12512. }
  12513. }
  12514. catch (IException *E)
  12515. {
  12516. throw makeWrappedException(E);
  12517. }
  12518. }
  12519. }
  12520. // interface IExceptionHandler
  12521. virtual bool fireException(IException *e)
  12522. {
  12523. // called from puller thread on failure
  12524. ready.interrupt(LINK(e));
  12525. space.interrupt(e);
  12526. return true;
  12527. }
  12528. // interface IRecordPullerCallback
  12529. virtual void processRow(const void *row)
  12530. {
  12531. {
  12532. CriticalBlock b(pulledCrit);
  12533. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12534. }
  12535. if (isThreaded)
  12536. {
  12537. ready.signal();
  12538. space.wait();
  12539. }
  12540. }
  12541. virtual void processEOG()
  12542. {
  12543. {
  12544. CriticalBlock b(pulledCrit);
  12545. pulled.enqueue(NULL);
  12546. }
  12547. if (isThreaded)
  12548. {
  12549. ready.signal();
  12550. space.wait();
  12551. }
  12552. }
  12553. virtual void processGroup(const ConstPointerArray &rows)
  12554. {
  12555. throwUnexpected();
  12556. }
  12557. virtual void processDone()
  12558. {
  12559. CriticalBlock b(pulledCrit);
  12560. allPulled = true;
  12561. if (isThreaded)
  12562. ready.signal();
  12563. }
  12564. };
  12565. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12566. {
  12567. public:
  12568. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12569. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12570. {
  12571. }
  12572. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12573. {
  12574. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12575. }
  12576. };
  12577. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12578. {
  12579. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12580. }
  12581. //=================================================================================
  12582. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12583. {
  12584. public:
  12585. CPointerArrayRoxieInput()
  12586. {
  12587. rowset = NULL;
  12588. rowcount = 0;
  12589. curRow = 0;
  12590. }
  12591. void init(size32_t _rowcount, byte **_rowset)
  12592. {
  12593. rowset = _rowset;
  12594. rowcount = _rowcount;
  12595. curRow = 0;
  12596. }
  12597. virtual const void * nextInGroup()
  12598. {
  12599. if (curRow < rowcount)
  12600. {
  12601. const void * ret = rowset[curRow];
  12602. if (ret)
  12603. LinkRoxieRow(ret);
  12604. curRow++;
  12605. return ret;
  12606. }
  12607. return NULL;
  12608. }
  12609. protected:
  12610. byte **rowset;
  12611. size32_t rowcount;
  12612. size32_t curRow;
  12613. };
  12614. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12615. {
  12616. protected:
  12617. IHThorLoopArg &helper;
  12618. ThorActivityKind activityKind;
  12619. unsigned maxIterations;
  12620. bool finishedLooping;
  12621. unsigned flags;
  12622. bool eof;
  12623. rtlRowBuilder loopExtractBuilder;
  12624. unsigned loopGraphId;
  12625. Linked<IOutputMetaData> counterMeta;
  12626. public:
  12627. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12628. : CRoxieServerActivity(_factory, _probeManager),
  12629. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12630. {
  12631. eof = false;
  12632. finishedLooping = false;
  12633. activityKind = factory->getKind();
  12634. flags = helper.getFlags();
  12635. maxIterations = 0;
  12636. }
  12637. virtual bool needsAllocator() const { return true; }
  12638. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12639. {
  12640. eof = false;
  12641. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12642. int iterations = (int) helper.numIterations();
  12643. maxIterations = (iterations >= 0) ? iterations : 0;
  12644. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12645. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12646. finishedLooping = true;
  12647. loopExtractBuilder.clear();
  12648. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12649. }
  12650. virtual void stop(bool aborting)
  12651. {
  12652. CRoxieServerActivity::stop(aborting);
  12653. loopExtractBuilder.clear();
  12654. }
  12655. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12656. {
  12657. if (flags & IHThorLoopArg::LFcounter)
  12658. {
  12659. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12660. *((thor_loop_counter_t *)counterRow) = counter;
  12661. RtlLinkedDatasetBuilder builder(rowAllocator);
  12662. builder.appendOwn(counterRow);
  12663. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12664. graph->setInputResult(2, counterResult);
  12665. }
  12666. }
  12667. };
  12668. //=================================================================================
  12669. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12670. {
  12671. Owned<IActivityGraph> loopQuery;
  12672. Owned<IRoxieServerChildGraph> loopGraph;
  12673. IRoxieInput * curInput;
  12674. RtlLinkedDatasetBuilder *loopInputBuilder;
  12675. CPointerArrayRoxieInput arrayInput;
  12676. Linked<IRoxieInput> resultInput;
  12677. unsigned loopCounter;
  12678. public:
  12679. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12680. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12681. {
  12682. curInput = NULL;
  12683. loopCounter = 0;
  12684. loopInputBuilder = NULL;
  12685. }
  12686. virtual bool needsAllocator() const { return true; }
  12687. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12688. {
  12689. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12690. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12691. }
  12692. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12693. {
  12694. curInput = input;
  12695. loopCounter = 1;
  12696. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12697. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12698. loopGraph.set(loopQuery->queryLoopGraph());
  12699. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12700. }
  12701. virtual void stop(bool aborting)
  12702. {
  12703. delete loopInputBuilder;
  12704. loopInputBuilder = NULL;
  12705. CRoxieServerLoopActivity::stop(aborting);
  12706. }
  12707. virtual const void * nextInGroup()
  12708. {
  12709. ActivityTimer t(totalCycles, timeActivities);
  12710. if (eof)
  12711. return NULL;
  12712. unsigned emptyIterations = 0;
  12713. loop
  12714. {
  12715. loop
  12716. {
  12717. const void * ret = curInput->nextInGroup();
  12718. if (!ret)
  12719. {
  12720. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12721. if (!ret)
  12722. {
  12723. if (finishedLooping)
  12724. {
  12725. eof = true;
  12726. return NULL;
  12727. }
  12728. break;
  12729. }
  12730. }
  12731. if (finishedLooping ||
  12732. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12733. {
  12734. processed++;
  12735. return ret;
  12736. }
  12737. loopInputBuilder->appendOwn(ret);
  12738. }
  12739. switch (activityKind)
  12740. {
  12741. case TAKloopdataset:
  12742. {
  12743. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12744. {
  12745. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12746. {
  12747. if (loopInputBuilder->getcount() == 0)
  12748. {
  12749. eof = true;
  12750. return NULL;
  12751. }
  12752. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12753. // MORE - should builder be cleared here?
  12754. curInput = &arrayInput;
  12755. finishedLooping = true;
  12756. continue; // back to the input loop again
  12757. }
  12758. }
  12759. break;
  12760. }
  12761. case TAKlooprow:
  12762. if (!loopInputBuilder->getcount())
  12763. {
  12764. finishedLooping = true;
  12765. eof = true;
  12766. return NULL;
  12767. }
  12768. break;
  12769. }
  12770. if (loopInputBuilder->getcount())
  12771. emptyIterations = 0;
  12772. else
  12773. {
  12774. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12775. emptyIterations++;
  12776. if (emptyIterations > maxEmptyLoopIterations)
  12777. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12778. if (emptyIterations % 32 == 0)
  12779. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12780. }
  12781. checkAbort();
  12782. try
  12783. {
  12784. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12785. resultInput.setown(results->createIterator(0));
  12786. if (flags & IHThorLoopArg::LFnewloopagain)
  12787. {
  12788. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12789. OwnedConstRoxieRow row = againResult->nextInGroup();
  12790. assertex(row);
  12791. //Result is a row which contains a single boolean field.
  12792. if (!((const bool *)row.get())[0])
  12793. finishedLooping = true;
  12794. }
  12795. }
  12796. catch (IException *E)
  12797. {
  12798. throw makeWrappedException(E);
  12799. }
  12800. curInput = resultInput.get();
  12801. loopCounter++;
  12802. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12803. finishedLooping = true;
  12804. }
  12805. }
  12806. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12807. {
  12808. try
  12809. {
  12810. loopGraph->beforeExecute();
  12811. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12812. loopInputBuilder->clear();
  12813. loopGraph->setInputResult(1, inputRowsResult);
  12814. createCounterResult(loopGraph, counter);
  12815. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12816. loopGraph->afterExecute();
  12817. return ret.getClear();
  12818. }
  12819. catch (...)
  12820. {
  12821. CTXLOG("Exception thrown in loop body - cleaning up");
  12822. loopGraph->afterExecute();
  12823. throw;
  12824. }
  12825. }
  12826. };
  12827. //=================================================================================
  12828. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12829. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12830. {
  12831. public:
  12832. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12833. input(_input)
  12834. {
  12835. eof = false;
  12836. }
  12837. virtual const void * nextInGroup()
  12838. {
  12839. if (eof)
  12840. return NULL;
  12841. const void * ret = input.dequeue();
  12842. if (!ret)
  12843. eof = true;
  12844. return ret;
  12845. }
  12846. protected:
  12847. SafeRowQueue & input;
  12848. bool eof;
  12849. };
  12850. class CRoxieServerParallelLoopActivity;
  12851. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12852. {
  12853. public:
  12854. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12855. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12856. {
  12857. }
  12858. virtual const void * nextInGroup();
  12859. protected:
  12860. CRoxieServerParallelLoopActivity * activity;
  12861. unsigned counter;
  12862. };
  12863. class LoopExecutorThread : public RestartableThread
  12864. {
  12865. protected:
  12866. Owned<IRoxieInput> safeInput;
  12867. CRoxieServerParallelLoopActivity * activity;
  12868. bool eof;
  12869. CriticalSection crit;
  12870. unsigned flags;
  12871. SafeRowQueue tempResults[2];
  12872. unsigned savedParentExtractSize;
  12873. const byte * savedParentExtract;
  12874. IArrayOf<IActivityGraph> cachedGraphs;
  12875. IRoxieSlaveContext *ctx;
  12876. public:
  12877. LoopExecutorThread()
  12878. : RestartableThread("LoopExecutorThread")
  12879. {
  12880. activity = NULL;
  12881. eof = false;
  12882. flags = 0;
  12883. ctx = NULL;
  12884. savedParentExtract = NULL;
  12885. savedParentExtractSize = 0;
  12886. }
  12887. virtual IRoxieInput *queryInput(unsigned idx) const
  12888. {
  12889. return safeInput->queryInput(idx);
  12890. }
  12891. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12892. {
  12893. activity = _activity;
  12894. flags = _flags;
  12895. // 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.
  12896. safeInput.setown(new CSafeRoxieInput(_input));
  12897. }
  12898. IRoxieInput *queryInput() const
  12899. {
  12900. return safeInput;
  12901. }
  12902. void onCreate(IRoxieSlaveContext * _ctx);
  12903. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12904. void stop(bool aborting);
  12905. void reset();
  12906. virtual int run();
  12907. protected:
  12908. void executeLoop();
  12909. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12910. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12911. };
  12912. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12913. {
  12914. friend class LoopFilterPseudoInput;
  12915. friend class LoopExecutorThread;
  12916. QueueOf<const void, true> ready;
  12917. CriticalSection helperCS;
  12918. CriticalSection cs;
  12919. size32_t sizeNumParallel;
  12920. rtlDataAttr listNumParallel;
  12921. unsigned defaultNumParallel;
  12922. LoopExecutorThread executor;
  12923. IProbeManager* probeManager;
  12924. CriticalSection canAccess;
  12925. CriticalSection scrit;
  12926. InterruptableSemaphore readySpace;
  12927. InterruptableSemaphore recordsReady;
  12928. protected:
  12929. bool includeInLoop(unsigned counter, const void * row)
  12930. {
  12931. CriticalBlock b(helperCS);
  12932. return helper.sendToLoop(counter, row);
  12933. }
  12934. public:
  12935. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12936. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12937. readySpace(parallelLoopFlowLimit)
  12938. {
  12939. probeManager = _probeManager;
  12940. defaultNumParallel = 0;
  12941. sizeNumParallel = 0;
  12942. }
  12943. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12944. {
  12945. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12946. executor.onCreate(_ctx);
  12947. }
  12948. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12949. {
  12950. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12951. readySpace.reinit(parallelLoopFlowLimit);
  12952. recordsReady.reinit();
  12953. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12954. defaultNumParallel = helper.defaultParallelIterations();
  12955. if (!defaultNumParallel)
  12956. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12957. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12958. //MORE: If numIterations <= number of parallel iterations[1],
  12959. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12960. //being transferred via a queue
  12961. executor.start(parentExtractSize, parentExtract, paused);
  12962. }
  12963. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12964. {
  12965. if (idx)
  12966. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12967. executor.setInput(this, _in, flags);
  12968. }
  12969. virtual void stop(bool aborting)
  12970. {
  12971. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12972. readySpace.interrupt();
  12973. recordsReady.interrupt();
  12974. executor.join(); // MORE - may not be needed given stop/reset split
  12975. CRoxieServerLoopActivity::stop(aborting);
  12976. }
  12977. virtual void reset()
  12978. {
  12979. while (ready.ordinality())
  12980. ReleaseRoxieRow(ready.dequeue());
  12981. executor.reset();
  12982. CRoxieServerActivity::reset();
  12983. }
  12984. virtual const void * nextInGroup()
  12985. {
  12986. ActivityTimer t(totalCycles, timeActivities);
  12987. loop
  12988. {
  12989. if (eof)
  12990. return NULL;
  12991. recordsReady.wait();
  12992. CriticalBlock procedure(canAccess);
  12993. if (ready.ordinality())
  12994. {
  12995. const void *result = ready.dequeue();
  12996. readySpace.signal();
  12997. if (result)
  12998. processed++;
  12999. return result;
  13000. }
  13001. else
  13002. eof = true;
  13003. }
  13004. }
  13005. unsigned getNumParallel(unsigned iter)
  13006. {
  13007. if (iter * sizeof(unsigned) >= sizeNumParallel)
  13008. return defaultNumParallel;
  13009. return ((unsigned *)listNumParallel.getdata())[iter];
  13010. }
  13011. inline void enqueueResult(const void * row)
  13012. {
  13013. try
  13014. {
  13015. while(!readySpace.wait(1000))
  13016. {
  13017. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13018. }
  13019. }
  13020. catch (...)
  13021. {
  13022. ReleaseRoxieRow(row);
  13023. throw;
  13024. }
  13025. CriticalBlock b2(canAccess);
  13026. ready.enqueue(row);
  13027. recordsReady.signal();
  13028. }
  13029. inline void finishResults()
  13030. {
  13031. recordsReady.signal();
  13032. }
  13033. virtual bool fireException(IException *e)
  13034. {
  13035. readySpace.interrupt(LINK(e));
  13036. recordsReady.interrupt(e);
  13037. return true;
  13038. }
  13039. IActivityGraph * createChildGraphInstance()
  13040. {
  13041. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13042. }
  13043. IActivityGraph * queryChildGraph()
  13044. {
  13045. return ctx->queryChildGraph(loopGraphId);
  13046. }
  13047. };
  13048. //=================================================================================
  13049. const void * LoopFilterPseudoInput::nextInGroup()
  13050. {
  13051. loop
  13052. {
  13053. const void * next = input->nextInGroup();
  13054. if (!next || activity->includeInLoop(counter, next))
  13055. return next;
  13056. activity->enqueueResult(next);
  13057. }
  13058. }
  13059. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13060. {
  13061. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13062. ctx = _ctx;
  13063. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13064. }
  13065. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13066. {
  13067. savedParentExtractSize = parentExtractSize;
  13068. savedParentExtract = parentExtract;
  13069. eof = false;
  13070. StringBuffer logPrefix("[");
  13071. ctx->getLogPrefix(logPrefix).append("] ");
  13072. RestartableThread::start(logPrefix);
  13073. }
  13074. int LoopExecutorThread::run()
  13075. {
  13076. try
  13077. {
  13078. executeLoop();
  13079. }
  13080. catch (IException *e)
  13081. {
  13082. activity->fireException(e);
  13083. }
  13084. catch (...)
  13085. {
  13086. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13087. }
  13088. return 0;
  13089. }
  13090. void LoopExecutorThread::stop(bool aborting)
  13091. {
  13092. safeInput->stop(aborting);
  13093. RestartableThread::join();
  13094. }
  13095. void LoopExecutorThread::reset()
  13096. {
  13097. safeInput->reset();
  13098. }
  13099. void LoopExecutorThread::executeLoop()
  13100. {
  13101. unsigned iterations = 0;
  13102. unsigned counter = 0;
  13103. unsigned outputIndex = 0;
  13104. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13105. loop
  13106. {
  13107. if (activity->activityKind == TAKloopcount)
  13108. {
  13109. if (counter == activity->maxIterations)
  13110. break;
  13111. }
  13112. else
  13113. {
  13114. //This condition isn't quite right because it needs to be whether the filtered
  13115. //input is empty. May be ok if we include that in the semantics,
  13116. if (tempResults[1-outputIndex].ordinality() == 0)
  13117. break;
  13118. }
  13119. unsigned numParallel = activity->getNumParallel(iterations);
  13120. Linked<IRoxieInput> curInput;
  13121. if (iterations == 0)
  13122. curInput.set(safeInput);
  13123. else
  13124. {
  13125. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13126. inputQueue.enqueue(NULL);
  13127. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  13128. }
  13129. SafeRowQueue * curOutput = NULL;
  13130. if (counter+numParallel > activity->maxIterations)
  13131. numParallel = activity->maxIterations - counter;
  13132. else if (counter+numParallel < activity->maxIterations)
  13133. curOutput = &tempResults[outputIndex];
  13134. executeLoopInstance(counter, numParallel, curInput, curOutput);
  13135. outputIndex = 1-outputIndex;
  13136. counter += numParallel;
  13137. iterations++;
  13138. }
  13139. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13140. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13141. while (inputQueue.ordinality())
  13142. {
  13143. const void * next = inputQueue.dequeue();
  13144. activity->enqueueResult(next);
  13145. }
  13146. activity->finishResults();
  13147. }
  13148. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  13149. {
  13150. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13151. Linked<IRoxieInput> curInput = input;
  13152. unsigned i;
  13153. for (i= 0; i != numIterations; i++)
  13154. {
  13155. unsigned thisCounter = counter+i+1;
  13156. IRoxieInput * filtered = curInput;
  13157. if (flags & IHThorLoopArg::LFfiltered)
  13158. {
  13159. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  13160. savedInputs.append(*filtered);
  13161. }
  13162. //graph is kept, so new curInput will be guaranteed to exist
  13163. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  13164. }
  13165. try
  13166. {
  13167. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13168. if (spillOutput)
  13169. {
  13170. loop
  13171. {
  13172. const void * next = curInput->nextInGroup();
  13173. if (!next)
  13174. break;
  13175. spillOutput->enqueue(next);
  13176. }
  13177. }
  13178. else
  13179. {
  13180. loop
  13181. {
  13182. const void * next = curInput->nextInGroup();
  13183. if (!next)
  13184. break;
  13185. activity->enqueueResult(next);
  13186. }
  13187. }
  13188. }
  13189. catch (IException *E)
  13190. {
  13191. ctx->notifyAbort(E);
  13192. for (i= 0; i != numIterations; i++)
  13193. {
  13194. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13195. }
  13196. curInput->stop(true);
  13197. curInput->reset();
  13198. throw;
  13199. }
  13200. for (i= 0; i != numIterations; i++)
  13201. {
  13202. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  13203. }
  13204. curInput->stop(false);
  13205. curInput->reset();
  13206. }
  13207. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  13208. {
  13209. if (!cachedGraphs.isItem(i))
  13210. cachedGraphs.append(*activity->createChildGraphInstance());
  13211. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  13212. loopGraph->beforeExecute();
  13213. if (!loopGraph->querySetInputResult(1, input))
  13214. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  13215. activity->createCounterResult(loopGraph, counter);
  13216. return loopGraph->selectOutput(0);
  13217. }
  13218. //=================================================================================
  13219. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  13220. {
  13221. public:
  13222. IMPLEMENT_IINTERFACE
  13223. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  13224. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  13225. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  13226. virtual void toXML(const byte * self, IXmlWriter & out) { }
  13227. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  13228. virtual unsigned getMetaFlags() { return 0; }
  13229. virtual void destruct(byte * self) {}
  13230. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13231. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13232. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13233. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  13234. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13235. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  13236. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  13237. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  13238. };
  13239. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  13240. {
  13241. unsigned loopGraphId;
  13242. unsigned flags;
  13243. Linked<IOutputMetaData> counterMeta;
  13244. public:
  13245. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13246. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13247. {
  13248. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  13249. flags = helper->getFlags();
  13250. counterMeta.setown(new CCounterRowMetaData);
  13251. }
  13252. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13253. {
  13254. if (flags & IHThorLoopArg::LFparallel)
  13255. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13256. else
  13257. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13258. }
  13259. };
  13260. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13261. {
  13262. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13263. }
  13264. //=================================================================================
  13265. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  13266. {
  13267. protected:
  13268. IHThorGraphLoopArg &helper;
  13269. unsigned maxIterations;
  13270. unsigned flags;
  13271. rtlRowBuilder GraphExtractBuilder;
  13272. unsigned loopGraphId;
  13273. Linked<IOutputMetaData> counterMeta;
  13274. public:
  13275. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13276. : CRoxieServerActivity(_factory, _probeManager),
  13277. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  13278. {
  13279. flags = helper.getFlags();
  13280. maxIterations = 0;
  13281. }
  13282. virtual bool needsAllocator() const { return true; }
  13283. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13284. {
  13285. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13286. int iterations = (int) helper.numIterations();
  13287. maxIterations = (iterations >= 0) ? iterations : 0;
  13288. if (maxIterations > maxGraphLoopIterations)
  13289. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  13290. if (maxIterations != 0)
  13291. {
  13292. GraphExtractBuilder.clear();
  13293. helper.createParentExtract(GraphExtractBuilder);
  13294. }
  13295. }
  13296. virtual void stop(bool aborting)
  13297. {
  13298. CRoxieServerActivity::stop(aborting);
  13299. GraphExtractBuilder.clear();
  13300. }
  13301. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13302. {
  13303. if (flags & IHThorGraphLoopArg::GLFcounter)
  13304. {
  13305. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13306. *((thor_loop_counter_t *)counterRow) = counter;
  13307. RtlLinkedDatasetBuilder builder(rowAllocator);
  13308. builder.appendOwn(counterRow);
  13309. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13310. graph->setInputResult(0, counterResult);
  13311. }
  13312. }
  13313. };
  13314. //=================================================================================
  13315. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  13316. {
  13317. Owned<IActivityGraph> GraphQuery;
  13318. Owned<IRoxieServerChildGraph> loopGraph;
  13319. Linked<IRoxieInput> resultInput;
  13320. bool evaluated;
  13321. public:
  13322. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13323. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13324. {
  13325. evaluated = false;
  13326. }
  13327. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13328. {
  13329. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13330. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13331. }
  13332. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13333. {
  13334. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13335. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13336. loopGraph.set(GraphQuery->queryLoopGraph());
  13337. evaluated = false;
  13338. }
  13339. virtual void stop(bool aborting)
  13340. {
  13341. if (loopGraph)
  13342. loopGraph->clearGraphLoopResults();
  13343. CRoxieServerGraphLoopActivity::stop(aborting);
  13344. }
  13345. virtual const void * nextInGroup()
  13346. {
  13347. ActivityTimer t(totalCycles, timeActivities);
  13348. if (!evaluated)
  13349. {
  13350. executeEntireGraph();
  13351. evaluated = true;
  13352. }
  13353. const void * ret = resultInput->nextInGroup();
  13354. if (ret)
  13355. processed++;
  13356. return ret;
  13357. }
  13358. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13359. {
  13360. try
  13361. {
  13362. loopGraph->beforeExecute();
  13363. createCounterResult(loopGraph, counter);
  13364. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13365. loopGraph->afterExecute();
  13366. }
  13367. catch (...)
  13368. {
  13369. CTXLOG("Exception thrown in graph body - cleaning up");
  13370. loopGraph->afterExecute();
  13371. throw;
  13372. }
  13373. }
  13374. void createInitialGraphInput()
  13375. {
  13376. loopGraph->clearGraphLoopResults();
  13377. RtlLinkedDatasetBuilder builder(rowAllocator);
  13378. input->readAll(builder);
  13379. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13380. loopGraph->setGraphLoopResult(0, result);
  13381. }
  13382. void executeEntireGraph()
  13383. {
  13384. createInitialGraphInput();
  13385. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13386. {
  13387. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13388. }
  13389. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13390. }
  13391. };
  13392. //=================================================================================
  13393. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13394. {
  13395. public:
  13396. virtual unsigned numBranches()
  13397. {
  13398. return 0;
  13399. }
  13400. virtual IOutputMetaData * queryOutputMeta()
  13401. {
  13402. return NULL;// get it from the parent..
  13403. }
  13404. };
  13405. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13406. class CGraphIterationInfo : public CInterface
  13407. {
  13408. private:
  13409. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13410. unsigned sourceIdx;
  13411. Linked<IRoxieServerActivity> sourceAct;
  13412. Linked<IRoxieInput> sourceInput;
  13413. unsigned numUses;
  13414. unsigned iteration;
  13415. public:
  13416. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13417. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13418. {
  13419. numUses = 0;
  13420. }
  13421. inline void noteUsed()
  13422. {
  13423. numUses++;
  13424. }
  13425. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13426. {
  13427. if (numUses > 1)
  13428. {
  13429. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13430. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13431. splitter->onCreate(ctx, NULL);
  13432. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13433. if (probeManager)
  13434. {
  13435. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13436. input = static_cast<IRoxieInput*>(inputBase);
  13437. // MORE - shouldn't this be added to probes?
  13438. }
  13439. sourceAct.setown(splitter);
  13440. sourceAct->setInput(0, input);
  13441. sourceIdx = 0;
  13442. sourceInput.clear();
  13443. }
  13444. }
  13445. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13446. {
  13447. // MORE - not really necessary to create splitters in separate pass, is it?
  13448. if (factory) // we created a splitter....
  13449. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13450. IRoxieInput *ret = sourceInput;
  13451. if (probeManager)
  13452. {
  13453. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13454. ret = static_cast<IRoxieInput *>(inputBase);
  13455. probes.append(*LINK(ret));
  13456. }
  13457. if (factory) // we created a splitter....
  13458. sourceIdx++;
  13459. return ret;
  13460. }
  13461. };
  13462. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13463. {
  13464. Owned<IActivityGraph> childGraph;
  13465. IRoxieInput * resultInput;
  13466. CIArrayOf<CGraphIterationInfo> outputs;
  13467. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13468. Owned<CExtractMapperInput> inputExtractMapper;
  13469. IProbeManager *probeManager;
  13470. unsigned createLoopCounter;
  13471. IArrayOf<IRoxieInput> probes;
  13472. public:
  13473. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13474. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13475. {
  13476. inputExtractMapper.setown(new CExtractMapperInput);
  13477. resultInput = NULL;
  13478. createLoopCounter = 0;
  13479. }
  13480. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13481. {
  13482. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13483. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13484. }
  13485. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13486. {
  13487. //Input needs to be handled very carefully.....
  13488. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13489. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13490. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13491. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13492. assertex(idx == 0);
  13493. inputExtractMapper->setInput(_in);
  13494. }
  13495. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13496. {
  13497. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13498. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13499. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13500. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13501. }
  13502. virtual void stop(bool aborting)
  13503. {
  13504. if (resultInput)
  13505. resultInput->stop(aborting);
  13506. CRoxieServerGraphLoopActivity::stop(aborting);
  13507. }
  13508. virtual void reset()
  13509. {
  13510. if (resultInput)
  13511. resultInput->reset();
  13512. resultInput = NULL;
  13513. outputs.kill();
  13514. iterationGraphs.kill(); // must be done after all activities killed
  13515. if (probeManager)
  13516. {
  13517. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13518. probes.kill();
  13519. }
  13520. CRoxieServerGraphLoopActivity::reset();
  13521. }
  13522. virtual const void * nextInGroup()
  13523. {
  13524. ActivityTimer t(totalCycles, timeActivities);
  13525. const void * ret = resultInput->nextInGroup();
  13526. if (ret)
  13527. processed++;
  13528. return ret;
  13529. }
  13530. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13531. {
  13532. //result(0) is the input to the graph.
  13533. resultInput = inputExtractMapper;
  13534. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13535. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13536. {
  13537. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13538. graph->beforeExecute();
  13539. iterationGraphs.append(*graph);
  13540. graph->gatherIterationUsage(*this);
  13541. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13542. outputs.append(*iteration);
  13543. }
  13544. createLoopCounter = 0;
  13545. createSplitters(probeManager);
  13546. ForEachItemIn(i2, iterationGraphs)
  13547. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13548. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13549. }
  13550. void createSplitters(IProbeManager *probeManager)
  13551. {
  13552. ForEachItemIn(i, outputs)
  13553. {
  13554. CGraphIterationInfo & next = outputs.item(i);
  13555. next.createSplitter(ctx, probeManager);
  13556. }
  13557. }
  13558. //IRoxieServerLoopResultProcessor
  13559. virtual void noteUseIteration(unsigned _whichIteration)
  13560. {
  13561. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13562. if (whichIteration >= 0)
  13563. {
  13564. if (!outputs.isItem(whichIteration))
  13565. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13566. outputs.item(whichIteration).noteUsed();
  13567. }
  13568. }
  13569. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13570. {
  13571. if (outputs.isItem(whichIteration))
  13572. {
  13573. CGraphIterationInfo & next = outputs.item(whichIteration);
  13574. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13575. }
  13576. return NULL;
  13577. }
  13578. };
  13579. //=================================================================================
  13580. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13581. {
  13582. unsigned loopGraphId;
  13583. unsigned flags;
  13584. Linked<IOutputMetaData> counterMeta;
  13585. public:
  13586. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13587. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13588. {
  13589. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13590. flags = helper->getFlags();
  13591. counterMeta.setown(new CCounterRowMetaData);
  13592. }
  13593. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13594. {
  13595. if (kind == TAKparallelgraphloop)
  13596. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13597. else
  13598. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13599. }
  13600. };
  13601. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13602. {
  13603. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13604. }
  13605. //=====================================================================================================
  13606. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13607. {
  13608. class OutputAdaptor : public CExtractMapperInput
  13609. {
  13610. bool stopped;
  13611. public:
  13612. CRoxieServerLibraryCallActivity *parent;
  13613. unsigned oid;
  13614. unsigned processed;
  13615. public:
  13616. IMPLEMENT_IINTERFACE;
  13617. OutputAdaptor() : CExtractMapperInput(NULL)
  13618. {
  13619. parent = NULL;
  13620. oid = 0;
  13621. init();
  13622. }
  13623. ~OutputAdaptor()
  13624. {
  13625. if (traceStartStop)
  13626. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  13627. if (processed && parent && parent->factory)
  13628. {
  13629. parent->factory->noteProcessed(oid, processed);
  13630. if (parent->ctx)
  13631. parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed);
  13632. }
  13633. }
  13634. void init()
  13635. {
  13636. processed = 0;
  13637. stopped = false;
  13638. }
  13639. virtual unsigned queryId() const
  13640. {
  13641. return parent->queryId();
  13642. }
  13643. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13644. {
  13645. parent->start(oid, parentExtractSize, parentExtract, paused);
  13646. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13647. }
  13648. virtual void stop(bool aborting)
  13649. {
  13650. if (!stopped)
  13651. {
  13652. stopped = true;
  13653. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13654. CExtractMapperInput::stop(aborting);
  13655. }
  13656. };
  13657. virtual void reset()
  13658. {
  13659. parent->reset(oid);
  13660. CExtractMapperInput::reset();
  13661. init();
  13662. };
  13663. virtual void checkAbort()
  13664. {
  13665. parent->checkAbort();
  13666. }
  13667. };
  13668. IHThorLibraryCallArg &helper;
  13669. unsigned numInputs;
  13670. unsigned numOutputs;
  13671. unsigned numActiveOutputs;
  13672. bool started;
  13673. OutputAdaptor* outputAdaptors;
  13674. CExtractMapperInput * * inputAdaptors;
  13675. bool * inputUsed;
  13676. bool * outputUsed;
  13677. Owned<IException> error;
  13678. CriticalSection crit;
  13679. rtlRowBuilder libraryExtractBuilder;
  13680. Owned<IActivityGraph> libraryGraph;
  13681. const LibraryCallFactoryExtra & extra;
  13682. public:
  13683. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13684. : CRoxieServerActivity(_factory, _probeManager),
  13685. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13686. {
  13687. numInputs = _numInputs;
  13688. numOutputs = _numOutputs;
  13689. numActiveOutputs = numOutputs;
  13690. inputAdaptors = new CExtractMapperInput*[numInputs];
  13691. inputUsed = new bool[numInputs];
  13692. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13693. {
  13694. inputAdaptors[i1] = new CExtractMapperInput;
  13695. inputUsed[i1] = false;
  13696. }
  13697. outputAdaptors = new OutputAdaptor[numOutputs];
  13698. outputUsed = new bool[numOutputs];
  13699. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13700. {
  13701. outputAdaptors[i2].parent = this;
  13702. outputAdaptors[i2].oid = i2;
  13703. outputUsed[i2] = false;
  13704. }
  13705. started = false;
  13706. }
  13707. ~CRoxieServerLibraryCallActivity()
  13708. {
  13709. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13710. ::Release(inputAdaptors[i1]);
  13711. delete [] inputAdaptors;
  13712. delete [] inputUsed;
  13713. delete [] outputAdaptors;
  13714. delete [] outputUsed;
  13715. }
  13716. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13717. {
  13718. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13719. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13720. libraryGraph->onCreate(_ctx, _colocalParent);
  13721. //Now map the inputs and outputs to the adapters
  13722. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13723. for (unsigned i1=0; i1<numInputs; i1++)
  13724. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13725. for (unsigned i2=0; i2<numOutputs; i2++)
  13726. {
  13727. unsigned outputIndex = extra.outputs.item(i2);
  13728. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13729. outputAdaptors[i2].setInput(output);
  13730. }
  13731. }
  13732. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13733. {
  13734. CriticalBlock b(crit);
  13735. if (error)
  13736. throw error.getLink();
  13737. if (factory)
  13738. factory->noteStarted(oid);
  13739. if (!started)
  13740. {
  13741. // even though it is not complete, we don't want to run this again if it fails.
  13742. started = true;
  13743. //see notes on splitter above
  13744. try
  13745. {
  13746. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13747. }
  13748. catch (IException *E)
  13749. {
  13750. #ifdef TRACE_SPLIT
  13751. CTXLOG("spill %d caught exception in start", activityId);
  13752. #endif
  13753. error.set(E);
  13754. throw;
  13755. }
  13756. catch (...)
  13757. {
  13758. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13759. error.set(E);
  13760. throw E;
  13761. }
  13762. //recreate the parent extract, and use it to reinitialize the graphs...
  13763. libraryExtractBuilder.clear();
  13764. helper.createParentExtract(libraryExtractBuilder);
  13765. // 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
  13766. // some inputs before we see start on others.
  13767. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13768. {
  13769. if (inputUsed[i1])
  13770. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13771. else
  13772. inputAdaptors[i1]->stop(false);
  13773. }
  13774. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13775. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13776. //call stop on all the unused inputs.
  13777. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13778. graph->beforeExecute();
  13779. ForEachItemIn(i3, extra.unusedOutputs)
  13780. {
  13781. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13782. output->stop(false);
  13783. }
  13784. }
  13785. }
  13786. virtual void stop(unsigned oid, bool aborting)
  13787. {
  13788. CriticalBlock b(crit);
  13789. if (--numActiveOutputs == 0)
  13790. {
  13791. //call stop on all the unused inputs.
  13792. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13793. graph->beforeExecute();
  13794. ForEachItemIn(i3, extra.unusedOutputs)
  13795. {
  13796. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13797. output->stop(false);
  13798. }
  13799. CRoxieServerActivity::stop(aborting);
  13800. }
  13801. }
  13802. void reset(unsigned oid)
  13803. {
  13804. started = false;
  13805. error.clear();
  13806. numActiveOutputs = numOutputs;
  13807. if (state != STATEreset) // make sure input is only reset once
  13808. {
  13809. CRoxieServerActivity::reset();
  13810. libraryGraph->reset();
  13811. //Call reset on all unused inputs/outputs from the graph - no one else will.
  13812. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13813. {
  13814. if (!inputUsed[i1])
  13815. inputAdaptors[i1]->reset();
  13816. }
  13817. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13818. ForEachItemIn(i3, extra.unusedOutputs)
  13819. {
  13820. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13821. output->reset();
  13822. }
  13823. }
  13824. };
  13825. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13826. {
  13827. inputAdaptors[idx]->setInput(_in);
  13828. }
  13829. public:
  13830. virtual const void *nextInGroup()
  13831. {
  13832. throwUnexpected(); // Internal logic error - we are not anybody's input
  13833. }
  13834. virtual IOutputMetaData * queryOutputMeta() const
  13835. {
  13836. throwUnexpected(); // should be called on outputs instead
  13837. }
  13838. virtual IRoxieInput *queryOutput(unsigned idx)
  13839. {
  13840. assertex(idx!=(unsigned)-1);
  13841. assertex(!outputUsed[idx]);
  13842. outputUsed[idx] = true;
  13843. return &outputAdaptors[idx];
  13844. }
  13845. };
  13846. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13847. {
  13848. ForEachItemIn(i1, _other.outputs)
  13849. outputs.append(_other.outputs.item(i1));
  13850. ForEachItemIn(i2, _other.unusedOutputs)
  13851. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13852. maxOutputs = _other.maxOutputs;
  13853. graphid = _other.graphid;
  13854. libraryName.set(_other.libraryName);
  13855. embeddedGraphName.set(_other.embeddedGraphName);
  13856. interfaceHash = _other.interfaceHash;
  13857. embedded = _other.embedded;
  13858. }
  13859. void LibraryCallFactoryExtra::calcUnused()
  13860. {
  13861. for (unsigned i=0; i < maxOutputs; i++)
  13862. if (!outputs.contains(i))
  13863. unusedOutputs.append(i);
  13864. }
  13865. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13866. {
  13867. private:
  13868. CRoxieServerMultiInputInfo inputs;
  13869. LibraryCallFactoryExtra extra;
  13870. public:
  13871. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13872. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13873. {
  13874. extra.set(_extra);
  13875. extra.calcUnused();
  13876. setNumOutputs(extra.outputs.ordinality());
  13877. }
  13878. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13879. {
  13880. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13881. }
  13882. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13883. {
  13884. inputs.set(idx, source, sourceidx);
  13885. }
  13886. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13887. {
  13888. return inputs.get(idx, sourceidx);
  13889. }
  13890. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13891. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13892. {
  13893. addXrefLibraryInfo(reply, extra.libraryName);
  13894. }
  13895. };
  13896. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13897. {
  13898. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13899. }
  13900. //=====================================================================================================
  13901. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13902. {
  13903. IHThorNWayInputArg & helper;
  13904. IRoxieInput ** inputs;
  13905. PointerArrayOf<IRoxieInput> selectedInputs;
  13906. unsigned numInputs;
  13907. public:
  13908. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13909. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13910. {
  13911. inputs = new IRoxieInput*[numInputs];
  13912. for (unsigned i = 0; i < numInputs; i++)
  13913. inputs[i] = NULL;
  13914. }
  13915. ~CRoxieServerNWayInputActivity()
  13916. {
  13917. delete [] inputs;
  13918. }
  13919. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13920. {
  13921. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13922. bool selectionIsAll;
  13923. size32_t selectionLen;
  13924. rtlDataAttr selection;
  13925. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13926. selectedInputs.kill();
  13927. if (selectionIsAll)
  13928. {
  13929. for (unsigned i=0; i < numInputs; i++)
  13930. selectedInputs.append(inputs[i]);
  13931. }
  13932. else
  13933. {
  13934. const size32_t * selections = (const size32_t *)selection.getdata();
  13935. unsigned max = selectionLen/sizeof(size32_t);
  13936. for (unsigned i = 0; i < max; i++)
  13937. {
  13938. unsigned nextIndex = selections[i];
  13939. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13940. for (unsigned j=i+1; j < max; j++)
  13941. {
  13942. if (nextIndex == selections[j])
  13943. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13944. }
  13945. if (nextIndex > numInputs)
  13946. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13947. selectedInputs.append(inputs[nextIndex-1]);
  13948. }
  13949. }
  13950. ForEachItemIn(i2, selectedInputs)
  13951. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13952. }
  13953. virtual void stop(bool aborting)
  13954. {
  13955. ForEachItemIn(i2, selectedInputs)
  13956. selectedInputs.item(i2)->stop(aborting);
  13957. CRoxieServerActivity::stop(aborting);
  13958. }
  13959. virtual unsigned __int64 queryLocalCycles() const
  13960. {
  13961. __int64 localCycles = totalCycles.totalCycles;
  13962. ForEachItemIn(i, selectedInputs)
  13963. {
  13964. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13965. }
  13966. if (localCycles < 0)
  13967. localCycles = 0;
  13968. return localCycles;
  13969. }
  13970. virtual IRoxieInput *queryInput(unsigned idx) const
  13971. {
  13972. if (selectedInputs.isItem(idx))
  13973. return selectedInputs.item(idx);
  13974. else
  13975. return NULL;
  13976. }
  13977. virtual void reset()
  13978. {
  13979. ForEachItemIn(i, selectedInputs)
  13980. selectedInputs.item(i)->reset();
  13981. selectedInputs.kill();
  13982. CRoxieServerActivity::reset();
  13983. }
  13984. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13985. {
  13986. assertex(idx < numInputs);
  13987. inputs[idx] = _in;
  13988. }
  13989. virtual const void * nextInGroup()
  13990. {
  13991. throwUnexpected();
  13992. }
  13993. virtual unsigned numConcreteOutputs() const
  13994. {
  13995. return selectedInputs.ordinality();
  13996. }
  13997. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13998. {
  13999. if (selectedInputs.isItem(idx))
  14000. return selectedInputs.item(idx);
  14001. return NULL;
  14002. }
  14003. };
  14004. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14005. {
  14006. // bool ordered;
  14007. public:
  14008. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14009. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14010. {
  14011. }
  14012. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14013. {
  14014. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  14015. }
  14016. };
  14017. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14018. {
  14019. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14020. }
  14021. //=====================================================================================================
  14022. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  14023. {
  14024. IHThorNWayGraphLoopResultReadArg & helper;
  14025. CIArrayOf<CRoxieServerActivity> resultReaders;
  14026. PointerArrayOf<IRoxieInput> inputs;
  14027. unsigned graphId;
  14028. bool grouped;
  14029. bool selectionIsAll;
  14030. size32_t selectionLen;
  14031. rtlDataAttr selection;
  14032. public:
  14033. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14034. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14035. {
  14036. grouped = helper.isGrouped();
  14037. graphId = _graphId;
  14038. selectionIsAll = false;
  14039. selectionLen = 0;
  14040. }
  14041. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14042. {
  14043. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14044. if (inputs.ordinality() == 0)
  14045. {
  14046. initInputSelection();
  14047. unsigned max = selectionLen / sizeof(size32_t);
  14048. const size32_t * selections = (const size32_t *)selection.getdata();
  14049. IProbeManager * probeManager = NULL; // MORE!!
  14050. for (unsigned i = 0; i < max; i++)
  14051. {
  14052. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  14053. resultReaders.append(*resultInput);
  14054. inputs.append(resultInput->queryOutput(0));
  14055. resultInput->onCreate(ctx, colocalParent);
  14056. resultInput->start(parentExtractSize, parentExtract, paused);
  14057. }
  14058. }
  14059. else
  14060. {
  14061. ForEachItemIn(i, inputs)
  14062. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  14063. }
  14064. }
  14065. virtual void stop(bool aborting)
  14066. {
  14067. ForEachItemIn(i, inputs)
  14068. inputs.item(i)->stop(aborting);
  14069. CRoxieServerActivity::stop(aborting);
  14070. }
  14071. virtual void reset()
  14072. {
  14073. ForEachItemIn(i, inputs)
  14074. inputs.item(i)->reset();
  14075. inputs.kill();
  14076. resultReaders.kill();
  14077. CRoxieServerActivity::reset();
  14078. }
  14079. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14080. {
  14081. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  14082. }
  14083. virtual const void * nextInGroup()
  14084. {
  14085. throwUnexpected();
  14086. }
  14087. virtual unsigned numConcreteOutputs() const
  14088. {
  14089. return inputs.ordinality();
  14090. }
  14091. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  14092. {
  14093. if (inputs.isItem(idx))
  14094. return inputs.item(idx);
  14095. return NULL;
  14096. }
  14097. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14098. {
  14099. ensureCreated();
  14100. basehelper.onStart(parentExtract, NULL);
  14101. initInputSelection();
  14102. unsigned max = selectionLen / sizeof(size32_t);
  14103. const size32_t * selections = (const size32_t *)selection.getdata();
  14104. for (unsigned i = 0; i < max; i++)
  14105. processor.noteUseIteration(selections[i]);
  14106. }
  14107. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  14108. {
  14109. //selection etc. already initialised from the gratherIterationUsage() call.
  14110. unsigned max = selectionLen / sizeof(size32_t);
  14111. const size32_t * selections = (const size32_t *)selection.getdata();
  14112. for (unsigned i = 0; i < max; i++)
  14113. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  14114. }
  14115. protected:
  14116. void initInputSelection()
  14117. {
  14118. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14119. if (selectionIsAll)
  14120. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  14121. }
  14122. };
  14123. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  14124. {
  14125. unsigned graphId;
  14126. public:
  14127. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  14128. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  14129. {
  14130. }
  14131. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14132. {
  14133. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  14134. }
  14135. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14136. {
  14137. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  14138. }
  14139. };
  14140. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  14141. {
  14142. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  14143. }
  14144. //=================================================================================
  14145. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  14146. {
  14147. public:
  14148. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  14149. IMPLEMENT_IINTERFACE
  14150. protected:
  14151. virtual const void * nextInputRow()
  14152. {
  14153. #ifdef TRACE_SEEK_REQUESTS
  14154. IRoxieContextLogger * logger = input->queryActivity();
  14155. const void * ret = doNextInputRow();
  14156. {
  14157. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14158. if (!ret)
  14159. xmlwrite.outputBool(true,"eof");
  14160. else if (input->queryOutputMeta()->hasXML())
  14161. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14162. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  14163. }
  14164. return ret;
  14165. #else
  14166. return doNextInputRow();
  14167. #endif
  14168. }
  14169. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14170. {
  14171. #ifdef TRACE_SEEK_REQUESTS
  14172. IRoxieContextLogger * logger = input->queryActivity();
  14173. {
  14174. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14175. if (input->queryOutputMeta()->hasXML())
  14176. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  14177. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  14178. numFields,
  14179. stepExtra.readAheadManyResults() ? "readahead " : "",
  14180. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14181. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14182. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14183. xmlwrite.str());
  14184. }
  14185. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14186. {
  14187. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  14188. if (!ret)
  14189. xmlwrite.outputBool(true,"eof");
  14190. else if (input->queryOutputMeta()->hasXML())
  14191. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  14192. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  14193. numFields,
  14194. stepExtra.readAheadManyResults() ? "readahead " : "",
  14195. stepExtra.returnMismatches() ? "mismatch" : "exact",
  14196. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  14197. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  14198. xmlwrite.str());
  14199. }
  14200. return ret;
  14201. #else
  14202. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14203. #endif
  14204. }
  14205. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14206. {
  14207. return input->gatherConjunctions(collector);
  14208. }
  14209. virtual void resetEOF()
  14210. {
  14211. input->resetEOF();
  14212. }
  14213. virtual IInputSteppingMeta * queryInputSteppingMeta()
  14214. {
  14215. return input->querySteppingMeta();
  14216. }
  14217. inline const void * doNextInputRow()
  14218. {
  14219. const void * ret = input->nextInGroup();
  14220. if (!ret)
  14221. ret = input->nextInGroup();
  14222. return ret;
  14223. }
  14224. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14225. {
  14226. assertex(wasCompleteMatch);
  14227. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14228. }
  14229. protected:
  14230. IRoxieInput * input;
  14231. };
  14232. //=================================================================================
  14233. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  14234. {
  14235. public:
  14236. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14237. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  14238. {
  14239. }
  14240. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14241. {
  14242. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14243. for (unsigned i=0; i < numInputs; i++)
  14244. {
  14245. IRoxieInput * cur = inputArray[i];
  14246. unsigned numRealInputs = cur->numConcreteOutputs();
  14247. for (unsigned j = 0; j < numRealInputs; j++)
  14248. {
  14249. IRoxieInput * curReal = cur->queryConcreteInput(j);
  14250. expandedInputs.append(curReal);
  14251. }
  14252. }
  14253. }
  14254. virtual void reset()
  14255. {
  14256. expandedInputs.kill();
  14257. CRoxieServerMultiInputActivity::reset();
  14258. }
  14259. protected:
  14260. PointerArrayOf<IRoxieInput> expandedInputs;
  14261. };
  14262. //=================================================================================
  14263. class CRoxieStreamMerger : public CStreamMerger
  14264. {
  14265. public:
  14266. CRoxieStreamMerger() : CStreamMerger(true)
  14267. {
  14268. inputArray = NULL;
  14269. }
  14270. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  14271. {
  14272. CStreamMerger::initInputs(_numInputs);
  14273. inputArray = _inputArray;
  14274. }
  14275. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  14276. {
  14277. const void * next;
  14278. bool matches = true;
  14279. if (seek)
  14280. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  14281. else
  14282. next = nextUngrouped(inputArray[i]);
  14283. pending[i] = next;
  14284. pendingMatches[i] = matches;
  14285. return (next != NULL);
  14286. }
  14287. virtual void releaseRow(const void * row)
  14288. {
  14289. ReleaseRoxieRow(row);
  14290. }
  14291. protected:
  14292. IRoxieInput **inputArray;
  14293. };
  14294. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  14295. {
  14296. public:
  14297. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14298. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  14299. helper((IHThorNWayMergeArg &)basehelper)
  14300. {
  14301. initializedMeta = false;
  14302. }
  14303. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14304. {
  14305. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14306. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  14307. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  14308. }
  14309. virtual void stop(bool aborting)
  14310. {
  14311. merger.done();
  14312. CRoxieServerNaryActivity::stop(aborting);
  14313. }
  14314. virtual void reset()
  14315. {
  14316. merger.cleanup();
  14317. CRoxieServerNaryActivity::reset();
  14318. initializedMeta = false;
  14319. }
  14320. virtual const void * nextInGroup()
  14321. {
  14322. ActivityTimer t(totalCycles, timeActivities);
  14323. const void * next = merger.nextRow();
  14324. if (next)
  14325. processed++;
  14326. return next;
  14327. }
  14328. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  14329. {
  14330. ActivityTimer t(totalCycles, timeActivities);
  14331. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  14332. if (next)
  14333. processed++;
  14334. return next;
  14335. }
  14336. virtual IInputSteppingMeta * querySteppingMeta()
  14337. {
  14338. if (expandedInputs.ordinality() == 0)
  14339. return NULL;
  14340. if (!initializedMeta)
  14341. {
  14342. meta.init(helper.querySteppingMeta(), false);
  14343. ForEachItemIn(i, expandedInputs)
  14344. {
  14345. if (meta.getNumFields() == 0)
  14346. break;
  14347. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14348. meta.intersect(inputMeta);
  14349. }
  14350. initializedMeta = true;
  14351. }
  14352. if (meta.getNumFields() == 0)
  14353. return NULL;
  14354. return &meta;
  14355. }
  14356. protected:
  14357. IHThorNWayMergeArg &helper;
  14358. CRoxieStreamMerger merger;
  14359. CSteppingMeta meta;
  14360. bool initializedMeta;
  14361. };
  14362. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14363. {
  14364. public:
  14365. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14366. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14367. {
  14368. }
  14369. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14370. {
  14371. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14372. }
  14373. };
  14374. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14375. {
  14376. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14377. }
  14378. //=================================================================================
  14379. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14380. {
  14381. public:
  14382. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14383. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14384. helper((IHThorNWayMergeJoinArg &)basehelper)
  14385. {
  14386. }
  14387. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14388. {
  14389. CRoxieServerNaryActivity::onCreate(_ctx, _colocalParent);
  14390. ICodeContext * codectx = ctx->queryCodeContext();
  14391. inputAllocator.setown(codectx->getRowAllocator(helper.queryInputMeta(), activityId));
  14392. outputAllocator.setown(codectx->getRowAllocator(helper.queryOutputMeta(), activityId));
  14393. }
  14394. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14395. {
  14396. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14397. ForEachItemIn(i1, expandedInputs)
  14398. {
  14399. IRoxieInput * cur = expandedInputs.item(i1);
  14400. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14401. processor.addInput(stepInput);
  14402. }
  14403. processor.beforeProcessing(inputAllocator, outputAllocator);
  14404. }
  14405. virtual void stop(bool aborting)
  14406. {
  14407. processor.afterProcessing();
  14408. CRoxieServerNaryActivity::stop(aborting);
  14409. }
  14410. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14411. {
  14412. return processor.gatherConjunctions(collector);
  14413. }
  14414. virtual void resetEOF()
  14415. {
  14416. processor.queryResetEOF();
  14417. }
  14418. virtual const void * nextInGroup()
  14419. {
  14420. ActivityTimer t(totalCycles, timeActivities);
  14421. const void * next = processor.nextInGroup();
  14422. if (next)
  14423. processed++;
  14424. return next;
  14425. }
  14426. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14427. {
  14428. ActivityTimer t(totalCycles, timeActivities);
  14429. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14430. if (next)
  14431. processed++;
  14432. return next;
  14433. }
  14434. virtual IInputSteppingMeta * querySteppingMeta()
  14435. {
  14436. return processor.queryInputSteppingMeta();
  14437. }
  14438. protected:
  14439. IHThorNWayMergeJoinArg & helper;
  14440. CMergeJoinProcessor & processor;
  14441. Owned<IEngineRowAllocator> inputAllocator;
  14442. Owned<IEngineRowAllocator> outputAllocator;
  14443. };
  14444. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14445. {
  14446. public:
  14447. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14448. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14449. {
  14450. }
  14451. protected:
  14452. CAndMergeJoinProcessor andProcessor;
  14453. };
  14454. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14455. {
  14456. public:
  14457. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14458. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14459. {
  14460. }
  14461. protected:
  14462. CAndLeftMergeJoinProcessor andLeftProcessor;
  14463. };
  14464. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14465. {
  14466. public:
  14467. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14468. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14469. {
  14470. }
  14471. protected:
  14472. CMofNMergeJoinProcessor mofnProcessor;
  14473. };
  14474. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14475. {
  14476. public:
  14477. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14478. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14479. {
  14480. }
  14481. protected:
  14482. CProximityJoinProcessor proximityProcessor;
  14483. };
  14484. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14485. {
  14486. unsigned flags;
  14487. public:
  14488. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14489. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14490. {
  14491. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14492. flags = helper->getJoinFlags();
  14493. }
  14494. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14495. {
  14496. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14497. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14498. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14499. {
  14500. case IHThorNWayMergeJoinArg::MJFinner:
  14501. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14502. case IHThorNWayMergeJoinArg::MJFleftonly:
  14503. case IHThorNWayMergeJoinArg::MJFleftouter:
  14504. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14505. case IHThorNWayMergeJoinArg::MJFmofn:
  14506. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14507. default:
  14508. throwUnexpected();
  14509. }
  14510. }
  14511. };
  14512. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14513. {
  14514. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14515. }
  14516. //=================================================================================
  14517. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14518. {
  14519. IHThorNWaySelectArg &helper;
  14520. public:
  14521. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14522. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14523. helper((IHThorNWaySelectArg &)basehelper)
  14524. {
  14525. selectedInput = NULL;
  14526. }
  14527. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14528. {
  14529. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14530. unsigned whichInput = helper.getInputIndex();
  14531. selectedInput = NULL;
  14532. if (whichInput--)
  14533. {
  14534. for (unsigned i=0; i < numInputs; i++)
  14535. {
  14536. IRoxieInput * cur = inputArray[i];
  14537. unsigned numRealInputs = cur->numConcreteOutputs();
  14538. if (whichInput < numRealInputs)
  14539. {
  14540. selectedInput = cur->queryConcreteInput(whichInput);
  14541. break;
  14542. }
  14543. whichInput -= numRealInputs;
  14544. }
  14545. }
  14546. }
  14547. virtual void reset()
  14548. {
  14549. selectedInput = NULL;
  14550. CRoxieServerMultiInputActivity::reset();
  14551. }
  14552. const void * nextInGroup()
  14553. {
  14554. ActivityTimer t(totalCycles, timeActivities);
  14555. if (!selectedInput)
  14556. return NULL;
  14557. return selectedInput->nextInGroup();
  14558. }
  14559. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14560. {
  14561. if (!selectedInput)
  14562. return false;
  14563. return selectedInput->gatherConjunctions(collector);
  14564. }
  14565. virtual void resetEOF()
  14566. {
  14567. if (selectedInput)
  14568. selectedInput->resetEOF();
  14569. }
  14570. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14571. {
  14572. ActivityTimer t(totalCycles, timeActivities);
  14573. if (!selectedInput)
  14574. return NULL;
  14575. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14576. }
  14577. IInputSteppingMeta * querySteppingMeta()
  14578. {
  14579. if (selectedInput)
  14580. return selectedInput->querySteppingMeta();
  14581. return NULL;
  14582. }
  14583. protected:
  14584. IRoxieInput * selectedInput;
  14585. };
  14586. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14587. {
  14588. public:
  14589. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14590. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14591. {
  14592. }
  14593. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14594. {
  14595. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14596. }
  14597. };
  14598. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14599. {
  14600. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14601. }
  14602. //=================================================================================
  14603. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14604. {
  14605. protected:
  14606. IHThorRemoteArg &helper;
  14607. CRemoteResultAdaptor remote;
  14608. public:
  14609. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14610. : CRoxieServerActivity(_factory, _probeManager),
  14611. helper((IHThorRemoteArg &)basehelper),
  14612. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14613. {
  14614. }
  14615. virtual const IResolvedFile *queryVarFileInfo() const
  14616. {
  14617. return NULL;
  14618. }
  14619. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14620. {
  14621. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14622. remote.onCreate(this, this, _ctx, _colocalParent);
  14623. }
  14624. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14625. {
  14626. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14627. remote.onStart(parentExtractSize, parentExtract);
  14628. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14629. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14630. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14631. remote.flush();
  14632. remote.senddone();
  14633. }
  14634. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14635. {
  14636. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14637. }
  14638. virtual IRoxieInput *queryOutput(unsigned idx)
  14639. {
  14640. if (idx==(unsigned)-1)
  14641. idx = 0;
  14642. return idx ? NULL: &remote;
  14643. }
  14644. virtual void reset()
  14645. {
  14646. processed = remote.processed;
  14647. remote.processed = 0;
  14648. CRoxieServerActivity::reset();
  14649. }
  14650. virtual void onLimitExceeded(bool isKeyed)
  14651. {
  14652. if (traceLevel > 4)
  14653. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14654. helper.onLimitExceeded();
  14655. }
  14656. virtual const void *createLimitFailRow(bool isKeyed)
  14657. {
  14658. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14659. }
  14660. virtual const void *nextInGroup()
  14661. {
  14662. throwUnexpected(); // I am nobody's input
  14663. }
  14664. };
  14665. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14666. {
  14667. public:
  14668. RemoteActivityId remoteId;
  14669. bool isRoot;
  14670. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14672. {
  14673. }
  14674. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14675. {
  14676. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14677. }
  14678. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14679. {
  14680. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14681. }
  14682. virtual bool isSink() const
  14683. {
  14684. //I don't think the action version of this is implemented - but this would be the code
  14685. return isRoot && !meta.queryOriginal();
  14686. }
  14687. virtual const StatisticsMapping &queryStatsMapping() const
  14688. {
  14689. return allStatistics; // Child queries...
  14690. }
  14691. };
  14692. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14693. {
  14694. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14695. }
  14696. //=================================================================================
  14697. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14698. {
  14699. IHThorIterateArg &helper;
  14700. OwnedConstRoxieRow defaultRecord;
  14701. OwnedConstRoxieRow left;
  14702. OwnedConstRoxieRow right;
  14703. unsigned counter;
  14704. public:
  14705. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14706. : CRoxieServerActivity(_factory, _probeManager),
  14707. helper((IHThorIterateArg &)basehelper)
  14708. {
  14709. counter = 0;
  14710. }
  14711. virtual bool needsAllocator() const { return true; }
  14712. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14713. {
  14714. counter = 0;
  14715. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14716. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14717. size32_t thisSize = helper.createDefault(rowBuilder);
  14718. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14719. }
  14720. virtual void reset()
  14721. {
  14722. defaultRecord.clear();
  14723. right.clear();
  14724. left.clear();
  14725. CRoxieServerActivity::reset();
  14726. }
  14727. virtual const void * nextInGroup()
  14728. {
  14729. ActivityTimer t(totalCycles, timeActivities);
  14730. loop
  14731. {
  14732. right.setown(input->nextInGroup());
  14733. if (!right)
  14734. {
  14735. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14736. left.clear();
  14737. counter = 0;
  14738. if (skippedGroup) continue;
  14739. return NULL;
  14740. }
  14741. try
  14742. {
  14743. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14744. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14745. if (outSize)
  14746. {
  14747. left.setown(rowBuilder.finalizeRowClear(outSize));
  14748. processed++;
  14749. return left.getLink();
  14750. }
  14751. }
  14752. catch (IException *E)
  14753. {
  14754. throw makeWrappedException(E);
  14755. }
  14756. }
  14757. }
  14758. };
  14759. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14760. {
  14761. public:
  14762. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14763. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14764. {
  14765. }
  14766. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14767. {
  14768. return new CRoxieServerIterateActivity(this, _probeManager);
  14769. }
  14770. };
  14771. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14772. {
  14773. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14774. }
  14775. //=================================================================================
  14776. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14777. {
  14778. IHThorProcessArg &helper;
  14779. OwnedConstRoxieRow curRight;
  14780. OwnedConstRoxieRow initialRight;
  14781. unsigned counter;
  14782. Owned<IEngineRowAllocator> rightRowAllocator;
  14783. public:
  14784. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14785. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14786. {
  14787. counter = 0;
  14788. }
  14789. virtual bool needsAllocator() const { return true; }
  14790. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14791. {
  14792. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14793. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14794. }
  14795. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14796. {
  14797. counter = 0;
  14798. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14799. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14800. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14801. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14802. curRight.set(initialRight);
  14803. }
  14804. virtual const void * nextInGroup()
  14805. {
  14806. ActivityTimer t(totalCycles, timeActivities);
  14807. try
  14808. {
  14809. loop
  14810. {
  14811. const void * in = input->nextInGroup();
  14812. if (!in)
  14813. {
  14814. bool eog = (curRight != initialRight); // processed any records?
  14815. counter = 0;
  14816. curRight.set(initialRight);
  14817. if (eog)
  14818. return NULL;
  14819. in = input->nextInGroup();
  14820. if (!in)
  14821. return NULL;
  14822. }
  14823. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14824. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14825. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14826. ReleaseRoxieRow(in);
  14827. if (outSize)
  14828. {
  14829. //MORE: This should be returned...
  14830. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14831. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14832. processed++;
  14833. return rowBuilder.finalizeRowClear(outSize);
  14834. }
  14835. }
  14836. }
  14837. catch (IException *E)
  14838. {
  14839. throw makeWrappedException(E);
  14840. }
  14841. }
  14842. };
  14843. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14844. {
  14845. public:
  14846. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14847. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14848. {
  14849. }
  14850. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14851. {
  14852. return new CRoxieServerProcessActivity(this, _probeManager);
  14853. }
  14854. };
  14855. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14856. {
  14857. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14858. }
  14859. //=================================================================================
  14860. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14861. {
  14862. IHThorGroupArg &helper;
  14863. bool endPending;
  14864. bool eof;
  14865. bool first;
  14866. const void *next;
  14867. public:
  14868. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14869. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14870. {
  14871. next = NULL;
  14872. endPending = false;
  14873. eof = false;
  14874. first = true;
  14875. }
  14876. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14877. {
  14878. endPending = false;
  14879. eof = false;
  14880. first = true;
  14881. assertex(next == NULL);
  14882. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14883. }
  14884. virtual void reset()
  14885. {
  14886. ReleaseClearRoxieRow(next);
  14887. CRoxieServerActivity::reset();
  14888. }
  14889. virtual const void * nextInGroup()
  14890. {
  14891. ActivityTimer t(totalCycles, timeActivities);
  14892. if (first)
  14893. {
  14894. next = input->nextInGroup();
  14895. first = false;
  14896. }
  14897. if (eof || endPending)
  14898. {
  14899. endPending = false;
  14900. return NULL;
  14901. }
  14902. const void * prev = next;
  14903. next = input->nextInGroup();
  14904. if (!next)
  14905. next = input->nextInGroup();
  14906. if (next)
  14907. {
  14908. assertex(prev);
  14909. if (!helper.isSameGroup(prev, next))
  14910. endPending = true;
  14911. }
  14912. else
  14913. eof = true;
  14914. if (prev)
  14915. processed++;
  14916. return prev;
  14917. }
  14918. };
  14919. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14920. {
  14921. public:
  14922. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14923. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14924. {
  14925. }
  14926. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14927. {
  14928. return new CRoxieServerGroupActivity(this, _probeManager);
  14929. }
  14930. };
  14931. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14932. {
  14933. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14934. }
  14935. //=================================================================================
  14936. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14937. {
  14938. unsigned __int64 limit;
  14939. unsigned __int64 skip;
  14940. unsigned doneThisGroup;
  14941. IHThorFirstNArg &helper;
  14942. public:
  14943. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14944. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14945. {
  14946. doneThisGroup = 0;
  14947. limit = 0;
  14948. skip = 0;
  14949. }
  14950. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14951. {
  14952. doneThisGroup = 0;
  14953. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14954. limit = helper.getLimit();
  14955. skip = helper.numToSkip();
  14956. lateStart(parentExtractSize, parentExtract, limit > 0);
  14957. if (limit + skip >= limit)
  14958. limit += skip;
  14959. }
  14960. const void * nextInGroup()
  14961. {
  14962. ActivityTimer t(totalCycles, timeActivities);
  14963. if (eof)
  14964. return NULL;
  14965. const void *ret;
  14966. loop
  14967. {
  14968. ret = input->nextInGroup();
  14969. if (!ret)
  14970. {
  14971. if (meta.isGrouped())
  14972. {
  14973. if (doneThisGroup > skip)
  14974. {
  14975. doneThisGroup = 0;
  14976. return NULL;
  14977. }
  14978. doneThisGroup = 0;
  14979. }
  14980. ret = input->nextInGroup();
  14981. if (!ret)
  14982. {
  14983. eof = true;
  14984. return NULL;
  14985. }
  14986. }
  14987. doneThisGroup++;
  14988. if (doneThisGroup > skip)
  14989. break;
  14990. ReleaseRoxieRow(ret);
  14991. }
  14992. if (doneThisGroup <= limit)
  14993. {
  14994. processed++;
  14995. return ret;
  14996. }
  14997. ReleaseRoxieRow(ret);
  14998. if (meta.isGrouped())
  14999. {
  15000. while ((ret = input->nextInGroup()) != NULL)
  15001. ReleaseRoxieRow(ret);
  15002. doneThisGroup = 0;
  15003. }
  15004. else
  15005. eof = true;
  15006. return NULL;
  15007. }
  15008. };
  15009. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  15010. {
  15011. public:
  15012. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15013. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15014. {
  15015. }
  15016. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15017. {
  15018. return new CRoxieServerFirstNActivity(this, _probeManager);
  15019. }
  15020. };
  15021. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15022. {
  15023. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15024. }
  15025. //=================================================================================
  15026. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  15027. {
  15028. bool done;
  15029. IHThorSelectNArg &helper;
  15030. public:
  15031. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15032. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  15033. {
  15034. done = false;
  15035. }
  15036. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15037. {
  15038. done = false;
  15039. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15040. }
  15041. const void *defaultRow()
  15042. {
  15043. if (!rowAllocator)
  15044. createRowAllocator(); // We delay as often not needed...
  15045. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15046. size32_t thisSize = helper.createDefault(rowBuilder);
  15047. return rowBuilder.finalizeRowClear(thisSize);
  15048. }
  15049. virtual const void * nextInGroup()
  15050. {
  15051. ActivityTimer t(totalCycles, timeActivities);
  15052. if (done)
  15053. return NULL;
  15054. done = true;
  15055. processed++; // always going to return a row!
  15056. unsigned __int64 index = helper.getRowToSelect();
  15057. while (--index)
  15058. {
  15059. const void * next = input->nextInGroup();
  15060. if (!next)
  15061. next = input->nextInGroup();
  15062. if (!next)
  15063. return defaultRow();
  15064. ReleaseRoxieRow(next);
  15065. }
  15066. const void * next = input->nextInGroup();
  15067. if (!next)
  15068. next = input->nextInGroup();
  15069. if (!next)
  15070. next = defaultRow();
  15071. return next;
  15072. }
  15073. };
  15074. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  15075. {
  15076. public:
  15077. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15078. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15079. {
  15080. }
  15081. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15082. {
  15083. return new CRoxieServerSelectNActivity(this, _probeManager);
  15084. }
  15085. };
  15086. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15087. {
  15088. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15089. }
  15090. //=================================================================================
  15091. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  15092. {
  15093. IHThorJoinArg &helper;
  15094. ICompare *collate;
  15095. OwnedRowArray group;
  15096. bool matchedLeft;
  15097. BoolArray matchedRight;
  15098. bool eof;
  15099. bool first;
  15100. unsigned leftIndex;
  15101. unsigned rightIndex;
  15102. unsigned rightOuterIndex;
  15103. unsigned joinLimit;
  15104. unsigned atmostLimit;
  15105. unsigned atmostsTriggered;
  15106. unsigned abortLimit;
  15107. unsigned keepLimit;
  15108. unsigned joinCounter;
  15109. bool leftOuterJoin;
  15110. bool rightOuterJoin;
  15111. bool exclude;
  15112. bool limitFail;
  15113. bool limitOnFail;
  15114. bool cloneLeft;
  15115. OwnedConstRoxieRow defaultLeft;
  15116. OwnedConstRoxieRow defaultRight;
  15117. OwnedConstRoxieRow lhs;
  15118. Owned<IException> failingLimit;
  15119. bool failingOuterAtmost;
  15120. Owned<IEngineRowAllocator> defaultAllocator;
  15121. Owned<IRHLimitedCompareHelper> limitedhelper;
  15122. Owned<CRHDualCache> dualcache;
  15123. IInputBase *dualCacheInput;
  15124. bool fillGroup()
  15125. {
  15126. group.clear();
  15127. matchedLeft = false;
  15128. matchedRight.kill();
  15129. failingOuterAtmost = false;
  15130. const void * next;
  15131. unsigned groupCount = 0;
  15132. while((next = input->nextInGroup()) != NULL)
  15133. {
  15134. if(groupCount==abortLimit)
  15135. {
  15136. if(limitFail)
  15137. failLimit(next);
  15138. if (ctx->queryDebugContext())
  15139. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15140. if(limitOnFail)
  15141. {
  15142. assertex(!failingLimit);
  15143. try
  15144. {
  15145. failLimit(next);
  15146. }
  15147. catch(IException * except)
  15148. {
  15149. failingLimit.setown(except);
  15150. }
  15151. assertex(failingLimit != NULL);
  15152. group.append(next);
  15153. groupCount++;
  15154. break;
  15155. }
  15156. group.clear();
  15157. groupCount = 0;
  15158. while(next)
  15159. {
  15160. ReleaseRoxieRow(next);
  15161. next = input->nextInGroup();
  15162. }
  15163. }
  15164. else if(groupCount==atmostLimit)
  15165. {
  15166. atmostsTriggered++;
  15167. if(leftOuterJoin)
  15168. {
  15169. group.append(next);
  15170. groupCount++;
  15171. failingOuterAtmost = true;
  15172. break;
  15173. }
  15174. else
  15175. {
  15176. group.clear();
  15177. groupCount = 0;
  15178. while (next)
  15179. {
  15180. ReleaseRoxieRow(next);
  15181. next = input->nextInGroup();
  15182. }
  15183. }
  15184. }
  15185. else
  15186. {
  15187. group.append(next);
  15188. groupCount++;
  15189. }
  15190. }
  15191. if(group.ordinality()==0)
  15192. {
  15193. eof = true;
  15194. return false;
  15195. }
  15196. leftIndex = 0;
  15197. rightIndex = 0;
  15198. rightOuterIndex = 0;
  15199. joinCounter = 0;
  15200. joinLimit = keepLimit;
  15201. ForEachItemIn(idx, group)
  15202. matchedRight.append(false);
  15203. return true;
  15204. }
  15205. void failLimit(const void * next)
  15206. {
  15207. helper.onMatchAbortLimitExceeded();
  15208. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15209. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15210. {
  15211. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  15212. }
  15213. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  15214. }
  15215. virtual bool needsAllocator() const { return true; }
  15216. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
  15217. {
  15218. try
  15219. {
  15220. if (cloneLeft && !except)
  15221. {
  15222. LinkRoxieRow(curLeft);
  15223. return curLeft;
  15224. }
  15225. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15226. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
  15227. if (outsize)
  15228. return rowBuilder.finalizeRowClear(outsize);
  15229. else
  15230. return NULL;
  15231. }
  15232. catch (IException *E)
  15233. {
  15234. throw makeWrappedException(E);
  15235. }
  15236. }
  15237. void createDefaultLeft()
  15238. {
  15239. if (!defaultLeft)
  15240. {
  15241. if (!defaultAllocator)
  15242. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15243. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15244. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15245. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15246. }
  15247. }
  15248. void createDefaultRight()
  15249. {
  15250. if (!defaultRight)
  15251. {
  15252. if (!defaultAllocator)
  15253. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15254. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  15255. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15256. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15257. }
  15258. }
  15259. public:
  15260. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15261. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  15262. {
  15263. collate = helper.queryCompareLeftRight();
  15264. eof = false;
  15265. first = true;
  15266. keepLimit = 0;
  15267. atmostLimit = 0;
  15268. atmostsTriggered = 0;
  15269. unsigned joinFlags = helper.getJoinFlags();
  15270. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15271. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15272. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15273. exclude = (joinFlags & JFexclude) != 0;
  15274. abortLimit = 0;
  15275. joinLimit = 0;
  15276. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  15277. getLimitType(joinFlags, limitFail, limitOnFail);
  15278. if((joinFlags & JFslidingmatch) != 0)
  15279. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  15280. failingOuterAtmost = false;
  15281. matchedLeft = false;
  15282. leftIndex = 0;
  15283. rightIndex = 0;
  15284. rightOuterIndex = 0;
  15285. joinCounter = 0;
  15286. dualCacheInput = NULL;
  15287. }
  15288. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15289. {
  15290. eof = false;
  15291. first = true;
  15292. failingLimit.clear();
  15293. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15294. keepLimit = helper.getKeepLimit();
  15295. if(keepLimit == 0)
  15296. keepLimit = (unsigned)-1;
  15297. atmostsTriggered = 0;
  15298. atmostLimit = helper.getJoinLimit();
  15299. if(atmostLimit == 0)
  15300. atmostLimit = (unsigned)-1;
  15301. else
  15302. assertex(!rightOuterJoin);
  15303. abortLimit = helper.getMatchAbortLimit();
  15304. if (abortLimit == 0)
  15305. abortLimit = (unsigned)-1;
  15306. if (rightOuterJoin)
  15307. createDefaultLeft();
  15308. if (leftOuterJoin || limitOnFail)
  15309. createDefaultRight();
  15310. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  15311. { //limited match join (s[1..n])
  15312. dualcache.setown(new CRHDualCache());
  15313. dualcache->init(CRoxieServerActivity::input);
  15314. dualCacheInput = dualcache->queryOut1();
  15315. failingOuterAtmost = false;
  15316. matchedLeft = false;
  15317. leftIndex = 0;
  15318. rightOuterIndex = 0;
  15319. joinCounter = 0;
  15320. limitedhelper.setown(createRHLimitedCompareHelper());
  15321. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  15322. }
  15323. }
  15324. virtual void reset()
  15325. {
  15326. if (atmostsTriggered)
  15327. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15328. group.clear();
  15329. CRoxieServerActivity::reset();
  15330. defaultLeft.clear();
  15331. defaultRight.clear();
  15332. }
  15333. virtual const void * nextInGroup()
  15334. {
  15335. ActivityTimer t(totalCycles, timeActivities);
  15336. if (limitedhelper)
  15337. {
  15338. while(!eof) //limited match join
  15339. {
  15340. if (!group.isItem(rightIndex))
  15341. {
  15342. lhs.setown(dualCacheInput->nextInGroup());
  15343. if (lhs)
  15344. {
  15345. rightIndex = 0;
  15346. joinCounter = 0;
  15347. group.clear();
  15348. limitedhelper->getGroup(group,lhs);
  15349. }
  15350. else
  15351. {
  15352. eof = true;
  15353. }
  15354. }
  15355. if (group.isItem(rightIndex))
  15356. {
  15357. const void * rhs = group.item(rightIndex++);
  15358. if(helper.match(lhs, rhs))
  15359. {
  15360. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15361. return ret;
  15362. }
  15363. }
  15364. }
  15365. return NULL;
  15366. }
  15367. else
  15368. {
  15369. if (first)
  15370. {
  15371. first = false;
  15372. fillGroup();
  15373. }
  15374. while(!eof)
  15375. {
  15376. if(failingOuterAtmost)
  15377. while(group.isItem(leftIndex))
  15378. {
  15379. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
  15380. if(ret)
  15381. {
  15382. processed++;
  15383. return ret;
  15384. }
  15385. }
  15386. if((joinLimit == 0) || !group.isItem(rightIndex))
  15387. {
  15388. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15389. {
  15390. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
  15391. if(ret)
  15392. {
  15393. matchedLeft = true;
  15394. processed++;
  15395. return ret;
  15396. }
  15397. }
  15398. leftIndex++;
  15399. matchedLeft = false;
  15400. rightIndex = 0;
  15401. joinCounter = 0;
  15402. joinLimit = keepLimit;
  15403. }
  15404. if(!group.isItem(leftIndex))
  15405. {
  15406. if(failingLimit || failingOuterAtmost)
  15407. {
  15408. const void * lhs;
  15409. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15410. {
  15411. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15412. ReleaseRoxieRow(lhs);
  15413. if(ret)
  15414. {
  15415. processed++;
  15416. return ret;
  15417. }
  15418. }
  15419. failingLimit.clear();
  15420. }
  15421. if(rightOuterJoin && !failingLimit)
  15422. while(group.isItem(rightOuterIndex))
  15423. if(!matchedRight.item(rightOuterIndex++))
  15424. {
  15425. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
  15426. if(ret)
  15427. {
  15428. processed++;
  15429. return ret;
  15430. }
  15431. }
  15432. if(!fillGroup())
  15433. return NULL;
  15434. continue;
  15435. }
  15436. const void * lhs = group.item(leftIndex);
  15437. if(failingLimit)
  15438. {
  15439. leftIndex++;
  15440. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
  15441. if(ret)
  15442. {
  15443. processed++;
  15444. return ret;
  15445. }
  15446. }
  15447. else
  15448. {
  15449. const void * rhs = group.item(rightIndex++);
  15450. if(helper.match(lhs, rhs))
  15451. {
  15452. matchedLeft = true;
  15453. matchedRight.replace(true, rightIndex-1);
  15454. if(!exclude)
  15455. {
  15456. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
  15457. if(ret)
  15458. {
  15459. processed++;
  15460. joinLimit--;
  15461. return ret;
  15462. }
  15463. }
  15464. }
  15465. }
  15466. }
  15467. return NULL;
  15468. }
  15469. }
  15470. };
  15471. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15472. {
  15473. public:
  15474. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15475. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15476. {
  15477. }
  15478. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15479. {
  15480. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15481. }
  15482. virtual const StatisticsMapping &queryStatsMapping() const
  15483. {
  15484. return joinStatistics;
  15485. }
  15486. };
  15487. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15488. {
  15489. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15490. }
  15491. //=====================================================================================================
  15492. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15493. {
  15494. private:
  15495. class LookupTable : public CInterface
  15496. {
  15497. public:
  15498. LookupTable(IHThorHashJoinArg &helper)
  15499. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  15500. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  15501. {
  15502. size = 0;
  15503. }
  15504. virtual const void *find(const void * left) const = 0;
  15505. virtual const void *findNext(const void * left) const = 0;
  15506. protected:
  15507. ICompare * leftRightCompare;
  15508. ICompare * rightCompare;
  15509. IHash * leftHash;
  15510. IHash * rightHash;
  15511. unsigned size;
  15512. };
  15513. class DedupLookupTable : public LookupTable
  15514. {
  15515. public:
  15516. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15517. : LookupTable(helper)
  15518. {
  15519. size = (4*rightRows.length())/3 + 1;
  15520. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  15521. ForEachItemIn(idx, rightRows)
  15522. add(rightRows.item(idx));
  15523. }
  15524. ~DedupLookupTable()
  15525. {
  15526. unsigned i;
  15527. for(i=0; i<size; i++)
  15528. ReleaseRoxieRow(table[i]);
  15529. free(table);
  15530. }
  15531. virtual const void *find(const void * left) const
  15532. {
  15533. unsigned index = leftHash->hash(left) % size;
  15534. unsigned start = index;
  15535. while (table[index])
  15536. {
  15537. if(leftRightCompare->docompare(left, table[index]) == 0)
  15538. return table[index];
  15539. index++;
  15540. if (index==size)
  15541. index = 0;
  15542. if (index==start)
  15543. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15544. }
  15545. return NULL;
  15546. }
  15547. virtual const void *findNext(const void * left) const
  15548. {
  15549. return NULL;
  15550. }
  15551. protected:
  15552. void add(const void * right)
  15553. {
  15554. unsigned index = rightHash->hash(right) % size;
  15555. unsigned start = index;
  15556. while (table[index])
  15557. {
  15558. if (rightCompare->docompare(table[index], right) == 0)
  15559. {
  15560. ReleaseRoxieRow(right);
  15561. return;
  15562. }
  15563. index++;
  15564. if (index==size)
  15565. index = 0;
  15566. if (index==start)
  15567. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  15568. }
  15569. table[index] = right;
  15570. }
  15571. const void * * table;
  15572. };
  15573. class FewLookupTable : public LookupTable
  15574. {
  15575. public:
  15576. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15577. : LookupTable(helper)
  15578. {
  15579. size = (4*rightRows.length())/3 + 1;
  15580. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  15581. findex = fstart = BadIndex;
  15582. ForEachItemIn(idx, rightRows)
  15583. add(rightRows.item(idx));
  15584. }
  15585. ~FewLookupTable()
  15586. {
  15587. unsigned i;
  15588. for(i=0; i<size; i++)
  15589. ReleaseRoxieRow(table[i]);
  15590. free(table);
  15591. }
  15592. virtual const void *find(const void * left) const
  15593. {
  15594. fstart = leftHash->hash(left) % size;
  15595. findex = fstart;
  15596. return doFind(left);
  15597. }
  15598. virtual const void *findNext(const void * left) const
  15599. {
  15600. if (findex == BadIndex)
  15601. return NULL;
  15602. advance();
  15603. return doFind(left);
  15604. }
  15605. protected:
  15606. void add(const void * right)
  15607. {
  15608. unsigned start = rightHash->hash(right) % size;
  15609. unsigned index = start;
  15610. while (table[index])
  15611. {
  15612. index++;
  15613. if (index==size)
  15614. index = 0;
  15615. if (index==start)
  15616. throwUnexpected(); //table is full, should never happen
  15617. }
  15618. table[index] = right;
  15619. }
  15620. void advance() const
  15621. {
  15622. findex++;
  15623. if(findex==size)
  15624. findex = 0;
  15625. if(findex==fstart)
  15626. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15627. }
  15628. const void *doFind(const void * left) const
  15629. {
  15630. while(table[findex])
  15631. {
  15632. if (leftRightCompare->docompare(left, table[findex]) == 0)
  15633. return table[findex];
  15634. advance();
  15635. }
  15636. findex = BadIndex;
  15637. return NULL;
  15638. }
  15639. const void * * table;
  15640. unsigned mutable fstart;
  15641. unsigned mutable findex;
  15642. static unsigned const BadIndex;
  15643. };
  15644. class ManyLookupTable : public LookupTable
  15645. {
  15646. public:
  15647. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  15648. : LookupTable(helper)
  15649. {
  15650. rightRows.swapWith(rowtable);
  15651. UInt64Array groups;
  15652. unsigned numRows = rowtable.length();
  15653. if (numRows)
  15654. {
  15655. unsigned groupStart = 0;
  15656. const void *groupStartRow = rowtable.item(0);
  15657. for (unsigned i=1; i < numRows; i++)
  15658. {
  15659. const void *thisRow = rowtable.item(i);
  15660. if (rightCompare->docompare(groupStartRow, thisRow))
  15661. {
  15662. groups.append(makeint64(groupStart, i-groupStart));
  15663. groupStart = i;
  15664. groupStartRow = thisRow;
  15665. }
  15666. }
  15667. groups.append(makeint64(groupStart, numRows-groupStart));
  15668. }
  15669. size = (4*groups.length())/3 + 1;
  15670. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  15671. ForEachItemIn(idx, groups)
  15672. {
  15673. unsigned __int64 group = groups.item(idx);
  15674. unsigned groupstart = high(group);
  15675. const void *row = rowtable.item(groupstart);
  15676. add(row, group);
  15677. }
  15678. }
  15679. ~ManyLookupTable()
  15680. {
  15681. ForEachItemIn(idx, rowtable)
  15682. {
  15683. ReleaseRoxieRow(rowtable.item(idx));
  15684. }
  15685. free(table);
  15686. }
  15687. void add(const void *row, unsigned __int64 group)
  15688. {
  15689. unsigned start = rightHash->hash(row) % size;
  15690. unsigned index = start;
  15691. while (table[index])
  15692. {
  15693. index++;
  15694. if (index==size)
  15695. index = 0;
  15696. if (index==start)
  15697. throwUnexpected(); //table is full, should never happen
  15698. }
  15699. table[index] = group;
  15700. }
  15701. virtual const void *find(const void * left) const
  15702. {
  15703. unsigned index = leftHash->hash(left) % size;
  15704. unsigned start = index;
  15705. while (table[index])
  15706. {
  15707. __uint64 group = table[index];
  15708. currentMatch = high(group);
  15709. const void *right = rowtable.item(currentMatch);
  15710. if (leftRightCompare->docompare(left, right) == 0)
  15711. {
  15712. currentMatch++;
  15713. matchCount = low(group) - 1;
  15714. return right;
  15715. }
  15716. index++;
  15717. if (index==size)
  15718. index = 0;
  15719. if (index==start)
  15720. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  15721. }
  15722. matchCount = 0;
  15723. return NULL;
  15724. }
  15725. virtual const void *findNext(const void * left) const
  15726. {
  15727. if (!matchCount)
  15728. return NULL;
  15729. matchCount--;
  15730. return rowtable.item(currentMatch++);
  15731. }
  15732. protected:
  15733. __uint64 *table;
  15734. ConstPointerArray rowtable;
  15735. mutable unsigned currentMatch;
  15736. mutable unsigned matchCount;
  15737. };
  15738. IHThorHashJoinArg &helper;
  15739. bool leftOuterJoin;
  15740. bool exclude;
  15741. bool eog;
  15742. bool many;
  15743. bool dedupRHS;
  15744. bool useFewTable;
  15745. bool matchedGroup;
  15746. const void *left;
  15747. OwnedConstRoxieRow defaultRight;
  15748. Owned<LookupTable> table;
  15749. unsigned keepLimit;
  15750. unsigned atmostLimit;
  15751. unsigned atmostsTriggered;
  15752. unsigned limitLimit;
  15753. unsigned joinCounter;
  15754. bool limitFail;
  15755. bool limitOnFail;
  15756. bool hasGroupLimit;
  15757. bool isSmartJoin;
  15758. unsigned keepCount;
  15759. bool gotMatch;
  15760. bool cloneLeft;
  15761. ConstPointerArray rightGroup;
  15762. aindex_t rightGroupIndex;
  15763. Owned<IException> failingLimit;
  15764. ConstPointerArray filteredRight;
  15765. ThorActivityKind activityKind;
  15766. Owned<IEngineRowAllocator> defaultRightAllocator;
  15767. void createDefaultRight()
  15768. {
  15769. if (!defaultRight)
  15770. {
  15771. if (!defaultRightAllocator)
  15772. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15773. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15774. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15775. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15776. }
  15777. }
  15778. public:
  15779. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  15780. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  15781. {
  15782. unsigned joinFlags = helper.getJoinFlags();
  15783. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15784. assertex((joinFlags & JFrightouter) == 0);
  15785. exclude = (joinFlags & JFexclude) != 0;
  15786. many = (joinFlags & JFmanylookup) != 0;
  15787. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15788. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15789. left = NULL;
  15790. activityKind = factory->getKind();
  15791. eog = false;
  15792. matchedGroup = false;
  15793. gotMatch = false;
  15794. keepLimit = 0;
  15795. keepCount = 0;
  15796. joinCounter = 0;
  15797. atmostLimit = 0;
  15798. atmostsTriggered = 0;
  15799. limitLimit = 0;
  15800. rightGroupIndex = 0;
  15801. hasGroupLimit = false;
  15802. isSmartJoin = (joinFlags & JFsmart) != 0;
  15803. getLimitType(joinFlags, limitFail, limitOnFail);
  15804. }
  15805. void loadRight()
  15806. {
  15807. ConstPointerArray rightset;
  15808. try
  15809. {
  15810. const void * next;
  15811. while(true)
  15812. {
  15813. next = input1->nextInGroup();
  15814. if(!next)
  15815. next = input1->nextInGroup();
  15816. if(!next)
  15817. break;
  15818. rightset.append(next);
  15819. }
  15820. if (!dedupRHS)
  15821. {
  15822. if (useFewTable)
  15823. {
  15824. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15825. }
  15826. else
  15827. {
  15828. if (!helper.isRightAlreadySorted())
  15829. {
  15830. if (helper.getJoinFlags() & JFunstable)
  15831. {
  15832. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  15833. }
  15834. else
  15835. {
  15836. unsigned rightord = rightset.ordinality();
  15837. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  15838. void **temp = (void **) tempAttr.bufferBase();
  15839. void **_rows = const_cast<void * *>(rightset.getArray());
  15840. memcpy(temp, _rows, rightord*sizeof(void **));
  15841. qsortvecstable(temp, rightord, *helper.queryCompareRight(), (void ***)_rows);
  15842. for (unsigned i = 0; i < rightord; i++)
  15843. {
  15844. *_rows = **((void ***)_rows);
  15845. _rows++;
  15846. }
  15847. }
  15848. }
  15849. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15850. }
  15851. }
  15852. else
  15853. {
  15854. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  15855. }
  15856. }
  15857. catch (...)
  15858. {
  15859. ForEachItemIn(idx, rightset)
  15860. ReleaseRoxieRow(rightset.item(idx));
  15861. throw;
  15862. }
  15863. };
  15864. virtual void reset()
  15865. {
  15866. if (atmostsTriggered)
  15867. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  15868. CRoxieServerTwoInputActivity::reset();
  15869. ReleaseClearRoxieRow(left);
  15870. defaultRight.clear();
  15871. table.clear();
  15872. }
  15873. virtual bool needsAllocator() const { return true; }
  15874. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15875. {
  15876. eog = false;
  15877. matchedGroup = false;
  15878. left = NULL;
  15879. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15880. keepLimit = helper.getKeepLimit();
  15881. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15882. atmostsTriggered = 0;
  15883. atmostLimit = helper.getJoinLimit();
  15884. limitLimit = helper.getMatchAbortLimit();
  15885. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15886. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15887. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15888. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15889. switch (activityKind)
  15890. {
  15891. case TAKlookupjoin:
  15892. case TAKlookupdenormalizegroup:
  15893. case TAKsmartjoin:
  15894. case TAKsmartdenormalizegroup:
  15895. if (leftOuterJoin)
  15896. createDefaultRight();
  15897. break;
  15898. }
  15899. if (limitOnFail)
  15900. createDefaultRight();
  15901. }
  15902. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15903. {
  15904. if (idx==1)
  15905. input1 = _in;
  15906. else
  15907. {
  15908. if ((helper.getJoinFlags() & JFparallel) != 0)
  15909. {
  15910. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15911. puller->setInput(0, _in);
  15912. _in = puller;
  15913. }
  15914. CRoxieServerActivity::setInput(idx, _in);
  15915. }
  15916. }
  15917. virtual const void * nextInGroup()
  15918. {
  15919. ActivityTimer t(totalCycles, timeActivities);
  15920. if(!table)
  15921. loadRight();
  15922. switch (activityKind)
  15923. {
  15924. case TAKlookupjoin:
  15925. case TAKsmartjoin:
  15926. return nextInGroupJoin();
  15927. case TAKlookupdenormalize:
  15928. case TAKlookupdenormalizegroup:
  15929. case TAKsmartdenormalize:
  15930. case TAKsmartdenormalizegroup:
  15931. return nextInGroupDenormalize();
  15932. }
  15933. throwUnexpected();
  15934. }
  15935. private:
  15936. const void * nextInGroupJoin()
  15937. {
  15938. if(!table)
  15939. loadRight();
  15940. while(true)
  15941. {
  15942. const void * right = NULL;
  15943. if(!left)
  15944. {
  15945. left = input->nextInGroup();
  15946. keepCount = keepLimit;
  15947. joinCounter = 0;
  15948. if(!left)
  15949. {
  15950. if (isSmartJoin)
  15951. left = input->nextInGroup();
  15952. if (!left)
  15953. {
  15954. if(matchedGroup || eog)
  15955. {
  15956. matchedGroup = false;
  15957. eog = true;
  15958. return NULL;
  15959. }
  15960. eog = true;
  15961. continue;
  15962. }
  15963. }
  15964. eog = false;
  15965. gotMatch = false;
  15966. right = getRightFirst();
  15967. }
  15968. else
  15969. right = getRightNext();
  15970. const void * ret = NULL;
  15971. if(failingLimit)
  15972. {
  15973. ret = joinException(left, failingLimit);
  15974. }
  15975. else
  15976. {
  15977. while(right)
  15978. {
  15979. if(helper.match(left, right))
  15980. {
  15981. gotMatch = true;
  15982. if(exclude)
  15983. break;
  15984. ret = joinRecords(left, right, ++joinCounter);
  15985. if(ret)
  15986. break;
  15987. }
  15988. right = getRightNext();
  15989. ret = NULL;
  15990. }
  15991. if(leftOuterJoin && !gotMatch)
  15992. {
  15993. ret = joinRecords(left, defaultRight, 0);
  15994. gotMatch = true;
  15995. }
  15996. }
  15997. if(ret)
  15998. {
  15999. matchedGroup = true;
  16000. processed++;
  16001. if(!many || (--keepCount == 0) || failingLimit)
  16002. {
  16003. ReleaseClearRoxieRow(left);
  16004. failingLimit.clear();
  16005. }
  16006. return ret;
  16007. }
  16008. ReleaseClearRoxieRow(left);
  16009. }
  16010. }
  16011. const void * nextInGroupDenormalize()
  16012. {
  16013. while(true)
  16014. {
  16015. left = input->nextInGroup();
  16016. if(!left)
  16017. {
  16018. if (!matchedGroup || isSmartJoin)
  16019. left = input->nextInGroup();
  16020. if (!left)
  16021. {
  16022. matchedGroup = false;
  16023. return NULL;
  16024. }
  16025. }
  16026. gotMatch = false;
  16027. const void * right = getRightFirst();
  16028. const void * ret = NULL;
  16029. if (failingLimit)
  16030. ret = joinException(left, failingLimit);
  16031. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  16032. {
  16033. OwnedConstRoxieRow newLeft;
  16034. newLeft.set(left);
  16035. unsigned rowSize = 0;
  16036. unsigned leftCount = 0;
  16037. keepCount = keepLimit;
  16038. while (right)
  16039. {
  16040. try
  16041. {
  16042. if (helper.match(left, right))
  16043. {
  16044. gotMatch = true;
  16045. if (exclude)
  16046. break;
  16047. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16048. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16049. if (thisSize)
  16050. {
  16051. rowSize = thisSize;
  16052. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16053. }
  16054. if(!many || (--keepCount == 0))
  16055. break;
  16056. }
  16057. right = getRightNext();
  16058. }
  16059. catch (IException *E)
  16060. {
  16061. throw makeWrappedException(E);
  16062. }
  16063. }
  16064. if (rowSize)
  16065. ret = newLeft.getClear();
  16066. else if (leftOuterJoin && !gotMatch)
  16067. {
  16068. ret = left;
  16069. left = NULL;
  16070. }
  16071. }
  16072. else
  16073. {
  16074. filteredRight.kill();
  16075. keepCount = keepLimit;
  16076. while (right)
  16077. {
  16078. if (helper.match(left, right))
  16079. {
  16080. gotMatch = true;
  16081. if(exclude)
  16082. break;
  16083. filteredRight.append(right);
  16084. if(!many || (--keepCount == 0))
  16085. break;
  16086. }
  16087. right = getRightNext();
  16088. }
  16089. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  16090. ret = denormalizeRecords(left, filteredRight);
  16091. filteredRight.kill();
  16092. }
  16093. ReleaseRoxieRow(left);
  16094. left = NULL;
  16095. failingLimit.clear();
  16096. if(ret)
  16097. {
  16098. matchedGroup = true;
  16099. processed++;
  16100. return ret;
  16101. }
  16102. }
  16103. }
  16104. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16105. {
  16106. if (cloneLeft)
  16107. {
  16108. LinkRoxieRow(left);
  16109. return left;
  16110. }
  16111. try
  16112. {
  16113. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16114. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16115. if (outSize)
  16116. return rowBuilder.finalizeRowClear(outSize);
  16117. else
  16118. return NULL;
  16119. }
  16120. catch (IException *E)
  16121. {
  16122. throw makeWrappedException(E);
  16123. }
  16124. }
  16125. const void * joinException(const void * left, IException * except)
  16126. {
  16127. try
  16128. {
  16129. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16130. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  16131. if (outSize)
  16132. return rowBuilder.finalizeRowClear(outSize);
  16133. else
  16134. return NULL;
  16135. }
  16136. catch (IException *E)
  16137. {
  16138. throw makeWrappedException(E);
  16139. }
  16140. }
  16141. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  16142. {
  16143. try
  16144. {
  16145. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16146. unsigned numRows = rows.ordinality();
  16147. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16148. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  16149. if (outSize)
  16150. return rowBuilder.finalizeRowClear(outSize);
  16151. else
  16152. return NULL;
  16153. }
  16154. catch (IException *E)
  16155. {
  16156. throw makeWrappedException(E);
  16157. }
  16158. }
  16159. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  16160. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  16161. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  16162. const void *fillRightGroup()
  16163. {
  16164. rightGroup.kill();
  16165. for(const void * right = table->find(left); right; right = table->findNext(left))
  16166. {
  16167. rightGroup.append(right);
  16168. if(rightGroup.ordinality() > limitLimit)
  16169. {
  16170. if(limitFail)
  16171. failLimit();
  16172. gotMatch = true;
  16173. if (ctx->queryDebugContext())
  16174. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16175. if(limitOnFail)
  16176. {
  16177. assertex(!failingLimit);
  16178. try
  16179. {
  16180. failLimit();
  16181. }
  16182. catch(IException * e)
  16183. {
  16184. failingLimit.setown(e);
  16185. }
  16186. assertex(failingLimit != NULL);
  16187. }
  16188. else
  16189. {
  16190. rightGroup.kill();
  16191. }
  16192. break;
  16193. }
  16194. if(rightGroup.ordinality() > atmostLimit)
  16195. {
  16196. atmostsTriggered++;
  16197. rightGroup.kill();
  16198. break;
  16199. }
  16200. }
  16201. rightGroupIndex = 0;
  16202. return readRightGroup();
  16203. }
  16204. void failLimit()
  16205. {
  16206. helper.onMatchAbortLimitExceeded();
  16207. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16208. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16209. {
  16210. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  16211. }
  16212. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  16213. }
  16214. };
  16215. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  16216. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16217. {
  16218. public:
  16219. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16220. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16221. {
  16222. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  16223. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  16224. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  16225. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  16226. }
  16227. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16228. {
  16229. return new CRoxieServerLookupJoinActivity(this, _probeManager, useFewTable);
  16230. }
  16231. virtual const StatisticsMapping &queryStatsMapping() const
  16232. {
  16233. return joinStatistics;
  16234. }
  16235. protected:
  16236. bool useFewTable;
  16237. };
  16238. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16239. {
  16240. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16241. }
  16242. //=====================================================================================================
  16243. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  16244. {
  16245. private:
  16246. IHThorAllJoinArg &helper;
  16247. bool leftOuterJoin;
  16248. bool rightOuterJoin;
  16249. bool exclude;
  16250. OwnedConstRoxieRow defaultRight;
  16251. OwnedConstRoxieRow defaultLeft;
  16252. Owned<IEngineRowAllocator> defaultRightAllocator;
  16253. Owned<IEngineRowAllocator> defaultLeftAllocator;
  16254. const void *left;
  16255. unsigned countForLeft;
  16256. ConstPointerArray rightset;
  16257. BoolArray matchedRight; // MORE - could use a bitset...
  16258. unsigned keepLimit;
  16259. bool started;
  16260. bool eog;
  16261. bool eos;
  16262. bool matchedLeft;
  16263. bool matchedGroup;
  16264. bool leftIsGrouped;
  16265. bool cloneLeft;
  16266. unsigned rightIndex;
  16267. unsigned joinCounter;
  16268. unsigned rightOrdinality;
  16269. ThorActivityKind activityKind;
  16270. ConstPointerArray filteredRight;
  16271. void createDefaultLeft()
  16272. {
  16273. if (!defaultLeft)
  16274. {
  16275. if (!defaultLeftAllocator)
  16276. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  16277. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  16278. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16279. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16280. }
  16281. }
  16282. void createDefaultRight()
  16283. {
  16284. if (!defaultRight)
  16285. {
  16286. if (!defaultRightAllocator)
  16287. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  16288. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16289. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16290. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16291. }
  16292. }
  16293. public:
  16294. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16295. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  16296. {
  16297. unsigned joinFlags = helper.getJoinFlags();
  16298. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16299. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16300. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16301. keepLimit = (unsigned) -1;
  16302. exclude = (joinFlags & JFexclude) != 0;
  16303. left = NULL;
  16304. started = true;
  16305. eog = false;
  16306. eos = false;
  16307. matchedLeft = false;
  16308. matchedGroup = false;
  16309. activityKind = factory->getKind();
  16310. rightIndex = 0;
  16311. rightOrdinality = 0;
  16312. leftIsGrouped = false;
  16313. countForLeft = 0;
  16314. joinCounter = 0;
  16315. }
  16316. virtual void reset()
  16317. {
  16318. defaultRight.clear();
  16319. defaultLeft.clear();
  16320. ReleaseRoxieRowSet(rightset);
  16321. matchedRight.kill();
  16322. CRoxieServerTwoInputActivity::reset();
  16323. }
  16324. virtual bool needsAllocator() const { return true; }
  16325. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16326. {
  16327. eog = false;
  16328. eos = false;
  16329. matchedLeft = false;
  16330. matchedGroup = false;
  16331. started = false;
  16332. left = NULL;
  16333. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16334. keepLimit = helper.getKeepLimit();
  16335. if(keepLimit==0)
  16336. keepLimit = (unsigned) -1;
  16337. countForLeft = keepLimit;
  16338. joinCounter = 0;
  16339. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  16340. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  16341. createDefaultRight();
  16342. if(rightOuterJoin)
  16343. createDefaultLeft();
  16344. }
  16345. void loadRight()
  16346. {
  16347. const void * next;
  16348. while(true)
  16349. {
  16350. next = input1->nextInGroup();
  16351. if(!next)
  16352. next = input1->nextInGroup();
  16353. if(!next)
  16354. break;
  16355. rightset.append(next);
  16356. matchedRight.append(false);
  16357. }
  16358. rightIndex = 0;
  16359. joinCounter = 0;
  16360. rightOrdinality = rightset.ordinality();
  16361. }
  16362. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16363. {
  16364. if (idx==1)
  16365. input1 = _in;
  16366. else
  16367. {
  16368. if ((helper.getJoinFlags() & JFparallel) != 0)
  16369. {
  16370. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  16371. puller->setInput(0, _in);
  16372. _in = puller;
  16373. }
  16374. CRoxieServerActivity::setInput(idx, _in);
  16375. }
  16376. }
  16377. const void * joinRecords(const void * left, const void * right, unsigned counter)
  16378. {
  16379. // MORE - could share some code with lookup join
  16380. if (cloneLeft)
  16381. {
  16382. LinkRoxieRow(left);
  16383. return left;
  16384. }
  16385. try
  16386. {
  16387. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16388. unsigned outSize = helper.transform(rowBuilder, left, right, counter);
  16389. if (outSize)
  16390. return rowBuilder.finalizeRowClear(outSize);
  16391. else
  16392. return NULL;
  16393. }
  16394. catch (IException *E)
  16395. {
  16396. throw makeWrappedException(E);
  16397. }
  16398. }
  16399. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  16400. {
  16401. try
  16402. {
  16403. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16404. unsigned numRows = rows.ordinality();
  16405. const void * right = numRows ? rows.item(0) : defaultRight.get();
  16406. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  16407. if (outSize)
  16408. return rowBuilder.finalizeRowClear(outSize);
  16409. else
  16410. return NULL;
  16411. }
  16412. catch (IException *E)
  16413. {
  16414. throw makeWrappedException(E);
  16415. }
  16416. }
  16417. virtual const void *nextInGroup()
  16418. {
  16419. ActivityTimer t(totalCycles, timeActivities);
  16420. if(!started)
  16421. {
  16422. started = true;
  16423. left = input->nextInGroup();
  16424. matchedLeft = false;
  16425. countForLeft = keepLimit;
  16426. joinCounter = 0;
  16427. if(left == NULL)
  16428. {
  16429. eos = true;
  16430. return NULL;
  16431. }
  16432. loadRight();
  16433. }
  16434. const void * ret;
  16435. const void * right;
  16436. if(eos)
  16437. return NULL;
  16438. while(true)
  16439. {
  16440. ret = NULL;
  16441. if((rightIndex == rightOrdinality) || (countForLeft==0))
  16442. {
  16443. if(leftOuterJoin && left && !matchedLeft)
  16444. {
  16445. switch(activityKind)
  16446. {
  16447. case TAKalljoin:
  16448. ret = joinRecords(left, defaultRight, 0);
  16449. break;
  16450. case TAKalldenormalize:
  16451. ret = left;
  16452. left = NULL;
  16453. break;
  16454. case TAKalldenormalizegroup:
  16455. filteredRight.kill();
  16456. ret = denormalizeRecords(left, filteredRight);
  16457. break;
  16458. default:
  16459. throwUnexpected();
  16460. }
  16461. }
  16462. rightIndex = 0;
  16463. joinCounter = 0;
  16464. ReleaseRoxieRow(left);
  16465. left = NULL;
  16466. if(ret)
  16467. {
  16468. matchedGroup = true;
  16469. processed++;
  16470. return ret;
  16471. }
  16472. }
  16473. if(!left)
  16474. {
  16475. left = input->nextInGroup();
  16476. matchedLeft = false;
  16477. countForLeft = keepLimit;
  16478. joinCounter = 0;
  16479. }
  16480. if(!left)
  16481. {
  16482. if(eog)
  16483. {
  16484. eos = true;
  16485. matchedGroup = false;
  16486. return NULL;
  16487. }
  16488. eog = true;
  16489. if (matchedGroup && leftIsGrouped)
  16490. {
  16491. matchedGroup = false;
  16492. return NULL;
  16493. }
  16494. matchedGroup = false;
  16495. continue;
  16496. }
  16497. eog = false;
  16498. switch(activityKind)
  16499. {
  16500. case TAKalljoin:
  16501. while(rightIndex < rightOrdinality)
  16502. {
  16503. right = rightset.item(rightIndex);
  16504. if(helper.match(left, right))
  16505. {
  16506. matchedLeft = true;
  16507. matchedRight.replace(true, rightIndex);
  16508. if(!exclude)
  16509. ret = joinRecords(left, right, ++joinCounter);
  16510. }
  16511. rightIndex++;
  16512. if(ret)
  16513. {
  16514. countForLeft--;
  16515. matchedGroup = true;
  16516. processed++;
  16517. return ret;
  16518. }
  16519. }
  16520. break;
  16521. case TAKalldenormalize:
  16522. {
  16523. OwnedConstRoxieRow newLeft;
  16524. newLeft.set(left);
  16525. unsigned rowSize = 0;
  16526. unsigned leftCount = 0;
  16527. while((rightIndex < rightOrdinality) && countForLeft)
  16528. {
  16529. right = rightset.item(rightIndex);
  16530. if(helper.match(left, right))
  16531. {
  16532. matchedLeft = true;
  16533. matchedRight.replace(true, rightIndex);
  16534. if(!exclude)
  16535. {
  16536. try
  16537. {
  16538. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16539. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  16540. if(thisSize)
  16541. {
  16542. rowSize = thisSize;
  16543. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  16544. --countForLeft;
  16545. }
  16546. }
  16547. catch (IException *e)
  16548. {
  16549. throw makeWrappedException(e);
  16550. }
  16551. }
  16552. }
  16553. rightIndex++;
  16554. }
  16555. if(rowSize)
  16556. {
  16557. processed++;
  16558. return newLeft.getClear();
  16559. }
  16560. }
  16561. break;
  16562. case TAKalldenormalizegroup:
  16563. filteredRight.kill();
  16564. while((rightIndex < rightOrdinality) && countForLeft)
  16565. {
  16566. right = rightset.item(rightIndex);
  16567. if(helper.match(left, right))
  16568. {
  16569. matchedLeft = true;
  16570. matchedRight.replace(true, rightIndex);
  16571. filteredRight.append(right);
  16572. --countForLeft;
  16573. }
  16574. ++rightIndex;
  16575. }
  16576. if(!exclude && filteredRight.ordinality())
  16577. {
  16578. ret = denormalizeRecords(left, filteredRight);
  16579. filteredRight.kill();
  16580. if(ret)
  16581. {
  16582. processed++;
  16583. return ret;
  16584. }
  16585. }
  16586. break;
  16587. default:
  16588. throwUnexpected();
  16589. }
  16590. }
  16591. }
  16592. };
  16593. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16594. {
  16595. public:
  16596. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16597. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16598. {
  16599. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16600. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16601. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16602. }
  16603. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16604. {
  16605. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16606. }
  16607. virtual const StatisticsMapping &queryStatsMapping() const
  16608. {
  16609. return joinStatistics;
  16610. }
  16611. };
  16612. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16613. {
  16614. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16615. }
  16616. //=====================================================================================================
  16617. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16618. {
  16619. unsigned limit;
  16620. bool hasBest;
  16621. bool eoi;
  16622. const void **sorted;
  16623. unsigned sortedCount;
  16624. unsigned curIndex;
  16625. IHThorTopNArg &helper;
  16626. ICompare &compare;
  16627. public:
  16628. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16629. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16630. {
  16631. sorted = NULL;
  16632. sortedCount = 0;
  16633. curIndex = 0;
  16634. limit = 0;
  16635. eoi = false;
  16636. hasBest = false;
  16637. }
  16638. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16639. {
  16640. assertex(sorted == NULL);
  16641. sortedCount = 0;
  16642. curIndex = 0;
  16643. eoi = false;
  16644. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16645. limit = (unsigned) helper.getLimit();
  16646. hasBest = helper.hasBest();
  16647. lateStart(parentExtractSize, parentExtract, limit > 0);
  16648. // MORE - should we use an expanding array instead?
  16649. if (limit > 0)
  16650. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16651. }
  16652. virtual void reset()
  16653. {
  16654. if (sorted)
  16655. {
  16656. while(curIndex < sortedCount)
  16657. ReleaseRoxieRow(sorted[curIndex++]);
  16658. ReleaseRoxieRow(sorted);
  16659. }
  16660. sorted = NULL;
  16661. CRoxieServerLateStartActivity::reset();
  16662. }
  16663. bool abortEarly()
  16664. {
  16665. if (hasBest && (sortedCount == limit))
  16666. {
  16667. int compare = helper.compareBest(sorted[sortedCount-1]);
  16668. if (compare == 0)
  16669. {
  16670. if (meta.isGrouped())
  16671. {
  16672. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16673. const void * next;
  16674. while ((next = input->nextInGroup()) != NULL)
  16675. ReleaseRoxieRow(next);
  16676. }
  16677. else
  16678. eoi = true;
  16679. return true;
  16680. }
  16681. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16682. if (compare < 0)
  16683. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16684. }
  16685. return false;
  16686. }
  16687. void getSorted()
  16688. {
  16689. curIndex = 0;
  16690. sortedCount = 0;
  16691. if(eoi)
  16692. return;
  16693. const void * next;
  16694. while ((next = input->nextInGroup()) != NULL)
  16695. {
  16696. if (sortedCount < limit)
  16697. {
  16698. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16699. sortedCount++;
  16700. if(abortEarly())
  16701. return;
  16702. }
  16703. else
  16704. {
  16705. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16706. {
  16707. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16708. ReleaseRoxieRow(sorted[sortedCount]);
  16709. if(abortEarly())
  16710. return;
  16711. }
  16712. else
  16713. {
  16714. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16715. }
  16716. }
  16717. }
  16718. }
  16719. virtual const void * nextInGroup()
  16720. {
  16721. ActivityTimer t(totalCycles, timeActivities);
  16722. if (eof)
  16723. return NULL;
  16724. if (curIndex >= sortedCount)
  16725. {
  16726. bool eog = sortedCount != 0;
  16727. getSorted();
  16728. if(sortedCount == 0)
  16729. {
  16730. eof = true;
  16731. return NULL;
  16732. }
  16733. if (eog)
  16734. return NULL;
  16735. }
  16736. processed++;
  16737. return sorted[curIndex++];
  16738. }
  16739. };
  16740. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16741. {
  16742. public:
  16743. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16744. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16745. {
  16746. }
  16747. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16748. {
  16749. return new CRoxieServerTopNActivity(this, _probeManager);
  16750. }
  16751. };
  16752. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16753. {
  16754. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16755. }
  16756. //=================================================================================
  16757. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16758. {
  16759. protected:
  16760. unsigned __int64 rowLimit;
  16761. IHThorLimitArg &helper;
  16762. public:
  16763. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16764. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16765. {
  16766. rowLimit = 0;
  16767. }
  16768. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16769. {
  16770. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16771. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16772. }
  16773. virtual const void *nextInGroup()
  16774. {
  16775. ActivityTimer t(totalCycles, timeActivities);
  16776. const void * ret = input->nextInGroup();
  16777. if (ret)
  16778. {
  16779. processed++;
  16780. if (processed > rowLimit)
  16781. {
  16782. ReleaseRoxieRow(ret);
  16783. if (traceLevel > 4)
  16784. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16785. helper.onLimitExceeded();
  16786. }
  16787. }
  16788. return ret;
  16789. }
  16790. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16791. {
  16792. ActivityTimer t(totalCycles, timeActivities);
  16793. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16794. if (ret)
  16795. {
  16796. if (wasCompleteMatch)
  16797. processed++;
  16798. if (processed > rowLimit)
  16799. {
  16800. ReleaseRoxieRow(ret);
  16801. if (traceLevel > 4)
  16802. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16803. helper.onLimitExceeded();
  16804. }
  16805. }
  16806. return ret;
  16807. }
  16808. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16809. {
  16810. return input->gatherConjunctions(collector);
  16811. }
  16812. virtual void resetEOF()
  16813. {
  16814. //Do not reset the rowLimit
  16815. input->resetEOF();
  16816. }
  16817. IInputSteppingMeta * querySteppingMeta()
  16818. {
  16819. return input->querySteppingMeta();
  16820. }
  16821. };
  16822. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16823. {
  16824. public:
  16825. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16826. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16827. {
  16828. }
  16829. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16830. {
  16831. return new CRoxieServerLimitActivity(this, _probeManager);
  16832. }
  16833. };
  16834. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16835. {
  16836. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16837. }
  16838. //=====================================================================================================
  16839. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16840. {
  16841. ConstPointerArray buff;
  16842. bool started;
  16843. unsigned index;
  16844. IHThorLimitTransformExtra * transformExtra;
  16845. public:
  16846. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16847. : CRoxieServerLimitActivity(_factory, _probeManager)
  16848. {
  16849. transformExtra = NULL;
  16850. started = false;
  16851. index = 0;
  16852. if (_onFail)
  16853. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16854. }
  16855. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16856. {
  16857. started = false;
  16858. index = 0;
  16859. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16860. }
  16861. virtual void reset()
  16862. {
  16863. while (buff.isItem(index))
  16864. ReleaseRoxieRow(buff.item(index++));
  16865. buff.kill();
  16866. started = false;
  16867. CRoxieServerLimitActivity::reset();
  16868. }
  16869. virtual const void *nextInGroup()
  16870. {
  16871. ActivityTimer t(totalCycles, timeActivities);
  16872. if (!started)
  16873. pullInput();
  16874. if (buff.isItem(index))
  16875. {
  16876. const void * next = buff.item(index++);
  16877. if(next)
  16878. processed++;
  16879. return next;
  16880. }
  16881. return NULL;
  16882. }
  16883. protected:
  16884. void pullInput()
  16885. {
  16886. unsigned count = 0;
  16887. loop
  16888. {
  16889. const void * next = input->nextInGroup();
  16890. if (next == NULL)
  16891. {
  16892. next = input->nextInGroup();
  16893. if(next == NULL)
  16894. break;
  16895. buff.append(NULL);
  16896. }
  16897. count++;
  16898. if (count > rowLimit)
  16899. {
  16900. ReleaseRoxieRow(next);
  16901. ReleaseRoxieRowSet(buff);
  16902. if (ctx->queryDebugContext())
  16903. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16904. if (transformExtra)
  16905. {
  16906. createRowAllocator();
  16907. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16908. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16909. if (outSize)
  16910. buff.append(rowBuilder.finalizeRowClear(outSize));
  16911. }
  16912. break;
  16913. }
  16914. buff.append(next);
  16915. }
  16916. started = true;
  16917. }
  16918. };
  16919. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16920. {
  16921. public:
  16922. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16923. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16924. {
  16925. }
  16926. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16927. {
  16928. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16929. }
  16930. };
  16931. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16932. {
  16933. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16934. }
  16935. //=================================================================================
  16936. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16937. {
  16938. IHThorCatchArg &helper;
  16939. public:
  16940. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16941. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16942. {
  16943. }
  16944. virtual const void *nextInGroup()
  16945. {
  16946. ActivityTimer t(totalCycles, timeActivities);
  16947. try
  16948. {
  16949. const void *ret = input->nextInGroup();
  16950. if (ret)
  16951. processed++;
  16952. return ret;
  16953. }
  16954. catch (IException *E)
  16955. {
  16956. E->Release();
  16957. helper.onExceptionCaught();
  16958. }
  16959. catch (...)
  16960. {
  16961. helper.onExceptionCaught();
  16962. }
  16963. throwUnexpected(); // onExceptionCaught should have thrown something
  16964. }
  16965. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16966. {
  16967. try
  16968. {
  16969. ActivityTimer t(totalCycles, timeActivities);
  16970. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16971. if (ret && wasCompleteMatch)
  16972. processed++;
  16973. return ret;
  16974. }
  16975. catch (IException *E)
  16976. {
  16977. E->Release();
  16978. helper.onExceptionCaught();
  16979. }
  16980. catch (...)
  16981. {
  16982. helper.onExceptionCaught();
  16983. }
  16984. throwUnexpected(); // onExceptionCaught should have thrown something
  16985. }
  16986. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16987. {
  16988. return input->gatherConjunctions(collector);
  16989. }
  16990. virtual void resetEOF()
  16991. {
  16992. input->resetEOF(); // MORE - why not in base class?
  16993. }
  16994. IInputSteppingMeta * querySteppingMeta()
  16995. {
  16996. return input->querySteppingMeta();
  16997. }
  16998. };
  16999. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  17000. {
  17001. ConstPointerArray buff;
  17002. bool started;
  17003. unsigned index;
  17004. IHThorCatchArg &helper;
  17005. bool createRow;
  17006. public:
  17007. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  17008. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  17009. {
  17010. started = false;
  17011. index = 0;
  17012. }
  17013. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17014. {
  17015. started = false;
  17016. index = 0;
  17017. try
  17018. {
  17019. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17020. }
  17021. catch (IException *E)
  17022. {
  17023. onException(E);
  17024. started = true;
  17025. }
  17026. catch (...)
  17027. {
  17028. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17029. started = true;
  17030. }
  17031. }
  17032. virtual void reset()
  17033. {
  17034. while (buff.isItem(index))
  17035. ReleaseRoxieRow(buff.item(index++));
  17036. buff.kill();
  17037. started = false;
  17038. CRoxieServerActivity::reset();
  17039. }
  17040. virtual const void *nextInGroup()
  17041. {
  17042. ActivityTimer t(totalCycles, timeActivities);
  17043. if (!started)
  17044. pullInput();
  17045. if (buff.isItem(index))
  17046. {
  17047. const void * next = buff.item(index++);
  17048. if(next)
  17049. processed++;
  17050. return next;
  17051. }
  17052. return NULL;
  17053. }
  17054. protected:
  17055. void onException(IException *E)
  17056. {
  17057. input->stop(true);
  17058. ReleaseRoxieRowSet(buff);
  17059. if (createRow)
  17060. {
  17061. createRowAllocator();
  17062. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17063. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  17064. if (outSize)
  17065. buff.append(rowBuilder.finalizeRowClear(outSize));
  17066. }
  17067. E->Release();
  17068. }
  17069. void pullInput()
  17070. {
  17071. try
  17072. {
  17073. bool EOGseen = false;
  17074. loop
  17075. {
  17076. const void * next = input->nextInGroup();
  17077. buff.append(next);
  17078. if (next == NULL)
  17079. {
  17080. if (EOGseen)
  17081. break;
  17082. EOGseen = true;
  17083. }
  17084. else
  17085. EOGseen = false;
  17086. }
  17087. }
  17088. catch (IException *E)
  17089. {
  17090. onException(E);
  17091. }
  17092. catch (...)
  17093. {
  17094. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  17095. }
  17096. started = true;
  17097. }
  17098. };
  17099. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  17100. {
  17101. public:
  17102. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17103. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17104. {
  17105. }
  17106. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17107. {
  17108. switch (kind)
  17109. {
  17110. case TAKcatch:
  17111. return new CRoxieServerCatchActivity(this, _probeManager);
  17112. case TAKskipcatch:
  17113. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  17114. case TAKcreaterowcatch:
  17115. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  17116. default:
  17117. throwUnexpected();
  17118. }
  17119. }
  17120. };
  17121. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17122. {
  17123. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17124. }
  17125. //=================================================================================
  17126. class CRoxieServerCaseActivity : public CRoxieServerActivity
  17127. {
  17128. IHThorCaseArg &helper;
  17129. IRoxieInput **inputs;
  17130. unsigned cond;
  17131. bool unusedStopped;
  17132. IRoxieInput *in;
  17133. unsigned numInputs;
  17134. public:
  17135. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  17136. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  17137. {
  17138. unusedStopped = false;
  17139. cond = 0;
  17140. inputs = new IRoxieInput*[numInputs];
  17141. for (unsigned i = 0; i < numInputs; i++)
  17142. inputs[i] = NULL;
  17143. in = NULL;
  17144. }
  17145. ~CRoxieServerCaseActivity()
  17146. {
  17147. delete [] inputs;
  17148. }
  17149. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17150. {
  17151. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17152. cond = helper.getBranch();
  17153. //CHOOSE defaults to the last argument if out of range.
  17154. if (cond >= numInputs)
  17155. cond = numInputs - 1;
  17156. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  17157. for (unsigned idx = 0; idx < numInputs; idx++)
  17158. {
  17159. if (idx!=cond)
  17160. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17161. }
  17162. in = inputs[cond];
  17163. unusedStopped = true;
  17164. }
  17165. virtual void stop(bool aborting)
  17166. {
  17167. for (unsigned idx = 0; idx < numInputs; idx++)
  17168. {
  17169. if (idx==cond || !unusedStopped)
  17170. inputs[idx]->stop(aborting);
  17171. }
  17172. CRoxieServerActivity::stop(aborting);
  17173. }
  17174. virtual void reset()
  17175. {
  17176. for (unsigned idx = 0; idx < numInputs; idx++)
  17177. {
  17178. inputs[idx]->reset();
  17179. }
  17180. unusedStopped = false;
  17181. in = NULL;
  17182. CRoxieServerActivity::reset();
  17183. }
  17184. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17185. {
  17186. assertex(idx < numInputs);
  17187. inputs[idx] = _in;
  17188. }
  17189. virtual const void *nextInGroup()
  17190. {
  17191. ActivityTimer t(totalCycles, timeActivities);
  17192. if (in)
  17193. {
  17194. const void *ret = in->nextInGroup();
  17195. if (ret)
  17196. processed++;
  17197. return ret;
  17198. }
  17199. return NULL;
  17200. }
  17201. };
  17202. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  17203. {
  17204. bool graphInvariant;
  17205. public:
  17206. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17207. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17208. {
  17209. graphInvariant = _graphInvariant;
  17210. }
  17211. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17212. {
  17213. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  17214. }
  17215. virtual bool isGraphInvariant() const
  17216. {
  17217. return graphInvariant;
  17218. }
  17219. };
  17220. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17221. {
  17222. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17223. }
  17224. //=================================================================================
  17225. class CRoxieServerIfActivity : public CRoxieServerActivity
  17226. {
  17227. IHThorIfArg &helper;
  17228. IRoxieInput *inputTrue;
  17229. IRoxieInput *inputFalse;
  17230. bool cond;
  17231. bool unusedStopped;
  17232. public:
  17233. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17234. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17235. {
  17236. inputFalse = NULL;
  17237. inputTrue = NULL;
  17238. unusedStopped = false;
  17239. cond = false;
  17240. }
  17241. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17242. {
  17243. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17244. cond = helper.getCondition();
  17245. if (cond)
  17246. {
  17247. inputTrue->start(parentExtractSize, parentExtract, paused);
  17248. if (inputFalse)
  17249. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  17250. }
  17251. else
  17252. {
  17253. if (inputFalse)
  17254. inputFalse->start(parentExtractSize, parentExtract, paused);
  17255. inputTrue->stop(false);
  17256. }
  17257. unusedStopped = true;
  17258. }
  17259. virtual void stop(bool aborting)
  17260. {
  17261. if (!unusedStopped || cond)
  17262. inputTrue->stop(aborting);
  17263. if (inputFalse && (!unusedStopped || !cond))
  17264. inputFalse->stop(aborting);
  17265. CRoxieServerActivity::stop(aborting);
  17266. }
  17267. virtual unsigned __int64 queryLocalCycles() const
  17268. {
  17269. __int64 localCycles = totalCycles.totalCycles;
  17270. localCycles -= inputTrue->queryTotalCycles();
  17271. if (inputFalse)
  17272. localCycles -= inputFalse->queryTotalCycles();
  17273. if (localCycles < 0)
  17274. localCycles = 0;
  17275. return localCycles;
  17276. }
  17277. virtual IRoxieInput *queryInput(unsigned idx) const
  17278. {
  17279. switch (idx)
  17280. {
  17281. case 0:
  17282. return inputTrue;
  17283. case 1:
  17284. return inputFalse;
  17285. default:
  17286. return NULL;
  17287. }
  17288. }
  17289. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  17290. {
  17291. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17292. if (in)
  17293. return in->queryIndexReadActivity();
  17294. return NULL;
  17295. }
  17296. virtual void reset()
  17297. {
  17298. CRoxieServerActivity::reset();
  17299. inputTrue->reset();
  17300. if (inputFalse)
  17301. inputFalse->reset();
  17302. unusedStopped = false;
  17303. }
  17304. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17305. {
  17306. if (idx==1)
  17307. inputFalse = _in;
  17308. else
  17309. {
  17310. assertex(!idx);
  17311. inputTrue = _in;
  17312. }
  17313. }
  17314. virtual const void *nextInGroup()
  17315. {
  17316. ActivityTimer t(totalCycles, timeActivities);
  17317. IRoxieInput *in = cond ? inputTrue : inputFalse;
  17318. if (in)
  17319. {
  17320. const void * ret;
  17321. if ((ret = in->nextInGroup()) != NULL)
  17322. processed++;
  17323. return ret;
  17324. }
  17325. return NULL;
  17326. }
  17327. };
  17328. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  17329. {
  17330. unsigned input2;
  17331. unsigned input2idx;
  17332. bool graphInvariant;
  17333. public:
  17334. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17335. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17336. {
  17337. graphInvariant = _graphInvariant;
  17338. input2 = (unsigned)-1;
  17339. input2idx = (unsigned)-1;
  17340. }
  17341. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17342. {
  17343. return new CRoxieServerIfActivity(this, _probeManager);
  17344. }
  17345. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  17346. {
  17347. if (idx==1)
  17348. {
  17349. input2 = source;
  17350. input2idx = sourceidx;
  17351. }
  17352. else
  17353. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  17354. }
  17355. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  17356. {
  17357. switch (idx)
  17358. {
  17359. case 1:
  17360. sourceidx = input2idx;
  17361. return input2;
  17362. case 0:
  17363. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  17364. default:
  17365. return (unsigned) -1;
  17366. }
  17367. }
  17368. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  17369. virtual bool isGraphInvariant() const
  17370. {
  17371. return graphInvariant;
  17372. }
  17373. };
  17374. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  17375. {
  17376. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  17377. }
  17378. //=================================================================================
  17379. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  17380. {
  17381. CriticalSection ecrit;
  17382. Owned<IException> exception;
  17383. bool executed;
  17384. public:
  17385. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17386. : CRoxieServerActivity(_factory, _probeManager)
  17387. {
  17388. executed = false;
  17389. }
  17390. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  17391. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  17392. {
  17393. CriticalBlock b(ecrit);
  17394. if (exception)
  17395. throw(exception.getLink());
  17396. if (!executed)
  17397. {
  17398. try
  17399. {
  17400. executed = true;
  17401. start(parentExtractSize, parentExtract, false);
  17402. doExecuteAction(parentExtractSize, parentExtract);
  17403. stop(false);
  17404. }
  17405. catch (IException * E)
  17406. {
  17407. ctx->notifyAbort(E);
  17408. stop(true);
  17409. exception.set(E);
  17410. throw;
  17411. }
  17412. }
  17413. }
  17414. virtual void reset()
  17415. {
  17416. executed = false;
  17417. exception.clear();
  17418. CRoxieServerActivity::reset();
  17419. }
  17420. virtual const void *nextInGroup()
  17421. {
  17422. throwUnexpected(); // I am nobody's input
  17423. }
  17424. virtual IRoxieInput *queryInput(unsigned idx) const
  17425. {
  17426. throwUnexpected(); // I am nobody's input
  17427. }
  17428. };
  17429. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  17430. {
  17431. IHThorIfArg &helper;
  17432. public:
  17433. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17434. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  17435. {
  17436. }
  17437. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17438. {
  17439. bool cond;
  17440. {
  17441. ActivityTimer t(totalCycles, timeActivities);
  17442. cond = helper.getCondition();
  17443. }
  17444. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  17445. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  17446. }
  17447. };
  17448. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  17449. {
  17450. bool isRoot;
  17451. public:
  17452. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17453. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17454. {
  17455. }
  17456. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17457. {
  17458. return new CRoxieServerIfActionActivity(this, _probeManager);
  17459. }
  17460. virtual bool isSink() const
  17461. {
  17462. return isRoot;
  17463. }
  17464. };
  17465. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17466. {
  17467. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17468. }
  17469. //=================================================================================
  17470. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  17471. {
  17472. public:
  17473. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17474. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17475. {
  17476. }
  17477. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17478. {
  17479. #ifdef PARALLEL_EXECUTE
  17480. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  17481. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  17482. #else
  17483. ForEachItemIn(idx, dependencies)
  17484. {
  17485. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  17486. }
  17487. #endif
  17488. }
  17489. };
  17490. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  17491. {
  17492. bool isRoot;
  17493. public:
  17494. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17495. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17496. {
  17497. assertex(!isRoot); // non-internal should be expanded out..
  17498. }
  17499. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17500. {
  17501. return new CRoxieServerParallelActionActivity(this, _probeManager);
  17502. }
  17503. virtual bool isSink() const
  17504. {
  17505. return isRoot;
  17506. }
  17507. };
  17508. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17509. {
  17510. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17511. }
  17512. //=================================================================================
  17513. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  17514. {
  17515. IHThorSequentialArg &helper;
  17516. public:
  17517. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17518. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  17519. {
  17520. }
  17521. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17522. {
  17523. unsigned numBranches = helper.numBranches();
  17524. for (unsigned branch=1; branch <= numBranches; branch++)
  17525. executeDependencies(parentExtractSize, parentExtract, branch);
  17526. }
  17527. };
  17528. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  17529. {
  17530. bool isRoot;
  17531. public:
  17532. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17533. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17534. {
  17535. }
  17536. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17537. {
  17538. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  17539. }
  17540. virtual bool isSink() const
  17541. {
  17542. return isRoot;
  17543. }
  17544. };
  17545. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17546. {
  17547. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17548. }
  17549. //=================================================================================
  17550. class CRoxieServerWhenActivity : public CRoxieServerActivity
  17551. {
  17552. public:
  17553. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17554. : CRoxieServerActivity(_factory, _probeManager)
  17555. {
  17556. savedExtractSize = 0;
  17557. savedExtract = NULL;
  17558. }
  17559. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17560. {
  17561. savedExtractSize = parentExtractSize;
  17562. savedExtract = parentExtract;
  17563. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17564. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17565. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17566. }
  17567. virtual void stop(bool aborting)
  17568. {
  17569. if (state == STATEreset)
  17570. {
  17571. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  17572. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  17573. }
  17574. else if (state != STATEstopped)
  17575. {
  17576. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  17577. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId); // These ones do
  17578. }
  17579. CRoxieServerActivity::stop(aborting);
  17580. }
  17581. virtual const void *nextInGroup()
  17582. {
  17583. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  17584. return input->nextInGroup();
  17585. }
  17586. protected:
  17587. unsigned savedExtractSize;
  17588. const byte *savedExtract;
  17589. };
  17590. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17591. {
  17592. public:
  17593. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17594. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17595. {
  17596. }
  17597. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17598. {
  17599. return new CRoxieServerWhenActivity(this, _probeManager);
  17600. }
  17601. };
  17602. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17603. {
  17604. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17605. }
  17606. //=================================================================================
  17607. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17608. {
  17609. public:
  17610. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17611. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17612. {
  17613. savedExtractSize = 0;
  17614. savedExtract = NULL;
  17615. }
  17616. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17617. {
  17618. savedExtractSize = parentExtractSize;
  17619. savedExtract = parentExtract;
  17620. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17621. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  17622. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17623. }
  17624. virtual void stop(bool aborting)
  17625. {
  17626. if (state != STATEstopped)
  17627. {
  17628. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  17629. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17630. }
  17631. CRoxieServerActionBaseActivity::stop(aborting);
  17632. }
  17633. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17634. {
  17635. executeDependencies(parentExtractSize, parentExtract, 1);
  17636. }
  17637. protected:
  17638. unsigned savedExtractSize;
  17639. const byte *savedExtract;
  17640. };
  17641. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17642. {
  17643. public:
  17644. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17645. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17646. {
  17647. }
  17648. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17649. {
  17650. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17651. }
  17652. virtual bool isSink() const
  17653. {
  17654. return isRoot;
  17655. }
  17656. private:
  17657. bool isRoot;
  17658. };
  17659. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17660. {
  17661. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17662. }
  17663. //=================================================================================
  17664. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17665. {
  17666. IHThorParseArg &helper;
  17667. INlpParser * parser;
  17668. INlpResultIterator * rowIter;
  17669. const void * in;
  17670. char * curSearchText;
  17671. INlpParseAlgorithm * algorithm;
  17672. size32_t curSearchTextLen;
  17673. bool anyThisGroup;
  17674. bool processRecord(const void * inRec)
  17675. {
  17676. if (helper.searchTextNeedsFree())
  17677. rtlFree(curSearchText);
  17678. curSearchTextLen = 0;
  17679. curSearchText = NULL;
  17680. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17681. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17682. }
  17683. public:
  17684. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17685. : CRoxieServerActivity(_factory, _probeManager),
  17686. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17687. {
  17688. parser = NULL;
  17689. rowIter = NULL;
  17690. in = NULL;
  17691. curSearchText = NULL;
  17692. anyThisGroup = false;
  17693. curSearchTextLen = 0;
  17694. }
  17695. ~CRoxieServerParseActivity()
  17696. {
  17697. ::Release(parser);
  17698. }
  17699. virtual bool needsAllocator() const { return true; }
  17700. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17701. {
  17702. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17703. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17704. rowIter = parser->queryResultIter();
  17705. }
  17706. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17707. {
  17708. anyThisGroup = false;
  17709. curSearchTextLen = 0;
  17710. curSearchText = NULL;
  17711. in = NULL;
  17712. parser->reset();
  17713. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17714. }
  17715. virtual void reset()
  17716. {
  17717. if (helper.searchTextNeedsFree())
  17718. rtlFree(curSearchText);
  17719. curSearchText = NULL;
  17720. ReleaseClearRoxieRow(in);
  17721. CRoxieServerActivity::reset();
  17722. }
  17723. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17724. {
  17725. try
  17726. {
  17727. return helper.transform(self, curRecord, results, walker);
  17728. }
  17729. catch (IException *E)
  17730. {
  17731. throw makeWrappedException(E);
  17732. }
  17733. }
  17734. virtual const void * nextInGroup()
  17735. {
  17736. ActivityTimer t(totalCycles, timeActivities);
  17737. loop
  17738. {
  17739. if (rowIter->isValid())
  17740. {
  17741. anyThisGroup = true;
  17742. OwnedConstRoxieRow out = rowIter->getRow();
  17743. rowIter->next();
  17744. processed++;
  17745. return out.getClear();
  17746. }
  17747. ReleaseClearRoxieRow(in);
  17748. in = input->nextInGroup();
  17749. if (!in)
  17750. {
  17751. if (anyThisGroup)
  17752. {
  17753. anyThisGroup = false;
  17754. return NULL;
  17755. }
  17756. in = input->nextInGroup();
  17757. if (!in)
  17758. return NULL;
  17759. }
  17760. processRecord(in);
  17761. rowIter->first();
  17762. }
  17763. }
  17764. };
  17765. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17766. {
  17767. Owned<INlpParseAlgorithm> algorithm;
  17768. Owned<IHThorParseArg> helper;
  17769. public:
  17770. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17771. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17772. {
  17773. helper.setown((IHThorParseArg *) helperFactory());
  17774. algorithm.setown(createThorParser(rc, *helper));
  17775. }
  17776. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17777. {
  17778. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17779. }
  17780. };
  17781. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17782. {
  17783. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17784. }
  17785. //=====================================================================================================
  17786. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17787. {
  17788. IHThorWorkUnitWriteArg &helper;
  17789. bool isReread;
  17790. bool grouped;
  17791. IRoxieServerContext *serverContext;
  17792. public:
  17793. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  17794. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17795. {
  17796. grouped = (helper.getFlags() & POFgrouped) != 0;
  17797. serverContext = NULL;
  17798. }
  17799. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17800. {
  17801. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17802. serverContext = ctx->queryServerContext();
  17803. if (!serverContext)
  17804. {
  17805. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17806. }
  17807. }
  17808. virtual bool needsAllocator() const { return true; }
  17809. virtual void onExecute()
  17810. {
  17811. int sequence = helper.getSequence();
  17812. const char *storedName = helper.queryName();
  17813. if (!storedName)
  17814. storedName = "Dataset";
  17815. MemoryBuffer result;
  17816. FlushingStringBuffer *response = NULL;
  17817. bool saveInContext = (int) sequence < 0 || isReread;
  17818. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17819. meta.set(input->queryOutputMeta());
  17820. Owned<IOutputRowSerializer> rowSerializer;
  17821. Owned<IXmlWriter> writer;
  17822. if ((int) sequence >= 0)
  17823. {
  17824. response = serverContext->queryResult(sequence);
  17825. if (response)
  17826. {
  17827. const IProperties *xmlns = serverContext->queryXmlns(sequence);
  17828. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0, xmlns);
  17829. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17830. {
  17831. unsigned int writeFlags = serverContext->getXmlFlags();
  17832. if (response->mlFmt==MarkupFmt_JSON)
  17833. writeFlags |= XWFnoindent;
  17834. writer.setown(createIXmlWriterExt(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17835. writer->outputBeginArray("Row");
  17836. }
  17837. }
  17838. }
  17839. size32_t outputLimitBytes = 0;
  17840. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  17841. if (workunit)
  17842. {
  17843. size32_t outputLimit;
  17844. if (helper.getFlags() & POFmaxsize)
  17845. outputLimit = helper.getMaxSize();
  17846. else
  17847. {
  17848. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  17849. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  17850. }
  17851. if (outputLimit>defaultDaliResultOutputMax)
  17852. throw MakeStringException(0, "Dali result outputs are restricted to a maximum of %d MB, the current limit is %d MB. A huge dali result usually indicates the ECL needs altering.", defaultDaliResultOutputMax, defaultDaliResultLimit);
  17853. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  17854. outputLimitBytes = outputLimit * 0x100000;
  17855. }
  17856. if (workunit != NULL || (response && response->isRaw))
  17857. {
  17858. createRowAllocator();
  17859. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17860. }
  17861. __int64 initialProcessed = processed;
  17862. RtlLinkedDatasetBuilder builder(rowAllocator);
  17863. loop
  17864. {
  17865. const void *row = input->nextInGroup();
  17866. if (saveInContext)
  17867. {
  17868. if (row || grouped)
  17869. builder.append(row);
  17870. }
  17871. if (grouped && (processed != initialProcessed))
  17872. {
  17873. if (workunit)
  17874. result.append(row == NULL);
  17875. if (response)
  17876. {
  17877. if (response->isRaw)
  17878. response->append((char)(row == NULL));
  17879. else
  17880. {
  17881. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17882. }
  17883. }
  17884. }
  17885. if (!row)
  17886. {
  17887. row = input->nextInGroup();
  17888. if (!row)
  17889. break;
  17890. if (saveInContext)
  17891. builder.append(row);
  17892. }
  17893. processed++;
  17894. if (workunit)
  17895. {
  17896. CThorDemoRowSerializer serializerTarget(result);
  17897. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17898. }
  17899. if (response)
  17900. {
  17901. if (response->isRaw)
  17902. {
  17903. // MORE - should be able to serialize straight to the response...
  17904. MemoryBuffer rowbuff;
  17905. CThorDemoRowSerializer serializerTarget(rowbuff);
  17906. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17907. response->append(rowbuff.length(), rowbuff.toByteArray());
  17908. }
  17909. else if (writer)
  17910. {
  17911. writer->outputBeginNested("Row", false);
  17912. helper.serializeXml((byte *) row, *writer);
  17913. writer->outputEndNested("Row");
  17914. }
  17915. else
  17916. {
  17917. SimpleOutputWriter x;
  17918. helper.serializeXml((byte *) row, x);
  17919. x.newline();
  17920. response->append(x.str());
  17921. }
  17922. response->incrementRowCount();
  17923. response->flush(false);
  17924. }
  17925. ReleaseRoxieRow(row);
  17926. if (outputLimitBytes && result.length() > outputLimitBytes)
  17927. {
  17928. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  17929. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  17930. const char *name = helper.queryName();
  17931. if (name)
  17932. errMsg.append("name=").append(name);
  17933. else
  17934. errMsg.append("sequence=").append(helper.getSequence());
  17935. errMsg.append(")");
  17936. throw MakeStringExceptionDirect(0, errMsg.str());
  17937. }
  17938. }
  17939. if (writer)
  17940. writer->outputEndArray("Row");
  17941. if (saveInContext)
  17942. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17943. if (workunit)
  17944. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17945. }
  17946. };
  17947. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17948. {
  17949. bool isReread;
  17950. public:
  17951. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17952. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17953. {
  17954. isReread = usageCount > 0;
  17955. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17956. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17957. }
  17958. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17959. {
  17960. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread, usageCount);
  17961. }
  17962. };
  17963. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17964. {
  17965. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17966. }
  17967. //=====================================================================================================
  17968. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17969. {
  17970. IHThorDictionaryWorkUnitWriteArg &helper;
  17971. IRoxieServerContext *serverContext;
  17972. public:
  17973. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  17974. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17975. {
  17976. serverContext = NULL;
  17977. }
  17978. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17979. {
  17980. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17981. serverContext = ctx->queryServerContext();
  17982. if (!serverContext)
  17983. {
  17984. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17985. }
  17986. }
  17987. virtual bool needsAllocator() const { return true; }
  17988. virtual void onExecute()
  17989. {
  17990. int sequence = helper.getSequence();
  17991. const char *storedName = helper.queryName();
  17992. assertex(storedName && *storedName);
  17993. assertex(sequence < 0);
  17994. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  17995. loop
  17996. {
  17997. const void *row = input->nextInGroup();
  17998. if (!row)
  17999. {
  18000. row = input->nextInGroup();
  18001. if (!row)
  18002. break;
  18003. }
  18004. builder.appendOwn(row);
  18005. processed++;
  18006. }
  18007. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  18008. }
  18009. };
  18010. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  18011. {
  18012. public:
  18013. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18014. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18015. {
  18016. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  18017. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18018. }
  18019. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18020. {
  18021. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager, usageCount);
  18022. }
  18023. };
  18024. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18025. {
  18026. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18027. }
  18028. //=================================================================================
  18029. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  18030. {
  18031. IHThorRemoteResultArg &helper;
  18032. public:
  18033. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  18034. : CRoxieServerInternalSinkActivity(_factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  18035. {
  18036. }
  18037. virtual void onExecute()
  18038. {
  18039. OwnedConstRoxieRow row = input->nextInGroup();
  18040. helper.sendResult(row); // should be only one row or something has gone wrong!
  18041. }
  18042. };
  18043. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  18044. {
  18045. public:
  18046. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18047. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  18048. {
  18049. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  18050. isInternal = (helper->getSequence()==ResultSequenceInternal);
  18051. }
  18052. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18053. {
  18054. return new CRoxieServerRemoteResultActivity(this, _probeManager, usageCount);
  18055. }
  18056. };
  18057. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  18058. {
  18059. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  18060. }
  18061. //=================================================================================
  18062. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  18063. {
  18064. IHThorXmlParseArg &helper;
  18065. Owned<IXMLParse> xmlParser;
  18066. const void * in;
  18067. char * srchStr;
  18068. unsigned numProcessedLastGroup;
  18069. bool srchStrNeedsFree;
  18070. Owned<IColumnProvider> lastMatch;
  18071. public:
  18072. IMPLEMENT_IINTERFACE;
  18073. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18074. : CRoxieServerActivity(_factory, _probeManager),
  18075. helper((IHThorXmlParseArg &)basehelper)
  18076. {
  18077. srchStrNeedsFree = helper.searchTextNeedsFree();
  18078. numProcessedLastGroup = 0;
  18079. srchStr = NULL;
  18080. in = NULL;
  18081. }
  18082. ~CRoxieServerXmlParseActivity()
  18083. {
  18084. }
  18085. virtual bool needsAllocator() const { return true; }
  18086. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18087. {
  18088. numProcessedLastGroup = 0;
  18089. srchStr = NULL;
  18090. in = NULL;
  18091. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18092. }
  18093. virtual void reset()
  18094. {
  18095. if (helper.searchTextNeedsFree())
  18096. rtlFree(srchStr);
  18097. srchStr = NULL;
  18098. ReleaseClearRoxieRow(in);
  18099. xmlParser.clear();
  18100. CRoxieServerActivity::reset();
  18101. }
  18102. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18103. {
  18104. lastMatch.set(&entry);
  18105. }
  18106. virtual const void *nextInGroup()
  18107. {
  18108. ActivityTimer t(totalCycles, timeActivities);
  18109. loop
  18110. {
  18111. if(xmlParser)
  18112. {
  18113. loop
  18114. {
  18115. if(!xmlParser->next())
  18116. {
  18117. if (srchStrNeedsFree)
  18118. {
  18119. rtlFree(srchStr);
  18120. srchStr = NULL;
  18121. }
  18122. xmlParser.clear();
  18123. break;
  18124. }
  18125. if(lastMatch)
  18126. {
  18127. try
  18128. {
  18129. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18130. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  18131. lastMatch.clear();
  18132. if (outSize)
  18133. {
  18134. processed++;
  18135. return rowBuilder.finalizeRowClear(outSize);
  18136. }
  18137. }
  18138. catch (IException *E)
  18139. {
  18140. throw makeWrappedException(E);
  18141. }
  18142. }
  18143. }
  18144. }
  18145. ReleaseClearRoxieRow(in);
  18146. in = input->nextInGroup();
  18147. if(!in)
  18148. {
  18149. if(numProcessedLastGroup == processed)
  18150. in = input->nextInGroup();
  18151. if(!in)
  18152. {
  18153. numProcessedLastGroup = processed;
  18154. return NULL;
  18155. }
  18156. }
  18157. size32_t srchLen;
  18158. helper.getSearchText(srchLen, srchStr, in);
  18159. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  18160. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  18161. }
  18162. }
  18163. };
  18164. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  18165. {
  18166. public:
  18167. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18168. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  18169. {
  18170. }
  18171. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18172. {
  18173. return new CRoxieServerXmlParseActivity(this, _probeManager);
  18174. }
  18175. };
  18176. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  18177. {
  18178. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  18179. }
  18180. //=====================================================================================================
  18181. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  18182. {
  18183. protected:
  18184. IHThorDiskReadBaseArg &helper;
  18185. IHThorCompoundExtra * compoundHelper;
  18186. RemoteActivityId remoteId; // Note we copy it rather than reference
  18187. Owned<CSkippableRemoteResultAdaptor> remote;
  18188. unsigned numParts;
  18189. unsigned __int64 rowLimit;
  18190. unsigned __int64 stopAfter;
  18191. Linked<IInMemoryIndexManager> manager;
  18192. Owned<IInMemoryIndexCursor> cursor;
  18193. Owned<IDirectReader> reader;
  18194. CThorContiguousRowBuffer deserializeSource;
  18195. Owned<ISourceRowPrefetcher> prefetcher;
  18196. bool eof;
  18197. bool isKeyed;
  18198. bool variableFileName;
  18199. bool isOpt;
  18200. bool sorted;
  18201. bool maySkip;
  18202. bool isLocal;
  18203. bool forceRemote;
  18204. CachedOutputMetaData diskSize;
  18205. Owned<const IResolvedFile> varFileInfo;
  18206. Owned<IFileIOArray> varFiles;
  18207. inline bool useRemote()
  18208. {
  18209. return remote != NULL && (forceRemote || numParts > 1);
  18210. }
  18211. public:
  18212. IMPLEMENT_IINTERFACE;
  18213. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18214. : CRoxieServerActivity(_factory, _probeManager),
  18215. helper((IHThorDiskReadBaseArg &)basehelper),
  18216. numParts(_numParts),
  18217. remoteId(_remoteId),
  18218. manager(_manager),
  18219. isLocal(_isLocal),
  18220. sorted(_sorted),
  18221. maySkip(_maySkip),
  18222. deserializeSource(NULL)
  18223. {
  18224. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  18225. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  18226. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  18227. compoundHelper = NULL;
  18228. eof = false;
  18229. rowLimit = (unsigned __int64) -1;
  18230. isKeyed = false;
  18231. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  18232. diskSize.set(helper.queryDiskRecordSize());
  18233. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18234. isOpt = (helper.getFlags() & TDRoptional) != 0;
  18235. }
  18236. virtual const IResolvedFile *queryVarFileInfo() const
  18237. {
  18238. return varFileInfo;
  18239. }
  18240. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18241. {
  18242. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18243. if (remote)
  18244. remote->onCreate(this, this, _ctx, _colocalParent);
  18245. }
  18246. virtual bool needsAllocator() const { return true; }
  18247. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18248. {
  18249. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18250. if (compoundHelper)
  18251. {
  18252. rowLimit = compoundHelper->getRowLimit();
  18253. stopAfter = compoundHelper->getChooseNLimit();
  18254. }
  18255. if (!helper.canMatchAny())
  18256. eof = true;
  18257. else
  18258. {
  18259. if (variableFileName)
  18260. {
  18261. OwnedRoxieString fileName(helper.getFileName());
  18262. varFileInfo.setown(resolveLFN(fileName, isOpt));
  18263. numParts = 0;
  18264. if (varFileInfo)
  18265. numParts = varFileInfo->getNumParts();
  18266. }
  18267. if (!numParts)
  18268. {
  18269. eof = true;
  18270. }
  18271. else if (useRemote())
  18272. {
  18273. remote->onStart(parentExtractSize, parentExtract);
  18274. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  18275. unsigned fileNo = 0;
  18276. // Translation into a message per channel done elsewhere....
  18277. remote->getMem(0, fileNo, 0);
  18278. remote->flush();
  18279. remote->senddone();
  18280. }
  18281. else
  18282. {
  18283. if (variableFileName)
  18284. {
  18285. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  18286. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  18287. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  18288. }
  18289. assertex(manager != NULL);
  18290. helper.createSegmentMonitors(this);
  18291. if (cursor)
  18292. {
  18293. isKeyed = cursor->selectKey();
  18294. cursor->reset();
  18295. }
  18296. if (!isKeyed)
  18297. {
  18298. reader.setown(manager->createReader(0, 0, 1));
  18299. deserializeSource.setStream(reader);
  18300. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  18301. }
  18302. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  18303. }
  18304. }
  18305. }
  18306. virtual void append(IKeySegmentMonitor *segment)
  18307. {
  18308. if (!segment->isWild())
  18309. {
  18310. if (!cursor)
  18311. cursor.setown(manager->createCursor());
  18312. cursor->append(segment);
  18313. }
  18314. }
  18315. virtual unsigned ordinality() const
  18316. {
  18317. return cursor ? cursor->ordinality() : 0;
  18318. }
  18319. virtual IKeySegmentMonitor *item(unsigned idx) const
  18320. {
  18321. return cursor ? cursor->item(idx) : 0;
  18322. }
  18323. virtual void setMergeBarrier(unsigned barrierOffset)
  18324. {
  18325. // no merging so no issue...
  18326. }
  18327. virtual void stop(bool aborting)
  18328. {
  18329. if (useRemote())
  18330. remote->onStop(aborting);
  18331. CRoxieServerActivity::stop(aborting);
  18332. }
  18333. virtual void reset()
  18334. {
  18335. if (useRemote())
  18336. {
  18337. processed = remote->processed;
  18338. remote->processed = 0;
  18339. remote->onReset();
  18340. }
  18341. varFileInfo.clear();
  18342. eof = false;
  18343. if (cursor)
  18344. cursor->reset();
  18345. deserializeSource.clearStream();
  18346. CRoxieServerActivity::reset();
  18347. }
  18348. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18349. {
  18350. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18351. }
  18352. virtual void onLimitExceeded(bool isKeyed)
  18353. {
  18354. if (traceLevel > 4)
  18355. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18356. assertex(compoundHelper);
  18357. if (isKeyed) // MORE does this exist for diskread? should it?
  18358. {
  18359. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  18360. {
  18361. if (ctx->queryDebugContext())
  18362. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18363. throw makeLimitSkipException(true);
  18364. }
  18365. else
  18366. {
  18367. UNIMPLEMENTED;
  18368. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  18369. }
  18370. }
  18371. else
  18372. {
  18373. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  18374. {
  18375. if (ctx->queryDebugContext())
  18376. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18377. throw makeLimitSkipException(false);
  18378. }
  18379. else
  18380. compoundHelper->onLimitExceeded();
  18381. }
  18382. }
  18383. virtual const void * createLimitFailRow(bool isKeyed)
  18384. {
  18385. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18386. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  18387. assertex(limitTransformExtra);
  18388. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18389. if (outSize)
  18390. return rowBuilder.finalizeRowClear(outSize);
  18391. return NULL;
  18392. }
  18393. };
  18394. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  18395. {
  18396. IHThorCompoundReadExtra * readHelper;
  18397. ConstPointerArray readrows;
  18398. bool readAheadDone;
  18399. unsigned readIndex;
  18400. public:
  18401. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18402. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18403. {
  18404. compoundHelper = (IHThorDiskReadArg *)&helper;
  18405. readHelper = (IHThorDiskReadArg *)&helper;
  18406. readAheadDone = false;
  18407. readIndex = 0;
  18408. }
  18409. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18410. {
  18411. rowLimit = compoundHelper->getRowLimit();
  18412. stopAfter = compoundHelper->getChooseNLimit();
  18413. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18414. readAheadDone = false;
  18415. readIndex = 0;
  18416. }
  18417. virtual void reset()
  18418. {
  18419. while (readrows.isItem(readIndex))
  18420. ReleaseRoxieRow(readrows.item(readIndex++));
  18421. readrows.kill();
  18422. readAheadDone = false;
  18423. readIndex = 0;
  18424. CRoxieServerDiskReadBaseActivity::reset();
  18425. }
  18426. virtual const void *nextInGroup()
  18427. {
  18428. if (eof)
  18429. return NULL;
  18430. else if (useRemote())
  18431. return remote->nextInGroup();
  18432. else if (maySkip)
  18433. {
  18434. if (!readAheadDone)
  18435. {
  18436. unsigned preprocessed = 0;
  18437. while (!eof)
  18438. {
  18439. const void *row = _nextInGroup();
  18440. if (row)
  18441. preprocessed++;
  18442. if (preprocessed > rowLimit)
  18443. {
  18444. ReleaseRoxieRow(row);
  18445. while (readrows.isItem(readIndex))
  18446. ReleaseRoxieRow(readrows.item(readIndex++));
  18447. readrows.kill();
  18448. eof = true;
  18449. if (ctx->queryDebugContext())
  18450. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18451. if (helper.getFlags() & TDRlimitskips)
  18452. return NULL;
  18453. else if (helper.getFlags() & TDRlimitcreates)
  18454. return createLimitFailRow(false);
  18455. else
  18456. throwUnexpected();
  18457. }
  18458. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  18459. {
  18460. eof = true;
  18461. ReleaseRoxieRow(row);
  18462. break;
  18463. }
  18464. readrows.append(row);
  18465. }
  18466. readAheadDone = true;
  18467. }
  18468. if (readrows.isItem(readIndex))
  18469. {
  18470. const void *ret = readrows.item(readIndex++);
  18471. if (ret)
  18472. processed++;
  18473. return ret;
  18474. }
  18475. else
  18476. {
  18477. eof = true;
  18478. return NULL;
  18479. }
  18480. }
  18481. else
  18482. {
  18483. const void *ret = _nextInGroup();
  18484. if (ret)
  18485. {
  18486. processed++;
  18487. if (processed > rowLimit)
  18488. {
  18489. if (traceLevel > 4)
  18490. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18491. ReleaseRoxieRow(ret);
  18492. compoundHelper->onLimitExceeded();
  18493. throwUnexpected(); // onLimitExceeded is not supposed to return
  18494. }
  18495. if (processed > stopAfter) // MORE - bit of a strange place to check
  18496. {
  18497. eof = true;
  18498. ReleaseRoxieRow(ret);
  18499. return NULL;
  18500. }
  18501. }
  18502. return ret;
  18503. }
  18504. }
  18505. const void *_nextInGroup()
  18506. {
  18507. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18508. unsigned transformedSize = 0;
  18509. if (isKeyed)
  18510. {
  18511. loop
  18512. {
  18513. const void *nextCandidate = cursor->nextMatch();
  18514. if (!nextCandidate)
  18515. {
  18516. eof = true;
  18517. return NULL;
  18518. }
  18519. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  18520. if (transformedSize)
  18521. break;
  18522. }
  18523. }
  18524. else // use reader...
  18525. {
  18526. assertex(reader != NULL);
  18527. loop
  18528. {
  18529. if (deserializeSource.eos())
  18530. {
  18531. eof = true;
  18532. return NULL;
  18533. }
  18534. prefetcher->readAhead(deserializeSource);
  18535. const byte *nextRec = deserializeSource.queryRow();
  18536. if (cursor && cursor->isFiltered(nextRec))
  18537. transformedSize = 0;
  18538. else
  18539. transformedSize = readHelper->transform(rowBuilder, nextRec);
  18540. deserializeSource.finishedRow();
  18541. if (transformedSize)
  18542. break;
  18543. }
  18544. }
  18545. return rowBuilder.finalizeRowClear(transformedSize);
  18546. }
  18547. };
  18548. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  18549. {
  18550. IHThorXmlReadArg * readHelper;
  18551. Owned<IXmlToRowTransformer> rowTransformer;
  18552. Owned<IXMLParse> xmlParser;
  18553. Owned<IColumnProvider> lastMatch;
  18554. unsigned __int64 localOffset;
  18555. public:
  18556. IMPLEMENT_IINTERFACE;
  18557. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  18558. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  18559. {
  18560. compoundHelper = NULL;
  18561. readHelper = (IHThorXmlReadArg *)&helper;
  18562. localOffset = 0;
  18563. }
  18564. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18565. {
  18566. rowLimit = readHelper->getRowLimit();
  18567. stopAfter = readHelper->getChooseNLimit();
  18568. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18569. if (!useRemote())
  18570. {
  18571. rowTransformer.set(readHelper->queryTransformer());
  18572. assertex(reader != NULL);
  18573. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  18574. if (factory->getKind()==TAKjsonread)
  18575. xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18576. else
  18577. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  18578. }
  18579. }
  18580. virtual void reset()
  18581. {
  18582. CRoxieServerDiskReadBaseActivity::reset();
  18583. rowTransformer.clear();
  18584. xmlParser.clear();
  18585. }
  18586. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  18587. {
  18588. localOffset = startOffset;
  18589. lastMatch.set(&entry);
  18590. }
  18591. virtual const void *nextInGroup()
  18592. {
  18593. if (eof)
  18594. return NULL;
  18595. else if (useRemote())
  18596. return remote->nextInGroup();
  18597. assertex(xmlParser != NULL);
  18598. try
  18599. {
  18600. while (!eof)
  18601. {
  18602. //call to next() will callback on the IXmlSelect interface
  18603. bool gotNext = false;
  18604. gotNext = xmlParser->next();
  18605. if(!gotNext)
  18606. eof = true;
  18607. else if (lastMatch)
  18608. {
  18609. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18610. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18611. lastMatch.clear();
  18612. localOffset = 0;
  18613. if (sizeGot)
  18614. {
  18615. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18616. if (processed > rowLimit)
  18617. {
  18618. if (traceLevel > 4)
  18619. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18620. readHelper->onLimitExceeded();
  18621. throwUnexpected(); // onLimitExceeded is not supposed to return
  18622. }
  18623. processed++;
  18624. if (processed > stopAfter) // MORE - bit of a strange place to check
  18625. {
  18626. eof = true;
  18627. return NULL;
  18628. }
  18629. return ret.getClear();
  18630. }
  18631. }
  18632. }
  18633. return NULL;
  18634. }
  18635. catch(IException *E)
  18636. {
  18637. throw makeWrappedException(E);
  18638. }
  18639. }
  18640. };
  18641. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18642. {
  18643. IHThorCsvReadArg *readHelper;
  18644. ICsvParameters * csvInfo;
  18645. unsigned headerLines;
  18646. unsigned maxDiskSize;
  18647. CSVSplitter csvSplitter;
  18648. unsigned __int64 localOffset;
  18649. const char *quotes;
  18650. const char *separators;
  18651. const char *terminators;
  18652. const char *escapes;
  18653. size32_t maxRowSize;
  18654. public:
  18655. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18656. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18657. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  18658. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18659. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  18660. {
  18661. compoundHelper = NULL;
  18662. readHelper = (IHThorCsvReadArg *)&helper;
  18663. rowLimit = readHelper->getRowLimit();
  18664. stopAfter = readHelper->getChooseNLimit();
  18665. csvInfo = readHelper->queryCsvParameters();
  18666. maxDiskSize = csvInfo->queryMaxSize();
  18667. localOffset = 0;
  18668. headerLines = 0;
  18669. }
  18670. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18671. {
  18672. rowLimit = readHelper->getRowLimit();
  18673. stopAfter = readHelper->getChooseNLimit();
  18674. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18675. if (!useRemote())
  18676. {
  18677. headerLines = csvInfo->queryHeaderLen();
  18678. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18679. 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...
  18680. if (!eof)
  18681. {
  18682. if (varFileInfo)
  18683. {
  18684. const IPropertyTree *options = varFileInfo->queryProperties();
  18685. if (options)
  18686. {
  18687. quotes = options->queryProp("@csvQuote");
  18688. separators = options->queryProp("@csvSeparate");
  18689. terminators = options->queryProp("@csvTerminate");
  18690. escapes = options->queryProp("@csvEscape");
  18691. }
  18692. }
  18693. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18694. }
  18695. }
  18696. }
  18697. virtual const void *nextInGroup()
  18698. {
  18699. if (eof)
  18700. return NULL;
  18701. else if (useRemote())
  18702. return remote->nextInGroup();
  18703. try
  18704. {
  18705. while (!eof)
  18706. {
  18707. if (reader->eos())
  18708. {
  18709. eof = true;
  18710. break;
  18711. }
  18712. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18713. size32_t rowSize = 4096; // MORE - make configurable
  18714. size32_t thisLineLength;
  18715. loop
  18716. {
  18717. size32_t avail;
  18718. const void *peek = reader->peek(rowSize, avail);
  18719. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18720. if (thisLineLength < rowSize || avail < rowSize)
  18721. break;
  18722. if (rowSize == maxRowSize)
  18723. throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
  18724. if (rowSize >= maxRowSize/2)
  18725. rowSize = maxRowSize;
  18726. else
  18727. rowSize += rowSize;
  18728. }
  18729. if (headerLines)
  18730. {
  18731. headerLines--;
  18732. reader->skip(thisLineLength);
  18733. }
  18734. else
  18735. {
  18736. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18737. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18738. reader->skip(thisLineLength);
  18739. if (transformedSize)
  18740. {
  18741. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18742. if (processed > rowLimit)
  18743. {
  18744. readHelper->onLimitExceeded();
  18745. throwUnexpected(); // onLimitExceeded is not supposed to return
  18746. }
  18747. processed++;
  18748. if (processed > stopAfter) // MORE - bit of a strange place to check
  18749. {
  18750. eof = true;
  18751. return NULL;
  18752. }
  18753. return ret.getClear();
  18754. }
  18755. }
  18756. }
  18757. return NULL;
  18758. }
  18759. catch(IException *E)
  18760. {
  18761. throw makeWrappedException(E);
  18762. }
  18763. }
  18764. virtual void reset()
  18765. {
  18766. CRoxieServerDiskReadBaseActivity::reset();
  18767. csvSplitter.reset();
  18768. localOffset = 0;
  18769. }
  18770. virtual unsigned __int64 getFilePosition(const void * row)
  18771. {
  18772. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18773. }
  18774. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18775. {
  18776. UNIMPLEMENTED;
  18777. }
  18778. };
  18779. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18780. {
  18781. IHThorDiskNormalizeArg *normalizeHelper;
  18782. bool firstPending;
  18783. public:
  18784. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18785. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18786. {
  18787. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18788. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18789. firstPending = true;
  18790. }
  18791. virtual void reset()
  18792. {
  18793. firstPending = true;
  18794. CRoxieServerDiskReadBaseActivity::reset();
  18795. }
  18796. virtual const void *nextInGroup()
  18797. {
  18798. if (eof)
  18799. return NULL;
  18800. else if (useRemote())
  18801. return remote->nextInGroup();
  18802. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18803. unsigned transformedSize = 0;
  18804. if (isKeyed)
  18805. {
  18806. loop
  18807. {
  18808. while (firstPending)
  18809. {
  18810. const void *nextCandidate = cursor->nextMatch();
  18811. if (!nextCandidate)
  18812. {
  18813. eof = true;
  18814. return NULL;
  18815. }
  18816. if (normalizeHelper->first(nextCandidate))
  18817. {
  18818. firstPending = false;
  18819. break;
  18820. }
  18821. }
  18822. transformedSize = normalizeHelper->transform(rowBuilder);
  18823. firstPending = !normalizeHelper->next();
  18824. if (transformedSize)
  18825. break;
  18826. }
  18827. }
  18828. else
  18829. {
  18830. assertex(reader != NULL);
  18831. loop
  18832. {
  18833. while (firstPending)
  18834. {
  18835. if (deserializeSource.eos())
  18836. {
  18837. eof = true;
  18838. return NULL;
  18839. }
  18840. prefetcher->readAhead(deserializeSource);
  18841. const byte *nextRec = deserializeSource.queryRow();
  18842. if (!cursor || !cursor->isFiltered(nextRec))
  18843. {
  18844. if (normalizeHelper->first(nextRec))
  18845. firstPending = false;
  18846. }
  18847. deserializeSource.finishedRow();
  18848. }
  18849. transformedSize = normalizeHelper->transform(rowBuilder);
  18850. firstPending = !normalizeHelper->next();
  18851. if (transformedSize)
  18852. break;
  18853. }
  18854. }
  18855. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18856. processed++;
  18857. if (processed > rowLimit)
  18858. {
  18859. compoundHelper->onLimitExceeded();
  18860. throwUnexpected(); // onLimitExceeded is not supposed to return
  18861. }
  18862. if (processed > stopAfter) // MORE - bit of a strange place to check
  18863. {
  18864. eof = true;
  18865. return NULL;
  18866. }
  18867. return recBuffer.getClear();
  18868. }
  18869. };
  18870. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18871. {
  18872. protected:
  18873. bool done;
  18874. public:
  18875. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18876. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18877. done(false)
  18878. {
  18879. }
  18880. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18881. {
  18882. done = false;
  18883. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18884. }
  18885. virtual IRoxieInput *queryOutput(unsigned idx)
  18886. {
  18887. if (idx==(unsigned)-1)
  18888. idx = 0;
  18889. return idx ? NULL: this;
  18890. }
  18891. };
  18892. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18893. {
  18894. IHThorDiskCountArg & countHelper;
  18895. unsigned __int64 choosenLimit;
  18896. IHThorSourceCountLimit *limitHelper;
  18897. unsigned __int64 getSkippedCount()
  18898. {
  18899. unsigned flags = countHelper.getFlags();
  18900. if (flags & TDRlimitskips)
  18901. return 0;
  18902. else if (flags & TDRlimitcreates)
  18903. return 1;
  18904. else
  18905. {
  18906. assertex(limitHelper);
  18907. if (traceLevel > 4)
  18908. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18909. limitHelper->onLimitExceeded();
  18910. throwUnexpected(); // onLimitExceeded should always throw exception
  18911. }
  18912. }
  18913. public:
  18914. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18915. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18916. countHelper((IHThorDiskCountArg &)basehelper)
  18917. {
  18918. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18919. choosenLimit = 0;
  18920. }
  18921. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18922. {
  18923. choosenLimit = countHelper.getChooseNLimit();
  18924. if (limitHelper)
  18925. {
  18926. rowLimit = limitHelper->getRowLimit();
  18927. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18928. }
  18929. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18930. }
  18931. virtual const void *nextInGroup()
  18932. {
  18933. ActivityTimer t(totalCycles, timeActivities);
  18934. if (done) return NULL;
  18935. done = true;
  18936. unsigned __int64 totalCount = 0;
  18937. if (helper.canMatchAny() && !eof)
  18938. {
  18939. if (useRemote())
  18940. {
  18941. loop
  18942. {
  18943. const void * next = remote->nextInGroup();
  18944. if (!next)
  18945. break;
  18946. if (meta.getFixedSize() == 1)
  18947. totalCount += *(byte *)next;
  18948. else
  18949. totalCount += *(unsigned __int64 *)next;
  18950. ReleaseRoxieRow(next);
  18951. if (totalCount > rowLimit)
  18952. {
  18953. totalCount = getSkippedCount();
  18954. break;
  18955. }
  18956. else if (totalCount >= choosenLimit)
  18957. {
  18958. totalCount = choosenLimit;
  18959. break;
  18960. }
  18961. }
  18962. }
  18963. else
  18964. {
  18965. if (isKeyed)
  18966. {
  18967. loop
  18968. {
  18969. const void *nextCandidate = cursor->nextMatch();
  18970. if (!nextCandidate)
  18971. break;
  18972. totalCount += countHelper.numValid(nextCandidate);
  18973. if (totalCount > rowLimit)
  18974. {
  18975. totalCount = getSkippedCount();
  18976. break;
  18977. }
  18978. else if (totalCount >= choosenLimit)
  18979. {
  18980. totalCount = choosenLimit;
  18981. break;
  18982. }
  18983. }
  18984. }
  18985. else
  18986. {
  18987. assertex(reader != NULL);
  18988. while (!deserializeSource.eos())
  18989. {
  18990. prefetcher->readAhead(deserializeSource);
  18991. const byte *nextRec = deserializeSource.queryRow();
  18992. if (!cursor || !cursor->isFiltered(nextRec))
  18993. {
  18994. totalCount += countHelper.numValid(nextRec);
  18995. }
  18996. deserializeSource.finishedRow();
  18997. if (totalCount > rowLimit)
  18998. {
  18999. totalCount = getSkippedCount();
  19000. break;
  19001. }
  19002. else if (totalCount >= choosenLimit)
  19003. {
  19004. totalCount = choosenLimit;
  19005. break;
  19006. }
  19007. }
  19008. }
  19009. }
  19010. }
  19011. size32_t rowSize = meta.getFixedSize();
  19012. void * result = rowAllocator->createRow();
  19013. if (rowSize == 1)
  19014. *(byte *)result = (byte)totalCount;
  19015. else
  19016. {
  19017. assertex(rowSize == sizeof(unsigned __int64));
  19018. *(unsigned __int64 *)result = totalCount;
  19019. }
  19020. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  19021. }
  19022. };
  19023. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19024. {
  19025. IHThorCompoundAggregateExtra & aggregateHelper;
  19026. public:
  19027. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19028. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19029. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19030. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  19031. {
  19032. }
  19033. const void * gatherMerged()
  19034. {
  19035. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19036. size32_t finalSize = 0;
  19037. if (useRemote())
  19038. {
  19039. const void * firstRow = remote->nextInGroup();
  19040. if (!firstRow)
  19041. {
  19042. rowBuilder.ensureRow();
  19043. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  19044. }
  19045. else
  19046. {
  19047. // NOTE need to clone this because going to modify below, could special case 1 row only
  19048. finalSize = cloneRow(rowBuilder, firstRow, meta);
  19049. ReleaseRoxieRow(firstRow);
  19050. }
  19051. loop
  19052. {
  19053. const void * next = remote->nextInGroup();
  19054. if (!next)
  19055. break;
  19056. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  19057. ReleaseRoxieRow(next);
  19058. }
  19059. }
  19060. else
  19061. {
  19062. aggregateHelper.clearAggregate(rowBuilder);
  19063. if (helper.canMatchAny() && !eof)
  19064. {
  19065. if (isKeyed)
  19066. {
  19067. loop
  19068. {
  19069. const void *next = cursor->nextMatch();
  19070. if (!next)
  19071. break;
  19072. aggregateHelper.processRow(rowBuilder, next);
  19073. }
  19074. }
  19075. else
  19076. {
  19077. assertex(reader != NULL);
  19078. while (!deserializeSource.eos())
  19079. {
  19080. prefetcher->readAhead(deserializeSource);
  19081. const byte *nextRec = deserializeSource.queryRow();
  19082. if (!cursor || !cursor->isFiltered(nextRec))
  19083. {
  19084. aggregateHelper.processRow(rowBuilder, nextRec);
  19085. }
  19086. deserializeSource.finishedRow();
  19087. }
  19088. }
  19089. }
  19090. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  19091. }
  19092. return rowBuilder.finalizeRowClear(finalSize);
  19093. }
  19094. virtual const void *nextInGroup()
  19095. {
  19096. ActivityTimer t(totalCycles, timeActivities);
  19097. if (done) return NULL;
  19098. const void * ret = gatherMerged();
  19099. done = true;
  19100. return ret;
  19101. }
  19102. };
  19103. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  19104. {
  19105. IHThorDiskGroupAggregateArg & aggregateHelper;
  19106. RowAggregator resultAggregator;
  19107. bool gathered;
  19108. public:
  19109. IMPLEMENT_IINTERFACE;
  19110. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  19111. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  19112. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  19113. resultAggregator(aggregateHelper, aggregateHelper),
  19114. gathered(false)
  19115. {
  19116. }
  19117. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19118. {
  19119. gathered= false;
  19120. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  19121. resultAggregator.start(rowAllocator);
  19122. }
  19123. virtual void reset()
  19124. {
  19125. resultAggregator.reset();
  19126. CRoxieServerDiskAggregateBaseActivity::reset();
  19127. }
  19128. void gatherMerged()
  19129. {
  19130. if (useRemote())
  19131. {
  19132. loop
  19133. {
  19134. const void * next = remote->nextInGroup();
  19135. if (!next)
  19136. break;
  19137. resultAggregator.mergeElement(next);
  19138. ReleaseRoxieRow(next);
  19139. }
  19140. }
  19141. else
  19142. {
  19143. if (helper.canMatchAny() && !eof)
  19144. {
  19145. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  19146. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  19147. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  19148. ctx->queryCodeContext(), activityId);
  19149. processor->doQuery(NULL, 0, 0, 0);
  19150. }
  19151. }
  19152. gathered = true;
  19153. }
  19154. virtual const void *nextInGroup()
  19155. {
  19156. ActivityTimer t(totalCycles, timeActivities);
  19157. if (done)
  19158. return NULL;
  19159. if (!gathered)
  19160. gatherMerged();
  19161. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  19162. if (next)
  19163. {
  19164. processed++;
  19165. return next->finalizeRowClear();
  19166. }
  19167. done = true;
  19168. return NULL;
  19169. }
  19170. };
  19171. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  19172. {
  19173. public:
  19174. RemoteActivityId remoteId;
  19175. bool isLocal;
  19176. bool sorted;
  19177. bool maySkip;
  19178. bool variableFileName;
  19179. Owned<IFileIOArray> files;
  19180. Owned<IInMemoryIndexManager> manager;
  19181. Owned<const IResolvedFile> datafile;
  19182. const char *quotes;
  19183. const char *separators;
  19184. const char *terminators;
  19185. const char *escapes;
  19186. size32_t maxCsvRowSize;
  19187. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19188. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19189. {
  19190. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19191. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19192. sorted = (helper->getFlags() & TDRunsorted) == 0;
  19193. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19194. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  19195. quotes = separators = terminators = escapes = NULL;
  19196. if (!variableFileName)
  19197. {
  19198. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  19199. OwnedRoxieString fileName(helper->getFileName());
  19200. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit()));
  19201. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  19202. if (isLocal || isSimple)
  19203. {
  19204. if (datafile)
  19205. {
  19206. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  19207. files.setown(datafile->getIFileIOArray(isOpt, channel));
  19208. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  19209. const IPropertyTree *options = datafile->queryProperties();
  19210. if (options)
  19211. {
  19212. quotes = options->queryProp("@csvQuote");
  19213. separators = options->queryProp("@csvSeparate");
  19214. terminators = options->queryProp("@csvTerminate");
  19215. escapes = options->queryProp("@csvEscape");
  19216. }
  19217. }
  19218. else
  19219. manager.setown(getEmptyIndexManager());
  19220. }
  19221. }
  19222. switch (kind)
  19223. {
  19224. case TAKcsvread:
  19225. {
  19226. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  19227. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  19228. if (workunit)
  19229. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  19230. break;
  19231. }
  19232. default:
  19233. maxCsvRowSize = 0; // unused
  19234. }
  19235. }
  19236. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19237. {
  19238. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  19239. switch (kind)
  19240. {
  19241. case TAKcsvread:
  19242. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  19243. quotes, separators, terminators, escapes, maxCsvRowSize);
  19244. case TAKxmlread:
  19245. case TAKjsonread:
  19246. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19247. case TAKdiskread:
  19248. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  19249. case TAKdisknormalize:
  19250. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  19251. case TAKdiskcount:
  19252. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19253. case TAKdiskaggregate:
  19254. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19255. case TAKdiskgroupaggregate:
  19256. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  19257. }
  19258. throwUnexpected();
  19259. }
  19260. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19261. {
  19262. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  19263. }
  19264. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19265. {
  19266. if (datafile)
  19267. addXrefFileInfo(reply, datafile);
  19268. else
  19269. {
  19270. // Temporarily resolve the file
  19271. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  19272. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  19273. {
  19274. OwnedRoxieString fileName(helper->getFileName());
  19275. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit());
  19276. if (temp)
  19277. addXrefFileInfo(reply, temp);
  19278. }
  19279. }
  19280. }
  19281. virtual const StatisticsMapping &queryStatsMapping() const
  19282. {
  19283. return diskStatistics;
  19284. }
  19285. };
  19286. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19287. {
  19288. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19289. }
  19290. //=================================================================================
  19291. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  19292. {
  19293. protected:
  19294. IHThorIndexReadBaseArg &indexHelper;
  19295. IHThorSteppedSourceExtra * steppedExtra;
  19296. Linked<IKeyArray> keySet;
  19297. Linked<TranslatorArray> translators;
  19298. CSkippableRemoteResultAdaptor remote;
  19299. CIndexTransformCallback callback;
  19300. bool sorted;
  19301. bool variableFileName;
  19302. bool variableInfoPending;
  19303. bool isOpt;
  19304. bool isLocal;
  19305. unsigned __int64 rowLimit;
  19306. unsigned __int64 keyedLimit;
  19307. unsigned __int64 choosenLimit;
  19308. unsigned accepted;
  19309. unsigned rejected;
  19310. unsigned seekGEOffset;
  19311. Owned<IKeyManager> tlk;
  19312. Owned<const IResolvedFile> varFileInfo;
  19313. const RemoteActivityId &remoteId;
  19314. void setVariableFileInfo()
  19315. {
  19316. OwnedRoxieString indexName(indexHelper.getFileName());
  19317. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19318. if (varFileInfo)
  19319. {
  19320. translators.setown(new TranslatorArray) ;
  19321. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19322. }
  19323. variableInfoPending = false;
  19324. }
  19325. public:
  19326. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19327. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19328. : CRoxieServerActivity(_factory, _probeManager),
  19329. keySet(_keySet),
  19330. translators(_translators),
  19331. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  19332. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  19333. remoteId(_remoteId),
  19334. sorted(_sorted),
  19335. isLocal(_isLocal)
  19336. {
  19337. indexHelper.setCallback(&callback);
  19338. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19339. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19340. variableInfoPending = false;
  19341. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  19342. seekGEOffset = 0;
  19343. // started = false;
  19344. rejected = accepted = 0;
  19345. rowLimit = choosenLimit = keyedLimit = 0;
  19346. }
  19347. virtual const IResolvedFile *queryVarFileInfo() const
  19348. {
  19349. return varFileInfo;
  19350. }
  19351. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  19352. {
  19353. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  19354. remote.onCreate(this, this, _ctx, _colocalParent);
  19355. }
  19356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19357. {
  19358. accepted = 0;
  19359. rejected = 0;
  19360. rowLimit = (unsigned __int64) -1;
  19361. keyedLimit = (unsigned __int64 ) -1;
  19362. choosenLimit = I64C(0x7fffffffffffffff);
  19363. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19364. remote.onStart(parentExtractSize, parentExtract);
  19365. variableInfoPending = variableFileName;
  19366. }
  19367. void processAllKeys()
  19368. {
  19369. try
  19370. {
  19371. if (indexHelper.canMatchAny())
  19372. {
  19373. if (variableInfoPending)
  19374. setVariableFileInfo();
  19375. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  19376. if (keySet)
  19377. {
  19378. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  19379. // 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
  19380. // However order is probably better to iterate fileno's inside partnos
  19381. // MORE - also not properly supporting STEPPED I fear.
  19382. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  19383. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  19384. {
  19385. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  19386. if (thisBase)
  19387. {
  19388. unsigned fileNo = 0;
  19389. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  19390. if (!thisKey->isTopLevelKey())
  19391. {
  19392. if (keyedLimit != (unsigned __int64) -1)
  19393. {
  19394. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19395. {
  19396. Owned<IKeyManager> countKey;
  19397. countKey.setown(createKeyManager(thisKey, 0, this));
  19398. countKey->setLayoutTranslator(translators->item(fileNo));
  19399. createSegmentMonitors(countKey);
  19400. unsigned __int64 count = countKey->checkCount(keyedLimit);
  19401. if (count > keyedLimit)
  19402. {
  19403. if (traceLevel > 4)
  19404. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19405. onLimitExceeded(true);
  19406. }
  19407. }
  19408. }
  19409. }
  19410. if (seekGEOffset && !thisKey->isTopLevelKey())
  19411. {
  19412. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  19413. }
  19414. else
  19415. {
  19416. tlk.setown(createKeyManager(thisKey, 0, this));
  19417. tlk->setLayoutTranslator(translators->item(fileNo));
  19418. }
  19419. createSegmentMonitors(tlk);
  19420. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19421. {
  19422. StringBuffer out;
  19423. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19424. CTXLOG("Using filter %s", out.str());
  19425. if (ctx->queryProbeManager())
  19426. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19427. }
  19428. tlk->reset();
  19429. loop // for each file part
  19430. {
  19431. //block for TransformCallbackAssociation
  19432. {
  19433. TransformCallbackAssociation associate(callback, tlk);
  19434. if (thisKey->isTopLevelKey())
  19435. {
  19436. if (thisKey->isFullySorted())
  19437. {
  19438. while (tlk->lookup(false))
  19439. {
  19440. unsigned slavePart = (unsigned) tlk->queryFpos();
  19441. if (slavePart)
  19442. {
  19443. accepted++;
  19444. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  19445. if (sorted && numChannels>1)
  19446. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  19447. }
  19448. }
  19449. }
  19450. else
  19451. {
  19452. // MORE - we could check whether there are any matching parts if we wanted.
  19453. // If people are in the habit of sending null values that would be worthwhile
  19454. remote.getMem(0, fileNo, 0);
  19455. }
  19456. }
  19457. else
  19458. {
  19459. if (processSingleKey(thisKey, translators->item(fileNo)))
  19460. break;
  19461. }
  19462. }
  19463. if (++fileNo < thisBase->numParts())
  19464. {
  19465. thisKey = thisBase->queryPart(fileNo);
  19466. tlk->setKey(thisKey);
  19467. tlk->setLayoutTranslator(translators->item(fileNo));
  19468. tlk->reset();
  19469. }
  19470. else
  19471. break;
  19472. }
  19473. tlk->releaseSegmentMonitors();
  19474. tlk->setKey(NULL);
  19475. }
  19476. }
  19477. }
  19478. }
  19479. remote.flush();
  19480. remote.senddone();
  19481. }
  19482. catch (IException *E)
  19483. {
  19484. remote.setException(E);
  19485. }
  19486. }
  19487. virtual void createSegmentMonitors(IKeyManager *key)
  19488. {
  19489. indexHelper.createSegmentMonitors(key);
  19490. key->finishSegmentMonitors();
  19491. }
  19492. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  19493. virtual void reset()
  19494. {
  19495. if (accepted)
  19496. noteStatistic(StNumIndexAccepted, accepted);
  19497. if (rejected)
  19498. noteStatistic(StNumIndexRejected, rejected);
  19499. remote.onReset();
  19500. CRoxieServerActivity::reset();
  19501. if (varFileInfo)
  19502. {
  19503. keySet.clear();
  19504. varFileInfo.clear();
  19505. }
  19506. variableInfoPending = false;
  19507. }
  19508. virtual void stop(bool aborting)
  19509. {
  19510. remote.onStop(aborting);
  19511. CRoxieServerActivity::stop(aborting);
  19512. }
  19513. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19514. {
  19515. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19516. }
  19517. };
  19518. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  19519. {
  19520. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19521. public:
  19522. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19523. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  19524. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  19525. {
  19526. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19527. }
  19528. virtual void reset()
  19529. {
  19530. remote.onReset();
  19531. CRoxieServerIndexActivity::reset();
  19532. }
  19533. virtual const void *nextInGroup()
  19534. {
  19535. ActivityTimer t(totalCycles, timeActivities);
  19536. try
  19537. {
  19538. const void *ret = remote.nextInGroup();
  19539. if (ret)
  19540. processed++;
  19541. return ret;
  19542. }
  19543. catch (IException *E)
  19544. {
  19545. throw makeWrappedException(E);
  19546. }
  19547. }
  19548. protected:
  19549. virtual const void * createLimitFailRow(bool isKeyed)
  19550. {
  19551. createRowAllocator();
  19552. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19553. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19554. if (outSize)
  19555. return rowBuilder.finalizeRowClear(outSize);
  19556. return NULL;
  19557. }
  19558. };
  19559. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  19560. {
  19561. protected:
  19562. IHThorCompoundReadExtra & readHelper;
  19563. ISteppingMeta *rawMeta;
  19564. CSteppingMeta steppingMeta;
  19565. unsigned * seekSizes;
  19566. bool optimizeSteppedPostFilter;
  19567. ISteppingMeta * projectedMeta;
  19568. unsigned maxSeekLookahead;
  19569. public:
  19570. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19571. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  19572. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  19573. readHelper((IHThorIndexReadArg &)basehelper)
  19574. {
  19575. rawMeta = readHelper.queryRawSteppingMeta();
  19576. unsigned flags = indexHelper.getFlags();
  19577. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19578. seekSizes = NULL;
  19579. maxSeekLookahead = _maxSeekLookahead;
  19580. if (rawMeta)
  19581. {
  19582. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19583. unsigned maxFields = rawMeta->getNumFields();
  19584. seekGEOffset = fields[0].offset;
  19585. seekSizes = new unsigned[maxFields];
  19586. seekSizes[0] = fields[0].size;
  19587. for (unsigned i=1; i < maxFields; i++)
  19588. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19589. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19590. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  19591. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  19592. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19593. steppingMeta.init(useMeta, hasPostFilter);
  19594. }
  19595. }
  19596. ~CRoxieServerIndexReadActivity()
  19597. {
  19598. delete [] seekSizes;
  19599. }
  19600. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19601. {
  19602. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19603. steppingMeta.setDistributed();
  19604. if (steppedExtra)
  19605. steppingMeta.setExtra(steppedExtra);
  19606. rowLimit = readHelper.getRowLimit();
  19607. keyedLimit = readHelper.getKeyedLimit();
  19608. choosenLimit = readHelper.getChooseNLimit();
  19609. if (!paused)
  19610. processAllKeys();
  19611. }
  19612. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  19613. {
  19614. public:
  19615. IMPLEMENT_IINTERFACE;
  19616. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  19617. {
  19618. Link();
  19619. return const_cast<LazyLocalKeyReader*> (this);
  19620. }
  19621. virtual const void *getMessageHeader(unsigned &length) const
  19622. {
  19623. length = 0;
  19624. return NULL;
  19625. }
  19626. virtual const void *getMessageMetadata(unsigned &length) const
  19627. {
  19628. length = 0;
  19629. return NULL;
  19630. }
  19631. virtual void discard() const
  19632. {
  19633. // nothing to do.
  19634. }
  19635. unsigned keyedCount;
  19636. unsigned matched;
  19637. bool EOFseen;
  19638. Owned<IKeyIndexSet> keySet;
  19639. Owned<IKeyManager> tlk;
  19640. CRoxieServerIndexReadActivity &owner;
  19641. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19642. : owner(_owner)
  19643. {
  19644. keyedCount = 0;
  19645. matched = 0;
  19646. EOFseen = false;
  19647. keySet.setown(createKeyIndexSet());
  19648. keySet->addIndex(LINK(key));
  19649. if (owner.seekGEOffset)
  19650. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19651. else
  19652. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19653. tlk->setLayoutTranslator(trans);
  19654. owner.indexHelper.createSegmentMonitors(tlk);
  19655. tlk->finishSegmentMonitors();
  19656. tlk->reset();
  19657. }
  19658. virtual const void *getNext(int length)
  19659. {
  19660. TransformCallbackAssociation associate(owner.callback, tlk);
  19661. while (tlk->lookup(true))
  19662. {
  19663. keyedCount++;
  19664. if (keyedCount > owner.keyedLimit)
  19665. {
  19666. owner.onLimitExceeded(true); // Should throw exception
  19667. throwUnexpected();
  19668. }
  19669. size32_t transformedSize;
  19670. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19671. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19672. try
  19673. {
  19674. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19675. owner.callback.finishedRow();
  19676. }
  19677. catch (IException *E)
  19678. {
  19679. throw owner.makeWrappedException(E);
  19680. }
  19681. if (transformedSize)
  19682. {
  19683. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19684. matched++;
  19685. if (matched > owner.rowLimit)
  19686. {
  19687. owner.onLimitExceeded(false); // Should throw exception
  19688. throwUnexpected();
  19689. }
  19690. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19691. {
  19692. break;
  19693. }
  19694. owner.accepted++;
  19695. return result.getClear();
  19696. }
  19697. else
  19698. owner.rejected++;
  19699. }
  19700. EOFseen = true;
  19701. return NULL;
  19702. }
  19703. virtual bool atEOF() const
  19704. {
  19705. return EOFseen;
  19706. }
  19707. virtual bool isSerialized() const
  19708. {
  19709. return false;
  19710. }
  19711. };
  19712. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19713. {
  19714. createRowAllocator();
  19715. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19716. return false;
  19717. }
  19718. virtual void onLimitExceeded(bool isKeyed)
  19719. {
  19720. if (traceLevel > 4)
  19721. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19722. if (isKeyed)
  19723. {
  19724. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19725. {
  19726. if (ctx->queryDebugContext())
  19727. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19728. throw makeLimitSkipException(true);
  19729. }
  19730. else
  19731. readHelper.onKeyedLimitExceeded();
  19732. }
  19733. else
  19734. {
  19735. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19736. {
  19737. if (ctx->queryDebugContext())
  19738. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19739. throw makeLimitSkipException(false);
  19740. }
  19741. else
  19742. readHelper.onLimitExceeded();
  19743. }
  19744. }
  19745. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19746. {
  19747. out.append((unsigned short) numFields);
  19748. out.append((unsigned short) seekLen);
  19749. out.append((unsigned short) stepExtra.queryFlags());
  19750. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19751. if (seeks)
  19752. {
  19753. unsigned lookahead = 40000/seekLen;
  19754. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19755. lookahead = maxSeekLookahead;
  19756. seeks->ensureFilled(seek, numFields, lookahead);
  19757. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19758. unsigned serialized = 1; // rawseek is always serialized...
  19759. unsigned patchLength = out.length();
  19760. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19761. out.append(seekLen, rawSeek);
  19762. if (seeks->ordinality())
  19763. {
  19764. const void *lastSeek = rawSeek;
  19765. byte *nextSeek = NULL;
  19766. if (projectedMeta)
  19767. nextSeek = (byte *) alloca(seekLen);
  19768. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19769. {
  19770. if (projectedMeta)
  19771. {
  19772. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19773. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19774. }
  19775. else
  19776. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19777. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19778. if (diff > 0)
  19779. {
  19780. serialized++;
  19781. out.append(seekLen, nextSeek);
  19782. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19783. }
  19784. }
  19785. unsigned length = out.length();
  19786. out.setWritePos(patchLength);
  19787. out.append(serialized);
  19788. out.setWritePos(length);
  19789. }
  19790. }
  19791. else
  19792. {
  19793. out.append(false);
  19794. out.append(1);
  19795. out.append(seekLen, rawSeek);
  19796. }
  19797. }
  19798. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19799. {
  19800. ActivityTimer t(totalCycles, timeActivities);
  19801. try
  19802. {
  19803. unsigned seeklen = 0;
  19804. const void *rawSeek = NULL;
  19805. if (seek && numFields)
  19806. {
  19807. seeklen = seekSizes[numFields-1];
  19808. rawSeek = (const byte *)seek + seekGEOffset;
  19809. if (projectedMeta)
  19810. {
  19811. byte * temp = (byte *) alloca(seeklen);
  19812. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19813. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19814. rawSeek = (byte *)temp;
  19815. }
  19816. }
  19817. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19818. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19819. processed++;
  19820. return ret;
  19821. }
  19822. catch (IException *E)
  19823. {
  19824. throw makeWrappedException(E);
  19825. }
  19826. }
  19827. virtual IInputSteppingMeta * querySteppingMeta()
  19828. {
  19829. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19830. return &steppingMeta;
  19831. return NULL;
  19832. }
  19833. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19834. {
  19835. if (variableInfoPending)
  19836. setVariableFileInfo();
  19837. return this;
  19838. }
  19839. virtual IKeyArray *getKeySet() const
  19840. {
  19841. return keySet.getLink();
  19842. }
  19843. virtual const IResolvedFile *getVarFileInfo() const
  19844. {
  19845. return varFileInfo.getLink();
  19846. }
  19847. virtual TranslatorArray *getTranslators() const
  19848. {
  19849. return translators.getLink();
  19850. }
  19851. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19852. {
  19853. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19854. }
  19855. virtual IRoxieServerActivity *queryActivity() { return this; }
  19856. virtual const RemoteActivityId& queryRemoteId() const
  19857. {
  19858. return remoteId;
  19859. }
  19860. };
  19861. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19862. {
  19863. IHThorCompoundReadExtra & readHelper;
  19864. IHThorIndexReadBaseArg & indexHelper;
  19865. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19866. IHThorSteppedSourceExtra * steppedExtra;
  19867. bool eof;
  19868. Linked<IKeyArray>keySet;
  19869. Owned<IKeyIndexSet>keyIndexSet;
  19870. Owned<IKeyManager> tlk;
  19871. Linked<TranslatorArray> translators;
  19872. CIndexTransformCallback callback;
  19873. unsigned __int64 keyedLimit;
  19874. unsigned rowLimit;
  19875. unsigned chooseNLimit;
  19876. unsigned accepted;
  19877. unsigned rejected;
  19878. unsigned keyedCount;
  19879. ISteppingMeta * rawMeta;
  19880. ISteppingMeta * projectedMeta;
  19881. size32_t seekGEOffset;
  19882. unsigned * seekSizes;
  19883. CSteppingMeta steppingMeta;
  19884. Owned<const IResolvedFile> varFileInfo;
  19885. const RemoteActivityId &remoteId;
  19886. bool firstRead;
  19887. bool variableFileName;
  19888. bool variableInfoPending;
  19889. bool isOpt;
  19890. bool isLocal;
  19891. bool optimizeSteppedPostFilter;
  19892. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19893. void initKeySet()
  19894. {
  19895. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19896. {
  19897. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19898. }
  19899. keyIndexSet.setown(createKeyIndexSet());
  19900. for (unsigned part = 0; part < keySet->length(); part++)
  19901. {
  19902. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19903. if (kib)
  19904. {
  19905. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19906. {
  19907. IKeyIndex *k = kib->queryPart(subpart);
  19908. if (k)
  19909. {
  19910. assertex(!k->isTopLevelKey());
  19911. keyIndexSet->addIndex(LINK(k));
  19912. }
  19913. }
  19914. }
  19915. }
  19916. }
  19917. void setVariableFileInfo()
  19918. {
  19919. OwnedRoxieString indexName(indexHelper.getFileName());
  19920. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19921. translators.setown(new TranslatorArray) ;
  19922. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  19923. initKeySet();
  19924. variableInfoPending = false;
  19925. }
  19926. void onEOF()
  19927. {
  19928. callback.setManager(NULL);
  19929. eof = true;
  19930. tlk.clear();
  19931. }
  19932. public:
  19933. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19934. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19935. : CRoxieServerActivity(_factory, _probeManager),
  19936. readHelper((IHThorIndexReadArg &)basehelper),
  19937. indexHelper((IHThorIndexReadArg &)basehelper),
  19938. translators(_translatorArray),
  19939. keySet(_keyArray),
  19940. isLocal(_isLocal),
  19941. remoteId(_remoteId)
  19942. {
  19943. rowLimit = 0;
  19944. keyedLimit = 0;
  19945. chooseNLimit = 0;
  19946. indexHelper.setCallback(&callback);
  19947. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19948. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19949. unsigned flags = indexHelper.getFlags();
  19950. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19951. variableInfoPending = false;
  19952. isOpt = (flags & TIRoptional) != 0;
  19953. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19954. firstRead = true;
  19955. accepted = 0;
  19956. rejected = 0;
  19957. keyedCount = 0;
  19958. eof = false;
  19959. rawMeta = readHelper.queryRawSteppingMeta();
  19960. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19961. seekGEOffset = 0;
  19962. seekSizes = NULL;
  19963. if (rawMeta)
  19964. {
  19965. // MORE - should check all keys in maxFields list can actually be keyed.
  19966. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19967. unsigned maxFields = rawMeta->getNumFields();
  19968. seekGEOffset = fields[0].offset;
  19969. seekSizes = new unsigned[maxFields];
  19970. seekSizes[0] = fields[0].size;
  19971. for (unsigned i=1; i < maxFields; i++)
  19972. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19973. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19974. if (projectedMeta)
  19975. steppingMeta.init(projectedMeta, hasPostFilter);
  19976. else
  19977. steppingMeta.init(rawMeta, hasPostFilter);
  19978. }
  19979. }
  19980. virtual const IResolvedFile *queryVarFileInfo() const
  19981. {
  19982. return varFileInfo;
  19983. }
  19984. ~CRoxieServerSimpleIndexReadActivity()
  19985. {
  19986. delete [] seekSizes;
  19987. }
  19988. virtual bool needsAllocator() const { return true; }
  19989. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19990. {
  19991. firstRead = true;
  19992. accepted = 0;
  19993. rejected = 0;
  19994. keyedCount = 0;
  19995. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19996. if (steppedExtra)
  19997. steppingMeta.setExtra(steppedExtra);
  19998. eof = !indexHelper.canMatchAny();
  19999. if (variableFileName)
  20000. variableInfoPending = true;
  20001. else
  20002. {
  20003. variableInfoPending = false;
  20004. if (!keyIndexSet)
  20005. initKeySet();
  20006. }
  20007. }
  20008. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  20009. {
  20010. if (variableInfoPending)
  20011. setVariableFileInfo();
  20012. return this;
  20013. }
  20014. virtual IKeyArray *getKeySet() const
  20015. {
  20016. return keySet.getLink();
  20017. }
  20018. virtual const IResolvedFile *getVarFileInfo() const
  20019. {
  20020. return varFileInfo.getLink();
  20021. }
  20022. virtual TranslatorArray *getTranslators() const
  20023. {
  20024. return translators.getLink();
  20025. }
  20026. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  20027. {
  20028. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  20029. }
  20030. virtual IRoxieServerActivity *queryActivity() { return this; }
  20031. virtual const RemoteActivityId& queryRemoteId() const
  20032. {
  20033. return remoteId;
  20034. }
  20035. const void *nextInGroup()
  20036. {
  20037. bool matched = true;
  20038. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  20039. }
  20040. unsigned __int64 checkCount(unsigned __int64 limit)
  20041. {
  20042. unsigned numParts = keyIndexSet->numParts();
  20043. unsigned __int64 result = 0;
  20044. for (unsigned i = 0; i < numParts; i++)
  20045. {
  20046. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  20047. countTlk->setLayoutTranslator(translators->item(i));
  20048. indexHelper.createSegmentMonitors(countTlk);
  20049. countTlk->finishSegmentMonitors();
  20050. result += countTlk->checkCount(limit-result);
  20051. if (result > limit)
  20052. break;
  20053. }
  20054. return result;
  20055. }
  20056. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  20057. {
  20058. ActivityTimer t(totalCycles, timeActivities);
  20059. if (eof)
  20060. return NULL;
  20061. if (firstRead)
  20062. {
  20063. if (variableInfoPending)
  20064. setVariableFileInfo();
  20065. rowLimit = (unsigned) readHelper.getRowLimit();
  20066. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  20067. unsigned numParts = keyIndexSet->numParts();
  20068. if (!numParts)
  20069. {
  20070. onEOF();
  20071. return NULL;
  20072. }
  20073. if (numParts > 1 || seekGEOffset)
  20074. {
  20075. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  20076. // note that we don't set up translator because we don't support it. If that ever changes...
  20077. }
  20078. else
  20079. {
  20080. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  20081. tlk->setLayoutTranslator(translators->item(0));
  20082. }
  20083. indexHelper.createSegmentMonitors(tlk);
  20084. tlk->finishSegmentMonitors();
  20085. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20086. {
  20087. StringBuffer out;
  20088. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  20089. CTXLOG("Using filter %s", out.str());
  20090. if (ctx->queryProbeManager())
  20091. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20092. }
  20093. tlk->reset();
  20094. callback.setManager(tlk);
  20095. keyedLimit = readHelper.getKeyedLimit();
  20096. if (keyedLimit != (unsigned __int64) -1)
  20097. {
  20098. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20099. {
  20100. unsigned __int64 count = checkCount(keyedLimit);
  20101. if (count > keyedLimit)
  20102. {
  20103. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  20104. readHelper.onKeyedLimitExceeded();
  20105. const void * ret = NULL;
  20106. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  20107. ret = createKeyedLimitOnFailRow();
  20108. onEOF();
  20109. return ret;
  20110. }
  20111. keyedLimit = (unsigned __int64) -1;
  20112. }
  20113. }
  20114. firstRead = false;
  20115. }
  20116. if (accepted == chooseNLimit)
  20117. {
  20118. onEOF();
  20119. return NULL;
  20120. }
  20121. const byte * rawSeek = NULL;
  20122. unsigned seekSize = 0;
  20123. if (seek)
  20124. {
  20125. seekSize = seekSizes[numFields-1];
  20126. rawSeek = (const byte *)seek + seekGEOffset;
  20127. if (projectedMeta)
  20128. {
  20129. byte *temp = (byte *) alloca(seekSize);
  20130. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  20131. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  20132. rawSeek = (byte *)temp;
  20133. }
  20134. #ifdef _DEBUG
  20135. // StringBuffer seekStr;
  20136. // for (unsigned i = 0; i < seekSize; i++)
  20137. // {
  20138. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  20139. // }
  20140. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  20141. #endif
  20142. }
  20143. const byte * originalRawSeek = rawSeek;
  20144. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20145. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  20146. {
  20147. checkAbort();
  20148. keyedCount++;
  20149. if (keyedCount > keyedLimit)
  20150. {
  20151. readHelper.onKeyedLimitExceeded();
  20152. break;
  20153. }
  20154. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  20155. #ifdef _DEBUG
  20156. // StringBuffer recstr;
  20157. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  20158. // for (unsigned i = 0; i < size; i++)
  20159. // {
  20160. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  20161. // }
  20162. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  20163. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  20164. assertex(!"smart seek failure");
  20165. #endif
  20166. size32_t transformedSize;
  20167. rowBuilder.ensureRow();
  20168. try
  20169. {
  20170. transformedSize = readHelper.transform(rowBuilder, keyRow);
  20171. //if the post filter causes a mismatch, and the stepping condition no longer matches
  20172. //then return a mismatch record - so the join code can start seeking on the other input.
  20173. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  20174. {
  20175. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  20176. {
  20177. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  20178. if (transformedSize != 0)
  20179. wasCompleteMatch = false;
  20180. }
  20181. }
  20182. callback.finishedRow();
  20183. }
  20184. catch (IException *E)
  20185. {
  20186. throw makeWrappedException(E);
  20187. }
  20188. if (transformedSize)
  20189. {
  20190. accepted++;
  20191. if (accepted > rowLimit)
  20192. {
  20193. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  20194. {
  20195. throwUnexpected(); // should not have used simple variant if maySkip set...
  20196. }
  20197. if (traceLevel > 4)
  20198. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20199. readHelper.onLimitExceeded();
  20200. break;
  20201. }
  20202. processed++;
  20203. #ifdef _DEBUG
  20204. // const byte *ret = (const byte *) out.get();
  20205. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  20206. // queryOutputMeta()->toXML(ret, xmlwrite);
  20207. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  20208. #endif
  20209. return rowBuilder.finalizeRowClear(transformedSize);
  20210. }
  20211. else
  20212. rejected++;
  20213. rawSeek = NULL;
  20214. }
  20215. onEOF();
  20216. return NULL;
  20217. }
  20218. virtual void reset()
  20219. {
  20220. onEOF();
  20221. if (accepted)
  20222. noteStatistic(StNumIndexAccepted, accepted);
  20223. if (rejected)
  20224. noteStatistic(StNumIndexRejected, rejected);
  20225. if (variableFileName)
  20226. {
  20227. varFileInfo.clear();
  20228. translators.clear();
  20229. }
  20230. variableInfoPending = false;
  20231. CRoxieServerActivity::reset();
  20232. }
  20233. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20234. {
  20235. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20236. }
  20237. virtual IInputSteppingMeta * querySteppingMeta()
  20238. {
  20239. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  20240. return &steppingMeta;
  20241. return NULL;
  20242. }
  20243. protected:
  20244. const void * createKeyedLimitOnFailRow()
  20245. {
  20246. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20247. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  20248. if (outSize)
  20249. return rowBuilder.finalizeRowClear(outSize);
  20250. return NULL;
  20251. }
  20252. };
  20253. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20254. {
  20255. public:
  20256. Owned<IKeyArray> keySet;
  20257. Owned<TranslatorArray> translatorArray;
  20258. Owned<IDefRecordMeta> activityMeta;
  20259. RemoteActivityId remoteId;
  20260. bool isSimple;
  20261. bool isLocal;
  20262. bool maySkip;
  20263. bool sorted;
  20264. bool variableFileName;
  20265. bool enableFieldTranslation;
  20266. unsigned maxSeekLookahead;
  20267. Owned<const IResolvedFile> indexfile;
  20268. CRoxieServerSideCache *cache;
  20269. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20270. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20271. {
  20272. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20273. unsigned flags = indexHelper->getFlags();
  20274. sorted = (flags & TIRunordered) == 0;
  20275. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20276. rtlDataAttr indexLayoutMeta;
  20277. size32_t indexLayoutSize;
  20278. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  20279. assertex(indexLayoutSize==0);
  20280. MemoryBuffer m;
  20281. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  20282. activityMeta.setown(deserializeRecordMeta(m, true));
  20283. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  20284. translatorArray.setown(new TranslatorArray);
  20285. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20286. if (!variableFileName)
  20287. {
  20288. bool isOpt = (flags & TIRoptional) != 0;
  20289. OwnedRoxieString indexName(indexHelper->getFileName());
  20290. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20291. if (indexfile)
  20292. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  20293. }
  20294. isSimple = isLocal;
  20295. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20296. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20297. {
  20298. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20299. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20300. isSimple = true;
  20301. }
  20302. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20303. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20304. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20305. }
  20306. ~CRoxieServerBaseIndexActivityFactory()
  20307. {
  20308. delete cache;
  20309. }
  20310. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20311. {
  20312. if (indexfile)
  20313. addXrefFileInfo(reply, indexfile);
  20314. else
  20315. {
  20316. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20317. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20318. {
  20319. OwnedRoxieString indexName(indexHelper->getFileName());
  20320. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit());
  20321. if (temp)
  20322. addXrefFileInfo(reply, temp);
  20323. }
  20324. }
  20325. }
  20326. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20327. {
  20328. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20329. }
  20330. virtual IRoxieServerSideCache *queryServerSideCache() const
  20331. {
  20332. return cache;
  20333. }
  20334. virtual bool getEnableFieldTranslation() const
  20335. {
  20336. return enableFieldTranslation;
  20337. }
  20338. virtual IDefRecordMeta *queryActivityMeta() const
  20339. {
  20340. return activityMeta;
  20341. }
  20342. virtual const StatisticsMapping &queryStatsMapping() const
  20343. {
  20344. return indexStatistics;
  20345. }
  20346. };
  20347. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20348. {
  20349. public:
  20350. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20351. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20352. {
  20353. }
  20354. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20355. {
  20356. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20357. return new CRoxieServerNullActivity(this, _probeManager);
  20358. else if (isSimple && !maySkip)
  20359. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20360. else
  20361. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  20362. }
  20363. };
  20364. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20365. {
  20366. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20367. }
  20368. //--------------------------------------------------------------------------------------------------------------------------
  20369. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  20370. {
  20371. bool done;
  20372. public:
  20373. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20374. : CRoxieServerActivity(_factory, _probeManager)
  20375. {
  20376. done = false;
  20377. }
  20378. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20379. {
  20380. done = false;
  20381. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20382. }
  20383. virtual bool needsAllocator() const { return true; }
  20384. virtual const void *nextInGroup()
  20385. {
  20386. ActivityTimer t(totalCycles, timeActivities);
  20387. if (done) return NULL;
  20388. done = true;
  20389. size32_t rowSize = meta.getFixedSize();
  20390. void * nullRow = rowAllocator->createRow();
  20391. if (rowSize == 1)
  20392. *(byte *)nullRow = 0;
  20393. else
  20394. {
  20395. assertex(rowSize == sizeof(unsigned __int64));
  20396. *(unsigned __int64 *)nullRow = 0;
  20397. }
  20398. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  20399. }
  20400. };
  20401. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  20402. {
  20403. IHThorCompoundCountExtra & countHelper;
  20404. IHThorSourceCountLimit * limitHelper;
  20405. bool done;
  20406. public:
  20407. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20408. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20409. countHelper((IHThorIndexCountArg &)basehelper),
  20410. done(false)
  20411. {
  20412. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  20413. }
  20414. virtual bool needsAllocator() const { return true; }
  20415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20416. {
  20417. done = false;
  20418. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20419. choosenLimit = countHelper.getChooseNLimit();
  20420. if (limitHelper)
  20421. {
  20422. rowLimit = limitHelper->getRowLimit();
  20423. keyedLimit = limitHelper->getKeyedLimit();
  20424. }
  20425. if (!paused)
  20426. processAllKeys();
  20427. }
  20428. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20429. {
  20430. unsigned __int64 count = 0;
  20431. if (countHelper.hasFilter())
  20432. {
  20433. while (tlk->lookup(true))
  20434. {
  20435. try
  20436. {
  20437. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  20438. callback.finishedRow();
  20439. }
  20440. catch (IException *E)
  20441. {
  20442. throw makeWrappedException(E);
  20443. }
  20444. accepted++;
  20445. if (count >= choosenLimit) // MORE - what about limit?
  20446. break;
  20447. }
  20448. }
  20449. else
  20450. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  20451. if (count)
  20452. {
  20453. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  20454. if (count > choosenLimit)
  20455. count = choosenLimit;
  20456. void * recBuffer = rowAllocator->createRow();
  20457. if (meta.getFixedSize() == 1)
  20458. *(byte *)recBuffer = (byte)count;
  20459. else
  20460. {
  20461. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20462. *(unsigned __int64 *)recBuffer = count;
  20463. }
  20464. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  20465. result->append(recBuffer);
  20466. remote.injectResult(result.getClear());
  20467. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  20468. if (count >= choosenLimit)
  20469. return true;
  20470. }
  20471. return false;
  20472. }
  20473. virtual void onLimitExceeded(bool isKeyed)
  20474. {
  20475. if (traceLevel > 4)
  20476. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20477. if (isKeyed)
  20478. {
  20479. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20480. {
  20481. if (ctx->queryDebugContext())
  20482. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20483. throw makeLimitSkipException(true);
  20484. }
  20485. else
  20486. {
  20487. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  20488. limitHelper->onKeyedLimitExceeded();
  20489. }
  20490. }
  20491. else
  20492. {
  20493. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  20494. {
  20495. if (ctx->queryDebugContext())
  20496. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20497. throw makeLimitSkipException(false);
  20498. }
  20499. else
  20500. {
  20501. assertex(limitHelper);
  20502. limitHelper->onLimitExceeded();
  20503. }
  20504. }
  20505. }
  20506. virtual const void *createLimitFailRow(bool isKeyed)
  20507. {
  20508. throwUnexpected();
  20509. }
  20510. virtual const void *nextInGroup()
  20511. {
  20512. ActivityTimer t(totalCycles, timeActivities);
  20513. if (done) return NULL;
  20514. done = true;
  20515. unsigned __int64 totalCount = 0;
  20516. bool hasLimit = rowLimit != (unsigned __int64) -1;
  20517. try
  20518. {
  20519. loop
  20520. {
  20521. const void * next = remote.nextInGroup();
  20522. if (!next)
  20523. break;
  20524. if (meta.getFixedSize() == 1)
  20525. totalCount += *(byte *)next;
  20526. else
  20527. totalCount += *(unsigned __int64 *) next;
  20528. ReleaseRoxieRow(next);
  20529. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  20530. break;
  20531. }
  20532. if (totalCount > rowLimit)
  20533. {
  20534. unsigned flags = indexHelper.getFlags();
  20535. if (flags & TIRlimitskips)
  20536. totalCount = 0;
  20537. else if (flags & TIRlimitcreates)
  20538. totalCount = 1;
  20539. else
  20540. {
  20541. assertex(limitHelper);
  20542. limitHelper->onLimitExceeded();
  20543. }
  20544. }
  20545. else if (totalCount > choosenLimit)
  20546. totalCount = choosenLimit;
  20547. }
  20548. catch (IException *E)
  20549. {
  20550. if (QUERYINTERFACE(E, LimitSkipException))
  20551. {
  20552. totalCount = 0;
  20553. unsigned flags = indexHelper.getFlags();
  20554. if (E->errorCode() == KeyedLimitSkipErrorCode)
  20555. {
  20556. if (flags & TIRkeyedlimitcreates)
  20557. totalCount++;
  20558. }
  20559. else
  20560. {
  20561. if (flags & TIRlimitcreates)
  20562. totalCount++;
  20563. }
  20564. if (totalCount > choosenLimit)
  20565. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  20566. E->Release();
  20567. }
  20568. else
  20569. throw ;
  20570. }
  20571. void * result = rowAllocator->createRow();
  20572. if (meta.getFixedSize() == 1)
  20573. *(byte *)result = (byte)totalCount;
  20574. else
  20575. {
  20576. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  20577. *(unsigned __int64 *)result = totalCount;
  20578. }
  20579. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  20580. }
  20581. };
  20582. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20583. {
  20584. public:
  20585. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20586. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20587. {
  20588. }
  20589. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20590. {
  20591. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20592. return new CRoxieServerNullCountActivity(this, _probeManager);
  20593. // else if (isSimple)
  20594. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20595. else
  20596. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20597. }
  20598. };
  20599. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20600. {
  20601. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20602. }
  20603. //--------------------------------------------------------------------------------------------------------------------------
  20604. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  20605. {
  20606. IHThorIndexAggregateArg &aggregateHelper;
  20607. bool done;
  20608. public:
  20609. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20610. : CRoxieServerActivity(_factory, _probeManager),
  20611. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  20612. {
  20613. done = false;
  20614. }
  20615. virtual bool needsAllocator() const { return true; }
  20616. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20617. {
  20618. done = false;
  20619. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20620. }
  20621. virtual const void *nextInGroup()
  20622. {
  20623. ActivityTimer t(totalCycles, timeActivities);
  20624. if (done) return NULL;
  20625. done = true;
  20626. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20627. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  20628. return rowBuilder.finalizeRowClear(thisSize);
  20629. }
  20630. };
  20631. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  20632. {
  20633. IHThorCompoundAggregateExtra & aggregateHelper;
  20634. bool done;
  20635. public:
  20636. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20637. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20638. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20639. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  20640. done(false)
  20641. {
  20642. }
  20643. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20644. {
  20645. done = false;
  20646. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20647. if (!paused)
  20648. processAllKeys();
  20649. }
  20650. virtual bool needsAllocator() const { return true; }
  20651. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20652. {
  20653. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20654. while (tlk->lookup(true))
  20655. {
  20656. if (!rowBuilder.exists())
  20657. {
  20658. rowBuilder.ensureRow();
  20659. aggregateHelper.clearAggregate(rowBuilder);
  20660. }
  20661. try
  20662. {
  20663. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20664. callback.finishedRow();
  20665. }
  20666. catch (IException *E)
  20667. {
  20668. throw makeWrappedException(E);
  20669. }
  20670. accepted++;
  20671. }
  20672. if (aggregateHelper.processedAnyRows())
  20673. {
  20674. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20675. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20676. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20677. result->append(recBuffer);
  20678. remote.injectResult(result.getClear());
  20679. }
  20680. return false;
  20681. }
  20682. virtual void onLimitExceeded(bool isKeyed)
  20683. {
  20684. if (traceLevel > 4)
  20685. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20686. throwUnexpected();
  20687. }
  20688. virtual const void *createLimitFailRow(bool isKeyed)
  20689. {
  20690. throwUnexpected();
  20691. }
  20692. const void * gatherMerged()
  20693. {
  20694. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20695. const void * firstRow = remote.nextInGroup();
  20696. size32_t finalSize = 0;
  20697. if (!firstRow)
  20698. {
  20699. rowBuilder.ensureRow();
  20700. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20701. }
  20702. else
  20703. {
  20704. // NOTE need to clone this because going to modify below, could special case 1 row only
  20705. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20706. ReleaseRoxieRow(firstRow);
  20707. }
  20708. loop
  20709. {
  20710. const void * next = remote.nextInGroup();
  20711. if (!next)
  20712. break;
  20713. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20714. ReleaseRoxieRow(next);
  20715. }
  20716. return rowBuilder.finalizeRowClear(finalSize);
  20717. }
  20718. virtual const void *nextInGroup()
  20719. {
  20720. ActivityTimer t(totalCycles, timeActivities);
  20721. if (done) return NULL;
  20722. const void * ret = gatherMerged();
  20723. done = true;
  20724. return ret;
  20725. }
  20726. };
  20727. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20728. {
  20729. public:
  20730. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20731. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20732. {
  20733. }
  20734. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20735. {
  20736. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20737. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20738. // else if (isSimple)
  20739. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20740. else
  20741. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20742. }
  20743. };
  20744. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20745. {
  20746. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20747. }
  20748. //--------------------------------------------------------------------------------------------------------------------------
  20749. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20750. {
  20751. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20752. RowAggregator singleAggregator;
  20753. RowAggregator resultAggregator;
  20754. unsigned groupSegCount;
  20755. bool gathered;
  20756. bool eof;
  20757. public:
  20758. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20759. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20760. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20761. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20762. singleAggregator(aggregateHelper, aggregateHelper),
  20763. resultAggregator(aggregateHelper, aggregateHelper),
  20764. gathered(false), eof(true)
  20765. {
  20766. groupSegCount = 0;
  20767. }
  20768. IMPLEMENT_IINTERFACE
  20769. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20770. {
  20771. eof = false;
  20772. gathered= false;
  20773. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20774. groupSegCount = 0;
  20775. if (!paused)
  20776. processAllKeys();
  20777. resultAggregator.start(rowAllocator);
  20778. }
  20779. virtual bool needsAllocator() const { return true; }
  20780. virtual void reset()
  20781. {
  20782. resultAggregator.reset();
  20783. CRoxieServerIndexActivity::reset();
  20784. }
  20785. virtual void processRow(const void * next)
  20786. {
  20787. singleAggregator.addRow(next);
  20788. }
  20789. virtual void createSegmentMonitors(IKeyManager *key)
  20790. {
  20791. unsigned groupSegSize;
  20792. ThorActivityKind kind = factory->getKind();
  20793. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20794. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20795. else
  20796. groupSegSize = 0;
  20797. if (groupSegSize)
  20798. {
  20799. key->setMergeBarrier(groupSegSize);
  20800. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20801. unsigned numSegs = tlk->ordinality();
  20802. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20803. {
  20804. IKeySegmentMonitor *seg = tlk->item(segNo);
  20805. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20806. {
  20807. groupSegCount = segNo+1;
  20808. break;
  20809. }
  20810. }
  20811. assertex(groupSegCount);
  20812. }
  20813. else
  20814. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20815. }
  20816. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20817. {
  20818. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20819. singleAggregator.start(rowAllocator);
  20820. ThorActivityKind kind = factory->getKind();
  20821. while (tlk->lookup(true))
  20822. {
  20823. try
  20824. {
  20825. if (groupSegCount && !trans)
  20826. {
  20827. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20828. callback.finishedRow();
  20829. if (kind==TAKindexgroupcount)
  20830. {
  20831. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20832. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20833. }
  20834. if (!tlk->nextRange(groupSegCount))
  20835. break;
  20836. }
  20837. else
  20838. {
  20839. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20840. callback.finishedRow();
  20841. }
  20842. }
  20843. catch (IException *E)
  20844. {
  20845. throw makeWrappedException(E);
  20846. }
  20847. accepted++;
  20848. }
  20849. loop
  20850. {
  20851. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20852. if (!next)
  20853. break;
  20854. size32_t size = next->querySize();
  20855. result->append(next->finalizeRowClear());
  20856. }
  20857. remote.injectResult(result.getClear());
  20858. singleAggregator.reset();
  20859. return false;
  20860. }
  20861. virtual void onLimitExceeded(bool isKeyed)
  20862. {
  20863. if (traceLevel > 4)
  20864. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20865. throwUnexpected();
  20866. }
  20867. virtual const void *createLimitFailRow(bool isKeyed)
  20868. {
  20869. throwUnexpected();
  20870. }
  20871. void gatherMerged()
  20872. {
  20873. gathered = true;
  20874. loop
  20875. {
  20876. const void * next = remote.nextInGroup();
  20877. if (!next)
  20878. break;
  20879. resultAggregator.mergeElement(next);
  20880. ReleaseRoxieRow(next);
  20881. }
  20882. }
  20883. virtual const void *nextInGroup()
  20884. {
  20885. ActivityTimer t(totalCycles, timeActivities);
  20886. if (eof)
  20887. return NULL;
  20888. if (!gathered)
  20889. gatherMerged();
  20890. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20891. if (next)
  20892. {
  20893. processed++;
  20894. return next->finalizeRowClear();
  20895. }
  20896. eof = true;
  20897. return NULL;
  20898. }
  20899. };
  20900. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20901. {
  20902. public:
  20903. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20904. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20905. {
  20906. }
  20907. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20908. {
  20909. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20910. return new CRoxieServerNullActivity(this, _probeManager);
  20911. // else if (isSimple)
  20912. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20913. else
  20914. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20915. }
  20916. };
  20917. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20918. {
  20919. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20920. }
  20921. //--------------------------------------------------------------------------------------------------------------------------
  20922. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20923. {
  20924. IHThorCompoundNormalizeExtra & readHelper;
  20925. public:
  20926. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20927. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20928. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20929. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20930. {
  20931. }
  20932. virtual bool needsAllocator() const { return true; }
  20933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20934. {
  20935. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20936. rowLimit = readHelper.getRowLimit();
  20937. keyedLimit = readHelper.getKeyedLimit();
  20938. choosenLimit = readHelper.getChooseNLimit();
  20939. if (!paused)
  20940. processAllKeys();
  20941. }
  20942. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20943. {
  20944. unsigned keyedCount = 0;
  20945. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20946. while (tlk->lookup(true))
  20947. {
  20948. keyedCount++;
  20949. if (keyedCount > keyedLimit)
  20950. {
  20951. if (traceLevel > 4)
  20952. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20953. onLimitExceeded(true);
  20954. break;
  20955. }
  20956. size32_t transformedSize;
  20957. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20958. {
  20959. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20960. do
  20961. {
  20962. if (accepted>=choosenLimit)
  20963. break;
  20964. rowBuilder.ensureRow();
  20965. try
  20966. {
  20967. transformedSize = readHelper.transform(rowBuilder);
  20968. }
  20969. catch (IException *E)
  20970. {
  20971. throw makeWrappedException(E);
  20972. }
  20973. if (transformedSize)
  20974. {
  20975. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20976. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20977. accepted++;
  20978. }
  20979. else
  20980. rejected++;
  20981. } while (readHelper.next());
  20982. remote.injectResult(result.getClear());
  20983. callback.finishedRow();
  20984. if (accepted>=choosenLimit)
  20985. return true;
  20986. }
  20987. }
  20988. return false;
  20989. }
  20990. virtual void onLimitExceeded(bool isKeyed)
  20991. {
  20992. if (traceLevel > 4)
  20993. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20994. if (isKeyed)
  20995. {
  20996. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20997. {
  20998. if (ctx->queryDebugContext())
  20999. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21000. throw makeLimitSkipException(true);
  21001. }
  21002. else
  21003. readHelper.onKeyedLimitExceeded();
  21004. }
  21005. else
  21006. {
  21007. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  21008. {
  21009. if (ctx->queryDebugContext())
  21010. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21011. throw makeLimitSkipException(false);
  21012. }
  21013. else
  21014. readHelper.onLimitExceeded();
  21015. }
  21016. }
  21017. virtual const void *createLimitFailRow(bool isKeyed)
  21018. {
  21019. UNIMPLEMENTED;
  21020. }
  21021. };
  21022. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21023. {
  21024. public:
  21025. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21026. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  21027. {
  21028. }
  21029. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21030. {
  21031. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21032. return new CRoxieServerNullActivity(this, _probeManager);
  21033. else
  21034. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  21035. }
  21036. };
  21037. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21038. {
  21039. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21040. }
  21041. //=================================================================================
  21042. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21043. {
  21044. IHThorFetchBaseArg &helper;
  21045. IHThorFetchContext * fetchContext;
  21046. Linked<IFilePartMap> map;
  21047. CRemoteResultAdaptor remote;
  21048. RecordPullerThread puller;
  21049. bool needsRHS;
  21050. bool variableFileName;
  21051. bool isOpt;
  21052. Owned<const IResolvedFile> varFileInfo;
  21053. public:
  21054. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  21055. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  21056. {
  21057. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  21058. needsRHS = helper.transformNeedsRhs();
  21059. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21060. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  21061. }
  21062. virtual const IResolvedFile *queryVarFileInfo() const
  21063. {
  21064. return varFileInfo;
  21065. }
  21066. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21067. {
  21068. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21069. remote.onCreate(this, this, _ctx, _colocalParent);
  21070. }
  21071. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21072. {
  21073. if (idx)
  21074. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21075. puller.setInput(this, _in);
  21076. }
  21077. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21078. {
  21079. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21080. remote.onStart(parentExtractSize, parentExtract);
  21081. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21082. if (variableFileName)
  21083. {
  21084. OwnedRoxieString fname(fetchContext->getFileName());
  21085. varFileInfo.setown(resolveLFN(fname, isOpt));
  21086. if (varFileInfo)
  21087. map.setown(varFileInfo->getFileMap());
  21088. }
  21089. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  21090. }
  21091. virtual void stop(bool aborting)
  21092. {
  21093. // Called from remote, so no need to call back to it....
  21094. puller.stop(aborting);
  21095. CRoxieServerActivity::stop(aborting);
  21096. }
  21097. virtual void reset()
  21098. {
  21099. processed = remote.processed;
  21100. remote.processed = 0;
  21101. puller.reset();
  21102. if (variableFileName)
  21103. {
  21104. varFileInfo.clear();
  21105. map.clear();
  21106. }
  21107. CRoxieServerActivity::reset();
  21108. }
  21109. virtual IRoxieInput *queryOutput(unsigned idx)
  21110. {
  21111. if (idx==(unsigned)-1)
  21112. idx = 0;
  21113. return idx ? NULL : &remote;
  21114. }
  21115. virtual void processRow(const void *row)
  21116. {
  21117. // called from puller thread
  21118. offset_t rp = fetchContext->extractPosition(row);
  21119. unsigned partNo;
  21120. if (isLocalFpos(rp))
  21121. partNo = getLocalFposPart(rp) + 1;
  21122. else
  21123. partNo = map->mapOffset(rp);
  21124. if (needsRHS)
  21125. {
  21126. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  21127. RtlDynamicRowBuilder rb(extractAllocator, true);
  21128. unsigned rhsSize = helper.extractJoinFields(rb, row);
  21129. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  21130. *(offset_t *) block = rp;
  21131. block += sizeof(rp);
  21132. *(unsigned *) block = rhsSize;
  21133. block += sizeof(rhsSize);
  21134. memcpy(block, rb.row(), rhsSize);
  21135. }
  21136. else
  21137. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  21138. ReleaseRoxieRow(row);
  21139. }
  21140. void processEOG()
  21141. {
  21142. #ifdef FETCH_PRESERVES_GROUPING
  21143. UNIMPLEMENTED;
  21144. #endif
  21145. // else discard is correct
  21146. }
  21147. void processGroup(const ConstPointerArray &)
  21148. {
  21149. throwUnexpected();
  21150. }
  21151. void processDone()
  21152. {
  21153. // called from puller thread
  21154. remote.flush();
  21155. remote.senddone();
  21156. }
  21157. virtual bool fireException(IException *e)
  21158. {
  21159. return remote.fireException(e);
  21160. }
  21161. virtual void onLimitExceeded(bool isKeyed)
  21162. {
  21163. if (traceLevel > 4)
  21164. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21165. if (isKeyed)
  21166. throwUnexpected();
  21167. helper.onLimitExceeded();
  21168. }
  21169. virtual const void *createLimitFailRow(bool isKeyed)
  21170. {
  21171. UNIMPLEMENTED;
  21172. }
  21173. virtual const void *nextInGroup()
  21174. {
  21175. throwUnexpected(); // I am nobody's input
  21176. }
  21177. };
  21178. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  21179. {
  21180. RemoteActivityId remoteId;
  21181. Owned<IFilePartMap> map;
  21182. bool variableFileName;
  21183. Owned<const IResolvedFile> datafile;
  21184. public:
  21185. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21186. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  21187. {
  21188. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21189. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21190. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21191. if (!variableFileName)
  21192. {
  21193. OwnedRoxieString fname(fetchContext->getFileName());
  21194. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  21195. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  21196. true, true,
  21197. _queryFactory.queryWorkUnit()));
  21198. if (datafile)
  21199. map.setown(datafile->getFileMap());
  21200. }
  21201. }
  21202. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  21203. {
  21204. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  21205. }
  21206. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21207. {
  21208. if (datafile)
  21209. addXrefFileInfo(reply, datafile);
  21210. else
  21211. {
  21212. // Temporarily resolve the file
  21213. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  21214. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  21215. if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  21216. {
  21217. OwnedRoxieString fileName(fetchContext->getFileName());
  21218. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit());
  21219. if (temp)
  21220. addXrefFileInfo(reply, temp);
  21221. }
  21222. }
  21223. }
  21224. virtual const StatisticsMapping &queryStatsMapping() const
  21225. {
  21226. return diskStatistics;
  21227. }
  21228. };
  21229. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  21230. {
  21231. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  21232. }
  21233. // MORE - is there any point keeping this now?
  21234. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  21235. {
  21236. public:
  21237. Owned<const IResolvedFile> indexfile;
  21238. Owned<const IResolvedFile> datafile;
  21239. StringAttr fileName;
  21240. StringAttr indexName;
  21241. Owned<IKeyArray> keySet;
  21242. Owned<IFileIOArray> files;
  21243. TranslatorArray layoutTranslators;
  21244. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21245. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  21246. {
  21247. try // does not want any missing file errors to be fatal, or throw traps - just log it
  21248. {
  21249. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  21250. return; // ignore 'spills'
  21251. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  21252. ThorActivityKind kind = getActivityKind(_graphNode);
  21253. if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  21254. {
  21255. fileName.set(queryNodeFileName(_graphNode, kind));
  21256. indexName.set(queryNodeIndexName(_graphNode, kind));
  21257. if (indexName && !allFilesDynamic)
  21258. {
  21259. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  21260. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  21261. if (indexfile)
  21262. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  21263. }
  21264. if (fileName && !allFilesDynamic)
  21265. {
  21266. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  21267. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  21268. if (datafile)
  21269. {
  21270. if (isLocal)
  21271. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  21272. }
  21273. }
  21274. }
  21275. }
  21276. catch(IException *E)
  21277. {
  21278. StringBuffer errors;
  21279. E->errorMessage(errors);
  21280. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  21281. E->Release();
  21282. }
  21283. }
  21284. 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__); }
  21285. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  21286. {
  21287. if (!allFilesDynamic)
  21288. {
  21289. if (datafile)
  21290. addXrefFileInfo(reply, datafile);
  21291. if (indexfile)
  21292. addXrefFileInfo(reply, indexfile);
  21293. }
  21294. else
  21295. {
  21296. Owned<const IResolvedFile> temp;
  21297. if (fileName.length())
  21298. {
  21299. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit()));
  21300. if (temp)
  21301. addXrefFileInfo(reply, temp);
  21302. }
  21303. if (indexName.length())
  21304. {
  21305. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit()));
  21306. if (temp)
  21307. addXrefFileInfo(reply, temp);
  21308. }
  21309. }
  21310. }
  21311. };
  21312. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  21313. {
  21314. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  21315. }
  21316. //=====================================================================================================
  21317. // Keyed joins...
  21318. //
  21319. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  21320. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  21321. // 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
  21322. // the transform and returns rows that are created.
  21323. // 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)
  21324. //
  21325. //=====================================================================================================
  21326. class CJoinGroup;
  21327. interface IJoinProcessor
  21328. {
  21329. virtual void processEOG() = 0;
  21330. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  21331. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  21332. virtual bool fireException(IException *E) = 0;
  21333. virtual void processCompletedGroups() = 0;
  21334. };
  21335. //------------------------------------------------------------------------------------------------------
  21336. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  21337. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  21338. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  21339. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  21340. // per-query limits etc (Note that the pointer array block is not though).
  21341. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  21342. //
  21343. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  21344. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  21345. // initial count when created.
  21346. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  21347. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  21348. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  21349. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  21350. // remaining reference and the JoinGroup will be processed and destroyed.
  21351. //
  21352. //------------------------------------------------------------------------------------------------------
  21353. class CJoinGroup : public CInterface, implements IInterface
  21354. {
  21355. protected:
  21356. const void *left; // LHS row
  21357. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  21358. atomic_t endMarkersPending; // How many slave responses still waiting for
  21359. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  21360. unsigned lastPartNo;
  21361. unsigned pos;
  21362. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  21363. public:
  21364. #undef new
  21365. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  21366. {
  21367. return a->allocate(size, activityId);
  21368. }
  21369. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21370. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21371. #endif
  21372. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  21373. {
  21374. ReleaseRoxieRow(ptr);
  21375. }
  21376. void operator delete(void *ptr)
  21377. {
  21378. ReleaseRoxieRow(ptr);
  21379. }
  21380. public:
  21381. IMPLEMENT_IINTERFACE;
  21382. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  21383. {
  21384. #ifdef TRACE_JOINGROUPS
  21385. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  21386. #endif
  21387. candidates = 0;
  21388. lastPartNo = 0;
  21389. pos = 0;
  21390. left = _left;
  21391. groupStart = _groupStart;
  21392. if (_groupStart)
  21393. {
  21394. atomic_inc(&_groupStart->endMarkersPending);
  21395. }
  21396. atomic_set(&endMarkersPending, 1);
  21397. }
  21398. ~CJoinGroup()
  21399. {
  21400. #ifdef TRACE_JOINGROUPS
  21401. DBGLOG("Destroying joinGroup %p", this);
  21402. #endif
  21403. if (left)
  21404. {
  21405. ReleaseRoxieRow(left);
  21406. ForEachItemIn(idx, rows)
  21407. ReleaseRoxieRow(rows.item(idx));
  21408. rows.kill();
  21409. }
  21410. }
  21411. inline bool isHeadRecord() const
  21412. {
  21413. return left==NULL;
  21414. }
  21415. inline bool complete() const
  21416. {
  21417. return atomic_read(&endMarkersPending) == 0;
  21418. }
  21419. #ifdef TRACE_JOINGROUPS
  21420. inline void notePending(unsigned lineNo)
  21421. #else
  21422. inline void notePending()
  21423. #endif
  21424. {
  21425. assert(!complete());
  21426. atomic_inc(&endMarkersPending);
  21427. #ifdef TRACE_JOINGROUPS
  21428. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  21429. #endif
  21430. }
  21431. inline bool inGroup(CJoinGroup *leader) const
  21432. {
  21433. return groupStart==leader;
  21434. }
  21435. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  21436. {
  21437. // Single threaded by now
  21438. assert(complete());
  21439. return rows.item(idx);
  21440. }
  21441. #ifdef TRACE_JOINGROUPS
  21442. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  21443. #else
  21444. bool noteEndReceived(unsigned candidateCount)
  21445. #endif
  21446. {
  21447. assert(!complete());
  21448. if (candidateCount)
  21449. {
  21450. candidates += candidateCount;
  21451. }
  21452. #ifdef TRACE_JOINGROUPS
  21453. 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);
  21454. #endif
  21455. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  21456. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  21457. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  21458. CJoinGroup *localGroupStart = groupStart;
  21459. if (atomic_dec_and_test(&endMarkersPending))
  21460. {
  21461. if (localGroupStart)
  21462. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  21463. else
  21464. return true;
  21465. }
  21466. else
  21467. return false;
  21468. }
  21469. inline const void *queryLeft() const
  21470. {
  21471. return left;
  21472. }
  21473. void addRightMatch(KeyedJoinHeader *right)
  21474. {
  21475. assert(!complete());
  21476. unsigned short partNo = right->partNo;
  21477. if (partNo != lastPartNo)
  21478. {
  21479. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  21480. if (partNo > lastPartNo)
  21481. pos = rows.length();
  21482. while (pos>0)
  21483. {
  21484. if (rows.item(pos-1)->partNo <= partNo)
  21485. break;
  21486. pos--;
  21487. }
  21488. lastPartNo = partNo;
  21489. }
  21490. rows.add(right, pos);
  21491. pos++;
  21492. }
  21493. inline unsigned rowsSeen() const
  21494. {
  21495. assert(complete());
  21496. return rows.length();
  21497. }
  21498. inline unsigned candidateCount() const
  21499. {
  21500. assert(complete());
  21501. return candidates;
  21502. }
  21503. };
  21504. #ifdef TRACE_JOINGROUPS
  21505. #define notePending() notePending(__LINE__)
  21506. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  21507. #endif
  21508. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  21509. {
  21510. private:
  21511. SafeQueueOf<const void, true> ready;
  21512. public:
  21513. IHThorKeyedJoinArg &helper;
  21514. unsigned joinProcessed;
  21515. bool isFullKey;
  21516. bool eof;
  21517. bool isSimple;
  21518. bool allPulled;
  21519. ActivityTimeAccumulator totalCycles;
  21520. unsigned activityId;
  21521. RecordPullerThread &puller;
  21522. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  21523. Owned<IEngineRowAllocator> ccdRecordAllocator;
  21524. IJoinProcessor &processor;
  21525. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  21526. RecordPullerThread &_puller, IJoinProcessor &_processor)
  21527. : helper(_helper),
  21528. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  21529. isFullKey(_isFullKey),
  21530. isSimple(_isSimple),
  21531. puller(_puller),
  21532. processor(_processor),
  21533. activityId(_activity.queryId())
  21534. {
  21535. joinProcessed = 0;
  21536. allPulled = false;
  21537. eof = false;
  21538. }
  21539. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  21540. {
  21541. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  21542. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  21543. }
  21544. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21545. {
  21546. eof = false;
  21547. joinProcessed = 0;
  21548. totalCycles.totalCycles = 0;
  21549. allPulled = false;
  21550. assertex(ready.ordinality()==0);
  21551. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  21552. }
  21553. virtual void reset()
  21554. {
  21555. CRemoteResultAdaptor::reset();
  21556. while (ready.ordinality())
  21557. {
  21558. const void *goer = ready.dequeue();
  21559. if (goer)
  21560. ReleaseRoxieRow(goer);
  21561. }
  21562. while (injected.ordinality())
  21563. {
  21564. const void *goer = injected.dequeue();
  21565. if (goer)
  21566. ReleaseRoxieRow(goer);
  21567. }
  21568. }
  21569. inline void addResult(const void *row)
  21570. {
  21571. ready.enqueue(row);
  21572. }
  21573. virtual unsigned __int64 queryTotalCycles() const
  21574. {
  21575. return totalCycles.totalCycles;
  21576. }
  21577. virtual IOutputMetaData * queryOutputMeta() const
  21578. {
  21579. return owner->queryOutputMeta();
  21580. }
  21581. virtual const void *nextInGroup()
  21582. {
  21583. ActivityTimer t(totalCycles, timeActivities);
  21584. loop
  21585. {
  21586. if (eof)
  21587. return NULL;
  21588. processSlaveResults();
  21589. if (ready.ordinality())
  21590. {
  21591. const void *result = ready.dequeue();
  21592. if (result)
  21593. joinProcessed++;
  21594. return result;
  21595. }
  21596. else
  21597. eof = true;
  21598. }
  21599. }
  21600. private:
  21601. void processSlaveResults()
  21602. {
  21603. while (!ready.ordinality())
  21604. {
  21605. KeyedJoinHeader *fetchedData;
  21606. if (isSimple)
  21607. {
  21608. while (!allPulled && !injected.ordinality())
  21609. {
  21610. if (!puller.pullRecords(1))
  21611. {
  21612. puller.done();
  21613. allPulled = true;
  21614. }
  21615. }
  21616. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21617. }
  21618. else
  21619. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21620. if (fetchedData)
  21621. {
  21622. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21623. if (fetchedData->partNo == (unsigned short) -1)
  21624. {
  21625. #ifdef TRACE_JOINGROUPS
  21626. CTXLOG("Got end for group %p", thisGroup);
  21627. #endif
  21628. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21629. ReleaseRoxieRow(fetchedData);
  21630. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21631. }
  21632. else
  21633. {
  21634. #ifdef TRACE_JOINGROUPS
  21635. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21636. #endif
  21637. thisGroup->addRightMatch(fetchedData);
  21638. if (isFullKey)
  21639. {
  21640. #ifdef TRACE_JOINGROUPS
  21641. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21642. #endif
  21643. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21644. }
  21645. }
  21646. }
  21647. else
  21648. break;
  21649. }
  21650. }
  21651. };
  21652. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21653. {
  21654. IHThorKeyedJoinArg &helper;
  21655. Owned<IKeyManager> tlk;
  21656. Linked<IKeyArray> keySet;
  21657. Linked<TranslatorArray> translators;
  21658. CRemoteResultAdaptor remote;
  21659. RecordPullerThread puller;
  21660. IOutputMetaData *indexReadMeta;
  21661. IJoinProcessor *joinHandler;
  21662. bool variableIndexFileName;
  21663. bool indexReadInputRecordVariable;
  21664. bool isLocal;
  21665. Owned<IEngineRowAllocator> indexReadAllocator;
  21666. Owned<const IResolvedFile> varFileInfo;
  21667. IRoxieInput *indexReadInput;
  21668. IIndexReadActivityInfo *rootIndex;
  21669. public:
  21670. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21671. : CRoxieServerActivity(_factory, _probeManager),
  21672. helper((IHThorKeyedJoinArg &)basehelper),
  21673. tlk(createKeyManager(NULL, 0, this)),
  21674. translators(_translators),
  21675. keySet(_keySet),
  21676. remote(_remoteId, 0, helper, *this, true, true),
  21677. indexReadMeta(_indexReadMeta),
  21678. joinHandler(_joinHandler),
  21679. puller(false),
  21680. isLocal(_isLocal)
  21681. {
  21682. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  21683. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21684. indexReadInput = NULL;
  21685. rootIndex = NULL;
  21686. }
  21687. virtual const IResolvedFile *queryVarFileInfo() const
  21688. {
  21689. return varFileInfo;
  21690. }
  21691. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21692. {
  21693. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21694. remote.onCreate(this, this, _ctx, _colocalParent);
  21695. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21696. }
  21697. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21698. {
  21699. if (!idx)
  21700. puller.setInput(this, _in);
  21701. else if (idx==1)
  21702. indexReadInput = _in;
  21703. else
  21704. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21705. }
  21706. virtual void serializeExtra(MemoryBuffer &out)
  21707. {
  21708. if (helper.getJoinFlags() & JFindexfromactivity)
  21709. {
  21710. assertex(rootIndex);
  21711. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21712. indexId.serialize(out);
  21713. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21714. MemoryBuffer tmp;
  21715. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21716. if (rootIndex->queryActivity()->queryVarFileInfo())
  21717. {
  21718. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21719. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21720. }
  21721. unsigned ctxlen = tmp.length();
  21722. out.append(ctxlen).append(tmp);
  21723. }
  21724. }
  21725. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21726. {
  21727. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21728. if (indexReadInput)
  21729. {
  21730. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21731. rootIndex = indexReadInput->queryIndexReadActivity();
  21732. if (!rootIndex)
  21733. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21734. }
  21735. remote.onStart(parentExtractSize, parentExtract);
  21736. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21737. if (rootIndex)
  21738. {
  21739. varFileInfo.setown(rootIndex->getVarFileInfo());
  21740. translators.setown(rootIndex->getTranslators());
  21741. keySet.setown(rootIndex->getKeySet());
  21742. }
  21743. else if (variableIndexFileName)
  21744. {
  21745. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21746. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21747. if (varFileInfo)
  21748. {
  21749. translators.setown(new TranslatorArray);
  21750. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
  21751. }
  21752. }
  21753. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  21754. }
  21755. virtual void stop(bool aborting)
  21756. {
  21757. puller.stop(aborting);
  21758. CRoxieServerActivity::stop(aborting);
  21759. }
  21760. virtual void reset()
  21761. {
  21762. CRoxieServerActivity::reset();
  21763. puller.reset();
  21764. if (varFileInfo)
  21765. {
  21766. keySet.clear();
  21767. varFileInfo.clear();
  21768. }
  21769. }
  21770. virtual IRoxieInput *queryOutput(unsigned idx)
  21771. {
  21772. if (idx==(unsigned)-1)
  21773. idx = 0;
  21774. return idx ? NULL : &remote;
  21775. }
  21776. virtual void processRow(const void *row)
  21777. {
  21778. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21779. // called from front puller thread
  21780. // buffer up an IndexRead request
  21781. if (helper.leftCanMatch(row))
  21782. {
  21783. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21784. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21785. OwnedConstRoxieRow extracted;
  21786. if (indexReadSize)
  21787. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21788. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21789. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21790. {
  21791. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21792. if (thisBase)
  21793. {
  21794. unsigned fileNo = 0;
  21795. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21796. try
  21797. {
  21798. tlk->setKey(thisKey);
  21799. tlk->setLayoutTranslator(translators->item(fileNo));
  21800. helper.createSegmentMonitors(tlk, extracted);
  21801. if (rootIndex)
  21802. rootIndex->mergeSegmentMonitors(tlk);
  21803. tlk->finishSegmentMonitors();
  21804. tlk->reset();
  21805. loop
  21806. {
  21807. typedef const void * cvp;
  21808. if (thisKey->isTopLevelKey())
  21809. {
  21810. bool locallySorted = !thisKey->isFullySorted();
  21811. while (locallySorted || tlk->lookup(false))
  21812. {
  21813. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21814. if (locallySorted || slavePart)
  21815. {
  21816. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21817. *outputBuffer++ = jg;
  21818. if (indexReadInputRecordVariable)
  21819. {
  21820. *(unsigned *) outputBuffer = indexReadSize;
  21821. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21822. }
  21823. jg->notePending();
  21824. memcpy(outputBuffer, extracted, indexReadSize);
  21825. if (locallySorted)
  21826. {
  21827. for (unsigned i = 1; i < numChannels; i++)
  21828. jg->notePending();
  21829. break;
  21830. }
  21831. }
  21832. }
  21833. }
  21834. else
  21835. {
  21836. // MORE - this code seems to be duplicated in half keyed
  21837. unsigned accepted = 0;
  21838. unsigned rejected = 0;
  21839. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21840. jg->notePending();
  21841. unsigned candidateCount = 0;
  21842. while (tlk->lookup(true))
  21843. {
  21844. candidateCount++;
  21845. atomic_inc(&indexRecordsRead);
  21846. KLBlobProviderAdapter adapter(tlk);
  21847. offset_t recptr;
  21848. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21849. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21850. {
  21851. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21852. rhs->fpos = recptr;
  21853. rhs->thisGroup = jg;
  21854. rhs->partNo = partNo;
  21855. result->append(rhs);
  21856. }
  21857. else
  21858. {
  21859. rejected++;
  21860. atomic_inc(&postFiltered);
  21861. }
  21862. }
  21863. // output an end marker for the matches to this group
  21864. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21865. endMarker->fpos = (offset_t) candidateCount;
  21866. endMarker->thisGroup = jg;
  21867. endMarker->partNo = (unsigned short) -1;
  21868. result->append(endMarker);
  21869. remote.injectResult(result.getClear());
  21870. if (accepted)
  21871. noteStatistic(StNumIndexAccepted, accepted);
  21872. if (rejected)
  21873. noteStatistic(StNumIndexRejected, rejected);
  21874. }
  21875. if (++fileNo < thisBase->numParts())
  21876. {
  21877. thisKey = thisBase->queryPart(fileNo);
  21878. tlk->setKey(thisKey);
  21879. tlk->setLayoutTranslator(translators->item(fileNo));
  21880. tlk->reset();
  21881. }
  21882. else
  21883. break;
  21884. }
  21885. tlk->releaseSegmentMonitors();
  21886. tlk->setKey(NULL);
  21887. }
  21888. catch (...)
  21889. {
  21890. tlk->releaseSegmentMonitors();
  21891. tlk->setKey(NULL);
  21892. throw;
  21893. }
  21894. }
  21895. }
  21896. joinHandler->noteEndReceived(jg, 0);
  21897. }
  21898. else
  21899. {
  21900. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21901. }
  21902. }
  21903. void processGroup(const ConstPointerArray &)
  21904. {
  21905. throwUnexpected();
  21906. }
  21907. virtual void processEOG()
  21908. {
  21909. joinHandler->processEOG();
  21910. }
  21911. virtual void processDone()
  21912. {
  21913. // called from puller thread
  21914. remote.flush();
  21915. remote.senddone();
  21916. }
  21917. virtual void onLimitExceeded(bool isKeyed)
  21918. {
  21919. if (traceLevel > 4)
  21920. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21921. if (isKeyed)
  21922. throwUnexpected();
  21923. helper.onLimitExceeded();
  21924. }
  21925. virtual const void *createLimitFailRow(bool isKeyed)
  21926. {
  21927. throwUnexpected();
  21928. }
  21929. virtual bool fireException(IException *e)
  21930. {
  21931. // called from puller thread on failure
  21932. remote.fireException(LINK(e));
  21933. return joinHandler->fireException(e);
  21934. }
  21935. virtual const void *nextInGroup()
  21936. {
  21937. throwUnexpected(); // I am nobody's input
  21938. }
  21939. };
  21940. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21941. {
  21942. protected:
  21943. IHThorKeyedJoinArg &helper;
  21944. KeyedJoinRemoteAdaptor remote;
  21945. RecordPullerThread puller;
  21946. OwnedConstRoxieRow defaultRight;
  21947. Owned<IEngineRowAllocator> defaultRightAllocator;
  21948. unsigned joinFlags;
  21949. unsigned atMost;
  21950. unsigned atmostsTriggered;
  21951. unsigned abortLimit;
  21952. unsigned keepLimit;
  21953. bool limitFail;
  21954. bool limitOnFail;
  21955. bool preserveGroups;
  21956. bool cloneLeft;
  21957. bool isSimple;
  21958. bool isLocal;
  21959. ThorActivityKind activityKind;
  21960. CJoinGroup *groupStart;
  21961. CriticalSection groupsCrit;
  21962. QueueOf<CJoinGroup, false> groups;
  21963. IRoxieInput *indexReadInput;
  21964. IIndexReadActivityInfo *rootIndex;
  21965. void createDefaultRight()
  21966. {
  21967. if (!defaultRight)
  21968. {
  21969. if (!defaultRightAllocator)
  21970. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21971. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21972. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21973. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21974. }
  21975. }
  21976. public:
  21977. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21978. , bool isFull, bool _isSimple, bool _isLocal)
  21979. : CRoxieServerActivity(_factory, _probeManager),
  21980. helper((IHThorKeyedJoinArg &)basehelper),
  21981. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21982. joinFlags(_joinFlags),
  21983. preserveGroups(meta.isGrouped()),
  21984. puller(false),
  21985. isSimple(_isSimple),
  21986. isLocal(_isLocal),
  21987. abortLimit(0),
  21988. keepLimit(0),
  21989. atMost(0),
  21990. limitFail(false),
  21991. limitOnFail(false),
  21992. cloneLeft(false)
  21993. {
  21994. groupStart = NULL;
  21995. activityKind = _factory->getKind();
  21996. indexReadInput = NULL;
  21997. rootIndex = NULL;
  21998. atmostsTriggered = 0;
  21999. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  22000. }
  22001. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22002. {
  22003. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  22004. remote.onCreate(this, this, _ctx, _colocalParent);
  22005. }
  22006. virtual void setInput(unsigned idx, IRoxieInput *_in)
  22007. {
  22008. if (!idx)
  22009. puller.setInput(this, _in);
  22010. else if (idx==1)
  22011. indexReadInput = _in;
  22012. else
  22013. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  22014. }
  22015. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22016. {
  22017. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22018. if (indexReadInput)
  22019. {
  22020. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22021. rootIndex = indexReadInput->queryIndexReadActivity();
  22022. if (!rootIndex)
  22023. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22024. }
  22025. remote.onStart(parentExtractSize, parentExtract);
  22026. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22027. atmostsTriggered = 0;
  22028. atMost = helper.getJoinLimit();
  22029. if (atMost == 0) atMost = (unsigned)-1;
  22030. abortLimit = helper.getMatchAbortLimit();
  22031. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  22032. keepLimit = helper.getKeepLimit();
  22033. if (keepLimit == 0) keepLimit = (unsigned)-1;
  22034. getLimitType(joinFlags, limitFail, limitOnFail);
  22035. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  22036. if (joinFlags & JFleftouter)
  22037. createDefaultRight();
  22038. }
  22039. virtual void stop(bool aborting)
  22040. {
  22041. puller.stop(aborting);
  22042. if (indexReadInput)
  22043. indexReadInput->stop(aborting);
  22044. CRoxieServerActivity::stop(aborting);
  22045. }
  22046. virtual unsigned __int64 queryLocalCycles() const
  22047. {
  22048. __int64 localCycles = remote.totalCycles.totalCycles;
  22049. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  22050. if (localCycles < 0)
  22051. localCycles = 0;
  22052. return localCycles;
  22053. }
  22054. virtual IRoxieInput *queryInput(unsigned idx)
  22055. {
  22056. if (idx==0)
  22057. return puller.queryInput();
  22058. else if (idx==1)
  22059. return indexReadInput;
  22060. else
  22061. return NULL;
  22062. }
  22063. virtual void reset()
  22064. {
  22065. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  22066. remote.totalCycles.totalCycles = 0;
  22067. processed = remote.joinProcessed;
  22068. remote.joinProcessed = 0;
  22069. defaultRight.clear();
  22070. if (indexReadInput)
  22071. indexReadInput->reset();
  22072. if (atmostsTriggered)
  22073. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  22074. CRoxieServerActivity::reset();
  22075. puller.reset();
  22076. while (groups.ordinality())
  22077. {
  22078. ::Release(groups.dequeue());
  22079. }
  22080. }
  22081. virtual IRoxieInput *queryOutput(unsigned idx)
  22082. {
  22083. if (idx==(unsigned)-1)
  22084. idx = 0;
  22085. return idx ? NULL : &remote;
  22086. }
  22087. #undef new
  22088. virtual CJoinGroup *createJoinGroup(const void *row)
  22089. {
  22090. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  22091. CriticalBlock c(groupsCrit);
  22092. if (preserveGroups && !groupStart)
  22093. {
  22094. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  22095. groups.enqueue(groupStart);
  22096. }
  22097. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  22098. groups.enqueue(jg);
  22099. return jg;
  22100. }
  22101. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  22102. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  22103. #endif
  22104. void endGroup()
  22105. {
  22106. CriticalBlock c(groupsCrit);
  22107. if (groupStart)
  22108. noteEndReceived(groupStart, 0);
  22109. groupStart = NULL;
  22110. }
  22111. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  22112. {
  22113. if (jg->noteEndReceived(candidateCount))
  22114. processCompletedGroups();
  22115. }
  22116. void processCompletedGroups()
  22117. {
  22118. loop
  22119. {
  22120. CriticalBlock c(groupsCrit);
  22121. if (!groups.head()->complete())
  22122. break;
  22123. Owned<CJoinGroup> head = groups.dequeue();
  22124. if (preserveGroups)
  22125. {
  22126. assert(head->isHeadRecord());
  22127. assert(groups.head()->inGroup(head));
  22128. unsigned joinGroupSize = 0;
  22129. while (groups.ordinality() && groups.head()->inGroup(head))
  22130. {
  22131. Owned<CJoinGroup> finger = groups.dequeue();
  22132. joinGroupSize += doJoinGroup(finger);
  22133. }
  22134. if (joinGroupSize)
  22135. remote.addResult(NULL);
  22136. }
  22137. else
  22138. doJoinGroup(head);
  22139. if (!groups.ordinality())
  22140. break;
  22141. }
  22142. }
  22143. void failLimit(const void * left)
  22144. {
  22145. helper.onMatchAbortLimitExceeded();
  22146. CommonXmlWriter xmlwrite(0);
  22147. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  22148. {
  22149. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  22150. }
  22151. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  22152. }
  22153. virtual bool needsAllocator() const { return true; }
  22154. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  22155. {
  22156. if (cloneLeft && !except)
  22157. {
  22158. LinkRoxieRow(left);
  22159. remote.addResult((void *) left);
  22160. return 1;
  22161. }
  22162. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22163. unsigned outSize;
  22164. try
  22165. {
  22166. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  22167. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  22168. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  22169. }
  22170. catch (IException *E)
  22171. {
  22172. throw makeWrappedException(E);
  22173. }
  22174. if (outSize)
  22175. {
  22176. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  22177. remote.addResult(shrunk);
  22178. return 1;
  22179. }
  22180. else
  22181. return 0;
  22182. }
  22183. unsigned doJoinGroup(CJoinGroup *jg)
  22184. {
  22185. unsigned matched = jg->rowsSeen();
  22186. unsigned added = 0;
  22187. const void *left = jg->queryLeft();
  22188. if (jg->candidateCount() > abortLimit)
  22189. {
  22190. if (limitFail)
  22191. failLimit(left);
  22192. if (ctx->queryDebugContext())
  22193. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22194. if (limitOnFail)
  22195. {
  22196. Owned<IException> except;
  22197. try
  22198. {
  22199. failLimit(left);
  22200. }
  22201. catch(IException * e)
  22202. {
  22203. except.setown(e);
  22204. }
  22205. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  22206. }
  22207. }
  22208. else if (!matched || jg->candidateCount() > atMost)
  22209. {
  22210. if (jg->candidateCount() > atMost)
  22211. atmostsTriggered++;
  22212. switch (joinFlags & JFtypemask)
  22213. {
  22214. case JFleftouter:
  22215. case JFleftonly:
  22216. switch (activityKind)
  22217. {
  22218. case TAKkeyedjoin:
  22219. case TAKkeyeddenormalizegroup:
  22220. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  22221. break;
  22222. case TAKkeyeddenormalize:
  22223. LinkRoxieRow(left);
  22224. remote.addResult((void *) left);
  22225. added++;
  22226. break;
  22227. }
  22228. break;
  22229. }
  22230. }
  22231. else if (!(joinFlags & JFexclude))
  22232. {
  22233. unsigned idx = 0;
  22234. switch (activityKind)
  22235. {
  22236. case TAKkeyedjoin:
  22237. while (idx < matched)
  22238. {
  22239. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22240. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
  22241. if (added==keepLimit)
  22242. break;
  22243. idx++;
  22244. }
  22245. break;
  22246. case TAKkeyeddenormalize:
  22247. {
  22248. OwnedConstRoxieRow newLeft;
  22249. newLeft.set(left);
  22250. unsigned rowSize = 0;
  22251. unsigned rightAdded = 0;
  22252. while (idx < matched)
  22253. {
  22254. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22255. try
  22256. {
  22257. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22258. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  22259. if (transformedSize)
  22260. {
  22261. rowSize = transformedSize;
  22262. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  22263. rightAdded++;
  22264. if (rightAdded==keepLimit)
  22265. break;
  22266. }
  22267. idx++;
  22268. }
  22269. catch (IException *E)
  22270. {
  22271. throw makeWrappedException(E);
  22272. }
  22273. }
  22274. if (rowSize)
  22275. {
  22276. remote.addResult(newLeft.getClear());
  22277. added++;
  22278. }
  22279. }
  22280. break;
  22281. case TAKkeyeddenormalizegroup:
  22282. {
  22283. ConstPointerArray extractedRows;
  22284. while (idx < matched && idx < keepLimit)
  22285. {
  22286. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  22287. extractedRows.append((void *) &rhs->rhsdata);
  22288. idx++;
  22289. }
  22290. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  22291. }
  22292. break;
  22293. }
  22294. }
  22295. return added;
  22296. }
  22297. virtual void processDone()
  22298. {
  22299. // called from puller thread
  22300. remote.flush();
  22301. remote.senddone();
  22302. }
  22303. virtual void onLimitExceeded(bool isKeyed)
  22304. {
  22305. if (traceLevel > 4)
  22306. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22307. if (isKeyed)
  22308. throwUnexpected();
  22309. helper.onLimitExceeded();
  22310. }
  22311. virtual const void *createLimitFailRow(bool isKeyed)
  22312. {
  22313. throwUnexpected();
  22314. }
  22315. virtual bool fireException(IException *e)
  22316. {
  22317. // called from puller thread on failure
  22318. return remote.fireException(e);
  22319. }
  22320. virtual const void *nextInGroup()
  22321. {
  22322. throwUnexpected(); // I am nobody's input
  22323. }
  22324. };
  22325. #ifdef _MSC_VER
  22326. #pragma warning ( push )
  22327. #pragma warning ( disable: 4355 )
  22328. #endif
  22329. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22330. {
  22331. CRoxieServerFullKeyedJoinHead head;
  22332. Owned<IEngineRowAllocator> fetchInputAllocator;
  22333. Linked<IFilePartMap> map;
  22334. bool variableFetchFileName;
  22335. Owned<const IResolvedFile> varFetchFileInfo;
  22336. CachedOutputMetaData fetchInputFields;
  22337. public:
  22338. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  22339. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  22340. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  22341. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  22342. map(_map)
  22343. {
  22344. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  22345. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22346. }
  22347. virtual const IResolvedFile *queryVarFileInfo() const
  22348. {
  22349. return varFetchFileInfo;
  22350. }
  22351. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22352. {
  22353. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22354. head.onCreate(_ctx, _colocalParent);
  22355. fetchInputFields.set(helper.queryFetchInputRecordSize());
  22356. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  22357. }
  22358. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22359. {
  22360. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22361. if (variableFetchFileName)
  22362. {
  22363. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22364. OwnedRoxieString fname(helper.getFileName());
  22365. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  22366. if (varFetchFileInfo)
  22367. map.setown(varFetchFileInfo->getFileMap());
  22368. }
  22369. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  22370. }
  22371. virtual void setInput(unsigned idx, IRoxieInput *in)
  22372. {
  22373. head.setInput(idx, in);
  22374. }
  22375. virtual void processRow(const void *_rhs)
  22376. {
  22377. // called from puller thread
  22378. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  22379. CJoinGroup *jg = rhs->thisGroup;
  22380. if (rhs->partNo != (unsigned short) -1)
  22381. {
  22382. unsigned partNo = map->mapOffset(rhs->fpos);
  22383. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  22384. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  22385. if (fetchInputFields.isVariableSize())
  22386. {
  22387. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  22388. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22389. ReleaseRoxieRow(rhs);
  22390. jg->notePending();
  22391. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  22392. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  22393. }
  22394. else
  22395. {
  22396. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  22397. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  22398. ReleaseRoxieRow(rhs);
  22399. jg->notePending();
  22400. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  22401. }
  22402. }
  22403. else
  22404. {
  22405. unsigned candidateCount = (unsigned) rhs->fpos;
  22406. // CTXLOG("Full keyed join - all results back from index");
  22407. ReleaseRoxieRow(rhs);
  22408. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  22409. }
  22410. }
  22411. virtual void processEOG()
  22412. {
  22413. // called from front puller thread
  22414. if (preserveGroups)
  22415. endGroup();
  22416. }
  22417. void processGroup(const ConstPointerArray &)
  22418. {
  22419. throwUnexpected();
  22420. }
  22421. };
  22422. #ifdef _MSC_VER
  22423. #pragma warning ( pop )
  22424. #endif
  22425. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  22426. {
  22427. IOutputMetaData *indexReadMeta;
  22428. Owned<IEngineRowAllocator> indexReadAllocator;
  22429. Owned<IKeyManager> tlk;
  22430. bool variableIndexFileName;
  22431. bool indexReadInputRecordVariable;
  22432. Owned<const IResolvedFile> varFileInfo;
  22433. Linked<TranslatorArray> translators;
  22434. Linked<IKeyArray> keySet;
  22435. Owned<IOutputMetaData> joinPrefixedMeta;
  22436. Owned<IEngineRowAllocator> joinFieldsAllocator;
  22437. public:
  22438. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  22439. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  22440. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  22441. indexReadMeta(_indexReadMeta),
  22442. tlk(createKeyManager(NULL, 0, this)),
  22443. keySet(_keySet),
  22444. translators(_translators)
  22445. {
  22446. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22447. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22448. }
  22449. virtual void serializeExtra(MemoryBuffer &out)
  22450. {
  22451. if (helper.getJoinFlags() & JFindexfromactivity)
  22452. {
  22453. assertex(rootIndex);
  22454. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22455. indexId.serialize(out);
  22456. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22457. MemoryBuffer tmp;
  22458. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22459. if (rootIndex->queryActivity()->queryVarFileInfo())
  22460. {
  22461. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22462. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22463. }
  22464. unsigned ctxlen = tmp.length();
  22465. out.append(ctxlen).append(tmp);
  22466. }
  22467. }
  22468. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  22469. {
  22470. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  22471. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  22472. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  22473. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  22474. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  22475. }
  22476. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22477. {
  22478. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  22479. if (rootIndex)
  22480. {
  22481. varFileInfo.setown(rootIndex->getVarFileInfo());
  22482. translators.setown(rootIndex->getTranslators());
  22483. keySet.setown(rootIndex->getKeySet());
  22484. }
  22485. else if (variableIndexFileName)
  22486. {
  22487. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22488. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22489. if (varFileInfo)
  22490. {
  22491. translators.setown(new TranslatorArray);
  22492. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
  22493. }
  22494. }
  22495. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  22496. }
  22497. virtual const IResolvedFile *queryVarFileInfo() const
  22498. {
  22499. return varFileInfo;
  22500. }
  22501. virtual void reset()
  22502. {
  22503. CRoxieServerKeyedJoinBase::reset();
  22504. if (varFileInfo)
  22505. {
  22506. keySet.clear();
  22507. varFileInfo.clear();
  22508. }
  22509. }
  22510. virtual void processRow(const void *row)
  22511. {
  22512. // called from front puller thread
  22513. // buffer up an IndexRead request
  22514. if (helper.leftCanMatch(row) && keySet)
  22515. {
  22516. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  22517. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  22518. OwnedConstRoxieRow extracted;
  22519. if (indexReadRecordSize)
  22520. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  22521. CJoinGroup *jg = createJoinGroup(row);
  22522. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  22523. {
  22524. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  22525. if (thisBase)
  22526. {
  22527. unsigned fileNo = 0;
  22528. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  22529. tlk->setKey(thisKey);
  22530. tlk->setLayoutTranslator(translators->item(fileNo));
  22531. helper.createSegmentMonitors(tlk, extracted);
  22532. if (rootIndex)
  22533. rootIndex->mergeSegmentMonitors(tlk);
  22534. tlk->finishSegmentMonitors();
  22535. try
  22536. {
  22537. tlk->reset();
  22538. loop
  22539. {
  22540. typedef const void * cvp;
  22541. if (thisKey && thisKey->isTopLevelKey())
  22542. {
  22543. bool locallySorted = (!thisKey->isFullySorted());
  22544. while (locallySorted || tlk->lookup(false))
  22545. {
  22546. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  22547. if (locallySorted || slavePart)
  22548. {
  22549. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  22550. *outputBuffer++ = jg;
  22551. if (indexReadInputRecordVariable)
  22552. {
  22553. *(unsigned *) outputBuffer = indexReadRecordSize;
  22554. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  22555. }
  22556. jg->notePending();
  22557. memcpy(outputBuffer, extracted, indexReadRecordSize);
  22558. if (locallySorted)
  22559. {
  22560. for (unsigned i = 1; i < numChannels; i++)
  22561. jg->notePending();
  22562. break;
  22563. }
  22564. }
  22565. }
  22566. }
  22567. else
  22568. {
  22569. unsigned accepted = 0;
  22570. unsigned rejected = 0;
  22571. Owned<CRowArrayMessageResult> result;
  22572. if (!isSimple)
  22573. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22574. // MORE - This code seems to be duplicated in keyedJoinHead
  22575. jg->notePending();
  22576. unsigned candidateCount = 0;
  22577. while (tlk->lookup(true))
  22578. {
  22579. candidateCount++;
  22580. atomic_inc(&indexRecordsRead);
  22581. KLBlobProviderAdapter adapter(tlk);
  22582. offset_t recptr;
  22583. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22584. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22585. {
  22586. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22587. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22588. accepted++;
  22589. KLBlobProviderAdapter adapter(tlk);
  22590. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22591. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22592. rec->fpos = recptr;
  22593. rec->thisGroup = jg;
  22594. rec->partNo = partNo;
  22595. if (isSimple)
  22596. remote.injected.enqueue(rec);
  22597. else
  22598. result->append(rec);
  22599. }
  22600. else
  22601. {
  22602. rejected++;
  22603. atomic_inc(&postFiltered);
  22604. }
  22605. }
  22606. // output an end marker for the matches to this group
  22607. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22608. rec->fpos = (offset_t) candidateCount;
  22609. rec->thisGroup = jg;
  22610. rec->partNo = (unsigned short) -1;
  22611. if (isSimple)
  22612. remote.injected.enqueue(rec);
  22613. else
  22614. {
  22615. result->append(rec);
  22616. remote.injectResult(result.getClear());
  22617. }
  22618. if (accepted)
  22619. noteStatistic(StNumIndexAccepted, accepted);
  22620. if (rejected)
  22621. noteStatistic(StNumIndexRejected, rejected);
  22622. }
  22623. if (++fileNo < thisBase->numParts())
  22624. {
  22625. thisKey = thisBase->queryPart(fileNo);
  22626. tlk->setKey(thisKey);
  22627. tlk->setLayoutTranslator(translators->item(fileNo));
  22628. tlk->reset();
  22629. }
  22630. else
  22631. break;
  22632. }
  22633. tlk->releaseSegmentMonitors();
  22634. tlk->setKey(NULL);
  22635. }
  22636. catch (...)
  22637. {
  22638. tlk->releaseSegmentMonitors();
  22639. tlk->setKey(NULL);
  22640. throw;
  22641. }
  22642. }
  22643. }
  22644. noteEndReceived(jg, 0);
  22645. }
  22646. else
  22647. {
  22648. noteEndReceived(createJoinGroup(row), 0);
  22649. }
  22650. }
  22651. virtual void processEOG()
  22652. {
  22653. // called from front puller thread
  22654. if (preserveGroups)
  22655. endGroup();
  22656. }
  22657. void processGroup(const ConstPointerArray &)
  22658. {
  22659. throwUnexpected();
  22660. }
  22661. };
  22662. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22663. {
  22664. Owned<const IResolvedFile> indexfile;
  22665. Owned<const IResolvedFile> datafile;
  22666. Owned<IKeyArray> keySet;
  22667. Owned<TranslatorArray> translatorArray;
  22668. Owned<IDefRecordMeta> activityMeta;
  22669. RemoteActivityId headId;
  22670. RemoteActivityId tailId;
  22671. IOutputMetaData *indexReadMeta;
  22672. Owned<IFilePartMap> map;
  22673. Owned<IFileIOArray> files;
  22674. unsigned joinFlags;
  22675. bool isHalfKeyed;
  22676. bool isLocal;
  22677. bool enableFieldTranslation;
  22678. bool variableFetchFileName;
  22679. bool variableIndexFileName;
  22680. bool isSimple;
  22681. public:
  22682. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22683. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22684. {
  22685. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22686. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22687. isSimple = isLocal;
  22688. rtlDataAttr indexLayoutMeta;
  22689. size32_t indexLayoutSize;
  22690. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22691. assertex(indexLayoutSize== 0);
  22692. MemoryBuffer m;
  22693. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22694. activityMeta.setown(deserializeRecordMeta(m, true));
  22695. enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
  22696. translatorArray.setown(new TranslatorArray);
  22697. joinFlags = helper->getJoinFlags();
  22698. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22699. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22700. if (!variableIndexFileName)
  22701. {
  22702. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22703. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22704. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  22705. if (indexfile)
  22706. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22707. }
  22708. if (keySet && keySet->length()==1 && !isSimple)
  22709. {
  22710. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22711. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  22712. isSimple = true;
  22713. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22714. }
  22715. if (!simpleLocalKeyedJoins)
  22716. isSimple = false;
  22717. isHalfKeyed = !helper->diskAccessRequired();
  22718. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22719. if (!isHalfKeyed && !variableFetchFileName)
  22720. {
  22721. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22722. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit()));
  22723. if (datafile)
  22724. {
  22725. if (isLocal)
  22726. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22727. else
  22728. map.setown(datafile->getFileMap());
  22729. }
  22730. }
  22731. }
  22732. virtual bool getEnableFieldTranslation() const
  22733. {
  22734. return enableFieldTranslation;
  22735. }
  22736. virtual IDefRecordMeta *queryActivityMeta() const
  22737. {
  22738. return activityMeta;
  22739. }
  22740. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22741. {
  22742. if (isHalfKeyed)
  22743. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22744. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22745. else
  22746. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22747. headId, keySet, translatorArray, indexReadMeta,
  22748. tailId, map, joinFlags, isLocal);
  22749. }
  22750. virtual const StatisticsMapping &queryStatsMapping() const
  22751. {
  22752. return keyedJoinStatistics;
  22753. }
  22754. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22755. {
  22756. if (datafile)
  22757. addXrefFileInfo(reply, datafile);
  22758. if (indexfile)
  22759. addXrefFileInfo(reply, indexfile);
  22760. }
  22761. };
  22762. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22763. {
  22764. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22765. }
  22766. //=================================================================================
  22767. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22768. {
  22769. protected:
  22770. Owned<ISoapCallHelper> soaphelper;
  22771. IHThorSoapActionArg & helper;
  22772. StringBuffer authToken;
  22773. bool eof;
  22774. CriticalSection crit;
  22775. ClientCertificate *pClientCert;
  22776. public:
  22777. IMPLEMENT_IINTERFACE;
  22778. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22779. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22780. {
  22781. eof = false;
  22782. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22783. pClientCert = &clientCert;
  22784. else
  22785. pClientCert = NULL;
  22786. }
  22787. // ISoapCallRowProvider
  22788. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22789. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22790. virtual const void * getNextRow() { return NULL; };
  22791. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22793. {
  22794. eof = false;
  22795. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22796. authToken.append(ctx->queryAuthToken());
  22797. }
  22798. virtual void reset()
  22799. {
  22800. // MORE - Shouldn't we make sure thread is stopped etc???
  22801. soaphelper.clear();
  22802. CRoxieServerActivity::reset();
  22803. }
  22804. // IRoxieAbortMonitor
  22805. virtual void checkForAbort() { checkAbort(); }
  22806. };
  22807. //---------------------------------------------------------------------------
  22808. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22809. {
  22810. IHThorSoapCallArg & callHelper;
  22811. public:
  22812. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22813. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22814. {
  22815. }
  22816. virtual IHThorSoapCallArg * queryCallHelper()
  22817. {
  22818. return &callHelper;
  22819. }
  22820. virtual bool needsAllocator() const { return true; }
  22821. virtual const void *nextInGroup()
  22822. {
  22823. ActivityTimer t(totalCycles, timeActivities);
  22824. if(eof) return NULL;
  22825. if (soaphelper == NULL)
  22826. {
  22827. if (factory->getKind()==TAKhttp_rowdataset)
  22828. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22829. else
  22830. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  22831. soaphelper->start();
  22832. }
  22833. OwnedConstRoxieRow ret = soaphelper->getRow();
  22834. if (!ret)
  22835. {
  22836. eof = true;
  22837. return NULL;
  22838. }
  22839. ++processed;
  22840. return ret.getClear();
  22841. }
  22842. };
  22843. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22844. {
  22845. public:
  22846. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22847. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22848. {
  22849. }
  22850. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22851. {
  22852. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22853. }
  22854. };
  22855. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22856. {
  22857. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22858. }
  22859. //---------------------------------------------------------------------------
  22860. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22861. {
  22862. public:
  22863. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22864. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22865. {}
  22866. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22867. {
  22868. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22869. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  22870. soaphelper->start();
  22871. soaphelper->waitUntilDone();
  22872. IException *e = soaphelper->getError();
  22873. soaphelper.clear();
  22874. if (e)
  22875. throw e;
  22876. }
  22877. virtual IRoxieInput *queryOutput(unsigned idx)
  22878. {
  22879. return NULL;
  22880. }
  22881. virtual const void *nextInGroup()
  22882. {
  22883. throwUnexpected(); // I am nobody's input
  22884. }
  22885. };
  22886. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22887. {
  22888. bool isRoot;
  22889. public:
  22890. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22891. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22892. {
  22893. }
  22894. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22895. {
  22896. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22897. }
  22898. virtual bool isSink() const
  22899. {
  22900. return isRoot;
  22901. }
  22902. };
  22903. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22904. {
  22905. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22906. }
  22907. //---------------------------------------------------------------------------
  22908. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22909. {
  22910. IHThorSoapCallArg & callHelper;
  22911. public:
  22912. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22913. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22914. {
  22915. }
  22916. virtual IHThorSoapCallArg * queryCallHelper()
  22917. {
  22918. return &callHelper;
  22919. }
  22920. virtual const void *getNextRow()
  22921. {
  22922. CriticalBlock b(crit);
  22923. const void *nextrec = input->nextInGroup();
  22924. if (!nextrec)
  22925. {
  22926. nextrec = input->nextInGroup();
  22927. }
  22928. return nextrec;
  22929. }
  22930. virtual bool needsAllocator() const { return true; }
  22931. virtual const void *nextInGroup()
  22932. {
  22933. ActivityTimer t(totalCycles, timeActivities);
  22934. if(eof) return NULL;
  22935. if (soaphelper == NULL)
  22936. {
  22937. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  22938. soaphelper->start();
  22939. }
  22940. OwnedConstRoxieRow ret = soaphelper->getRow();
  22941. if (!ret)
  22942. {
  22943. eof = true;
  22944. return NULL;
  22945. }
  22946. ++processed;
  22947. return ret.getClear();
  22948. }
  22949. };
  22950. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22951. {
  22952. public:
  22953. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22954. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22955. {
  22956. }
  22957. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22958. {
  22959. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22960. }
  22961. };
  22962. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22963. {
  22964. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22965. }
  22966. //---------------------------------------------------------------------------
  22967. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22968. {
  22969. public:
  22970. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22971. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22972. {}
  22973. virtual const void *getNextRow()
  22974. {
  22975. CriticalBlock b(crit);
  22976. const void *nextrec = input->nextInGroup();
  22977. if (!nextrec)
  22978. {
  22979. nextrec = input->nextInGroup();
  22980. }
  22981. if (nextrec)
  22982. processed++;
  22983. return nextrec;
  22984. }
  22985. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22986. {
  22987. try
  22988. {
  22989. start(parentExtractSize, parentExtract, false);
  22990. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  22991. soaphelper->start();
  22992. soaphelper->waitUntilDone();
  22993. IException *e = soaphelper->getError();
  22994. soaphelper.clear();
  22995. if (e)
  22996. throw e;
  22997. stop(false);
  22998. }
  22999. catch (IException *E)
  23000. {
  23001. ctx->notifyAbort(E);
  23002. stop(true);
  23003. throw;
  23004. }
  23005. catch(...)
  23006. {
  23007. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  23008. ctx->notifyAbort(E);
  23009. stop(true);
  23010. throw;
  23011. }
  23012. }
  23013. virtual IRoxieInput *queryOutput(unsigned idx)
  23014. {
  23015. return NULL;
  23016. }
  23017. virtual const void *nextInGroup()
  23018. {
  23019. throwUnexpected(); // I am nobody's input
  23020. }
  23021. };
  23022. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  23023. {
  23024. bool isRoot;
  23025. public:
  23026. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23027. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  23028. {
  23029. }
  23030. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  23031. {
  23032. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  23033. }
  23034. virtual bool isSink() const
  23035. {
  23036. return isRoot;
  23037. }
  23038. };
  23039. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  23040. {
  23041. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  23042. }
  23043. //=====================================================================================================
  23044. class CGraphResults : public CInterface, implements IRoxieGraphResults
  23045. {
  23046. IArrayOf<IGraphResult> results;
  23047. CriticalSection cs;
  23048. IGraphResult & select(unsigned idx)
  23049. {
  23050. CriticalBlock procedure(cs);
  23051. if (idx >= results.ordinality())
  23052. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  23053. return results.item(idx);
  23054. }
  23055. public:
  23056. IMPLEMENT_IINTERFACE
  23057. void clear()
  23058. {
  23059. CriticalBlock procedure(cs);
  23060. results.kill();
  23061. }
  23062. IRoxieInput * createIterator(unsigned id)
  23063. {
  23064. return select(id).createIterator();
  23065. }
  23066. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23067. {
  23068. select(id).getLinkedResult(count, ret);
  23069. }
  23070. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23071. {
  23072. select(id).getLinkedResult(count, ret);
  23073. }
  23074. virtual const void * getLinkedRowResult(unsigned id)
  23075. {
  23076. return select(id).getLinkedRowResult();
  23077. }
  23078. void setResult(unsigned id, IGraphResult * result)
  23079. {
  23080. CriticalBlock procedure(cs);
  23081. if (results.ordinality() <= id)
  23082. {
  23083. while (results.ordinality() < id)
  23084. results.append(*new CGraphResult);
  23085. results.append(*LINK(result));
  23086. }
  23087. else
  23088. results.replace(*LINK(result), id);
  23089. }
  23090. void appendResult(IGraphResult * result)
  23091. {
  23092. CriticalBlock procedure(cs);
  23093. results.append(*LINK(result));
  23094. }
  23095. };
  23096. //===================================================================================================================
  23097. class CPseudoArg : public CInterface, implements IHThorArg
  23098. {
  23099. public:
  23100. IMPLEMENT_IINTERFACE
  23101. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  23102. };
  23103. class CPseudoActivity : public CRoxieServerActivity
  23104. {
  23105. public:
  23106. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  23107. virtual const void *nextInGroup()
  23108. {
  23109. throwUnexpected(); // I am nobody's input
  23110. }
  23111. };
  23112. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  23113. {
  23114. protected:
  23115. class ActivityGraphSlaveContext : public IndirectSlaveContext
  23116. {
  23117. SpinLock abortLock;
  23118. bool aborted;
  23119. Owned<IException> exception;
  23120. public:
  23121. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  23122. {
  23123. aborted = false;
  23124. }
  23125. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  23126. virtual void notifyAbort(IException *E)
  23127. {
  23128. SpinBlock b(abortLock);
  23129. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  23130. {
  23131. aborted = true;
  23132. exception.set(E);
  23133. }
  23134. }
  23135. virtual void checkAbort()
  23136. {
  23137. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  23138. {
  23139. SpinBlock b(abortLock);
  23140. if (!exception)
  23141. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  23142. throw exception.getLink();
  23143. }
  23144. IndirectSlaveContext::checkAbort();
  23145. }
  23146. virtual ICodeContext *queryCodeContext()
  23147. {
  23148. return codeContext;
  23149. }
  23150. void setCodeContext(ICodeContext * _codeContext)
  23151. {
  23152. codeContext = _codeContext;
  23153. }
  23154. void setLoopCounter(unsigned _loopCounter)
  23155. {
  23156. loopCounter = _loopCounter;
  23157. }
  23158. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  23159. {
  23160. childGraphs.setValue(id, childGraph);
  23161. }
  23162. virtual IActivityGraph * queryChildGraph(unsigned id)
  23163. {
  23164. if (queryTraceLevel() > 10)
  23165. CTXLOG("resolveChildGraph %d", id);
  23166. IActivityGraph *childGraph = childGraphs.getValue(id);
  23167. assertex(childGraph);
  23168. return childGraph;
  23169. }
  23170. // 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
  23171. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  23172. {
  23173. logctx.getLogPrefix(ret);
  23174. if (loopCounter)
  23175. ret.appendf("{%u}", loopCounter);
  23176. return ret;
  23177. }
  23178. protected:
  23179. const IRoxieContextLogger &logctx;
  23180. unsigned loopCounter;
  23181. ICodeContext * codeContext;
  23182. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  23183. } graphSlaveContext;
  23184. class ActivityGraphCodeContext : public IndirectCodeContext
  23185. {
  23186. public:
  23187. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  23188. {
  23189. if ((unsigned) activityId == container->queryId())
  23190. return container;
  23191. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23192. if (match)
  23193. return match->queryLocalGraph();
  23194. return IndirectCodeContext::resolveLocalQuery(activityId);
  23195. }
  23196. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  23197. {
  23198. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  23199. return LINK(match->queryChildGraph());
  23200. }
  23201. virtual unsigned getGraphLoopCounter() const
  23202. {
  23203. return container->queryLoopCounter(); // only called if value is valid
  23204. }
  23205. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  23206. {
  23207. slaveContext = _slaveContext;
  23208. container = _container;
  23209. }
  23210. protected:
  23211. IRoxieSlaveContext * slaveContext;
  23212. CActivityGraph * container;
  23213. } graphCodeContext;
  23214. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  23215. IArrayOf<IRoxieServerActivity> activities;
  23216. IArrayOf<IRoxieInput> probes;
  23217. IRoxieServerActivityCopyArray sinks;
  23218. StringAttr graphName;
  23219. Owned<CGraphResults> results;
  23220. CGraphResults graphLoopResults;
  23221. ActivityArray & graphDefinition;
  23222. CriticalSection evaluateCrit;
  23223. IProbeManager *probeManager;
  23224. unsigned id;
  23225. unsigned loopCounter;
  23226. public:
  23227. IMPLEMENT_IINTERFACE;
  23228. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23229. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  23230. {
  23231. id = x.getLibraryGraphId();
  23232. if (!id)
  23233. id = _id;
  23234. loopCounter = 0;
  23235. graphSlaveContext.setCodeContext(&graphCodeContext);
  23236. graphCodeContext.setContainer(&graphSlaveContext, this);
  23237. }
  23238. ~CActivityGraph()
  23239. {
  23240. if (probeManager)
  23241. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  23242. }
  23243. virtual const char *queryName() const
  23244. {
  23245. return graphName.get();
  23246. }
  23247. void createGraph()
  23248. {
  23249. ForEachItemIn(idx, graphDefinition)
  23250. {
  23251. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  23252. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  23253. activities.append(activity);
  23254. if (donor.isSink())
  23255. {
  23256. sinks.append(activity);
  23257. if (probeManager)
  23258. probeManager->noteSink(&activity);
  23259. }
  23260. }
  23261. ForEachItemIn(idx1, graphDefinition)
  23262. {
  23263. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  23264. IRoxieServerActivity &activity = activities.item(idx1);
  23265. unsigned inputidx = 0;
  23266. loop
  23267. {
  23268. unsigned outputidx;
  23269. unsigned source = donor.getInput(inputidx, outputidx);
  23270. if (source==(unsigned) -1)
  23271. break;
  23272. connectInput(idx1, inputidx, source, outputidx, 0);
  23273. inputidx++;
  23274. }
  23275. IntArray &dependencies = donor.queryDependencies();
  23276. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23277. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23278. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  23279. ForEachItemIn(idx2, dependencies)
  23280. {
  23281. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  23282. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  23283. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  23284. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  23285. if (probeManager)
  23286. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  23287. }
  23288. }
  23289. }
  23290. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  23291. {
  23292. IRoxieServerActivity &targetActivity = activities.item(target);
  23293. IRoxieServerActivity &sourceActivity = activities.item(source);
  23294. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  23295. if (probeManager)
  23296. {
  23297. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  23298. output = static_cast<IRoxieInput*>(inputBase);
  23299. probes.append(*LINK(output));
  23300. }
  23301. targetActivity.setInput(targetIdx, output);
  23302. }
  23303. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  23304. {
  23305. graphSlaveContext.set(ctx);
  23306. if (graphDefinition.isMultiInstance())
  23307. {
  23308. graphCodeContext.set(ctx->queryCodeContext());
  23309. ctx = &graphSlaveContext;
  23310. }
  23311. ForEachItemIn(idx, activities)
  23312. {
  23313. IRoxieServerActivity *activity = &activities.item(idx);
  23314. if (activity)
  23315. activity->onCreate(ctx, _colocalParent);
  23316. }
  23317. }
  23318. virtual void abort()
  23319. {
  23320. ForEachItemIn(idx, sinks)
  23321. {
  23322. IRoxieServerActivity &sink = sinks.item(idx);
  23323. sink.stop(true);
  23324. }
  23325. }
  23326. virtual void reset()
  23327. {
  23328. ForEachItemIn(idx, sinks)
  23329. {
  23330. IRoxieServerActivity &sink = sinks.item(idx);
  23331. sink.reset();
  23332. }
  23333. }
  23334. Linked<IException> exception;
  23335. CriticalSection eCrit;
  23336. virtual void noteException(IException *E)
  23337. {
  23338. CriticalBlock b(eCrit);
  23339. if (!exception)
  23340. {
  23341. if (graphSlaveContext.queryDebugContext())
  23342. {
  23343. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  23344. }
  23345. exception.set(E);
  23346. }
  23347. }
  23348. virtual void checkAbort()
  23349. {
  23350. CriticalBlock b(eCrit);
  23351. if (exception)
  23352. throw exception.getLink();
  23353. }
  23354. virtual void execute()
  23355. {
  23356. results.setown(new CGraphResults);
  23357. doExecute(0, NULL);
  23358. }
  23359. //New child query code...
  23360. virtual IThorChildGraph * queryChildGraph()
  23361. {
  23362. return this;
  23363. }
  23364. virtual IEclGraphResults * queryLocalGraph()
  23365. {
  23366. return this;
  23367. }
  23368. virtual IRoxieServerChildGraph * queryLoopGraph()
  23369. {
  23370. return this;
  23371. }
  23372. inline unsigned queryId() const
  23373. {
  23374. return id;
  23375. }
  23376. inline unsigned queryLoopCounter() const
  23377. {
  23378. return loopCounter;
  23379. }
  23380. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  23381. {
  23382. if (sinks.ordinality()==1)
  23383. sinks.item(0).execute(parentExtractSize, parentExtract);
  23384. #ifdef PARALLEL_EXECUTE
  23385. else if (!probeManager && !graphDefinition.isSequential())
  23386. {
  23387. class casyncfor: public CAsyncFor
  23388. {
  23389. public:
  23390. IActivityGraph &parent;
  23391. unsigned parentExtractSize;
  23392. const byte * parentExtract;
  23393. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  23394. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  23395. void Do(unsigned i)
  23396. {
  23397. try
  23398. {
  23399. sinks.item(i).execute(parentExtractSize, parentExtract);
  23400. }
  23401. catch (IException *E)
  23402. {
  23403. parent.noteException(E);
  23404. throw;
  23405. }
  23406. }
  23407. private:
  23408. IRoxieServerActivityCopyArray &sinks;
  23409. } afor(sinks, *this, parentExtractSize, parentExtract);
  23410. afor.For(sinks.ordinality(), sinks.ordinality());
  23411. }
  23412. #endif
  23413. else
  23414. {
  23415. ForEachItemIn(idx, sinks)
  23416. {
  23417. IRoxieServerActivity &sink = sinks.item(idx);
  23418. sink.execute(parentExtractSize, parentExtract);
  23419. }
  23420. }
  23421. }
  23422. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  23423. {
  23424. CriticalBlock block(evaluateCrit);
  23425. results.setown(new CGraphResults);
  23426. try
  23427. {
  23428. doExecute(parentExtractSize, parentExtract);
  23429. }
  23430. catch (...)
  23431. {
  23432. DBGLOG("Exception thrown in child query - cleaning up");
  23433. reset();
  23434. throw;
  23435. }
  23436. reset();
  23437. return results.getClear();
  23438. }
  23439. //interface IRoxieServerChildGraph
  23440. virtual void beforeExecute()
  23441. {
  23442. results.setown(new CGraphResults);
  23443. }
  23444. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23445. {
  23446. IRoxieInput * ret = selectOutput(id);
  23447. ret->start(parentExtractSize, parentExtract, paused);
  23448. return ret;
  23449. }
  23450. virtual IRoxieInput * selectOutput(unsigned id)
  23451. {
  23452. ForEachItemIn(i, sinks)
  23453. {
  23454. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  23455. if (ret)
  23456. return ret;
  23457. }
  23458. throwUnexpected();
  23459. return NULL;
  23460. }
  23461. virtual void setInputResult(unsigned id, IGraphResult * result)
  23462. {
  23463. results->setResult(id, result);
  23464. }
  23465. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  23466. {
  23467. ForEachItemIn(i, activities)
  23468. {
  23469. if (activities.item(i).querySetStreamInput(id, input))
  23470. return true;
  23471. }
  23472. return false;
  23473. }
  23474. virtual void stopUnusedOutputs()
  23475. {
  23476. //Hmm not sure how to do this...
  23477. }
  23478. virtual void afterExecute()
  23479. {
  23480. ForEachItemIn(i, sinks)
  23481. {
  23482. sinks.item(i).stop(false);
  23483. }
  23484. if (graphSlaveContext.queryDebugContext())
  23485. {
  23486. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  23487. }
  23488. reset();
  23489. }
  23490. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  23491. {
  23492. doExecute(parentExtractSize, parentExtract);
  23493. return LINK(results);
  23494. }
  23495. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  23496. {
  23497. results->getLinkedResult(count, ret, id);
  23498. }
  23499. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  23500. {
  23501. results->getLinkedResult(count, ret, id);
  23502. }
  23503. virtual const void * getLinkedRowResult(unsigned id)
  23504. {
  23505. return results->getLinkedRowResult(id);
  23506. }
  23507. virtual void setResult(unsigned id, IGraphResult * result)
  23508. {
  23509. results->setResult(id, result);
  23510. }
  23511. virtual IRoxieInput * createResultIterator(unsigned id)
  23512. {
  23513. return results->createIterator(id);
  23514. }
  23515. virtual void setGraphLoopResult(IGraphResult * result)
  23516. {
  23517. graphLoopResults.appendResult(result);
  23518. }
  23519. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  23520. {
  23521. try
  23522. {
  23523. return graphLoopResults.createIterator(id);
  23524. }
  23525. catch (IException * e)
  23526. {
  23527. e->Release();
  23528. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  23529. }
  23530. }
  23531. virtual void clearGraphLoopResults()
  23532. {
  23533. graphLoopResults.clear();
  23534. }
  23535. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  23536. {
  23537. doExecute(parentExtractSize, parentExtract);
  23538. }
  23539. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  23540. {
  23541. graphLoopResults.setResult(id, result);
  23542. }
  23543. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  23544. {
  23545. return graphLoopResults.createIterator(id);
  23546. }
  23547. virtual void getProbeResponse(IPropertyTree *query)
  23548. {
  23549. if (probeManager)
  23550. probeManager->getProbeResponse(query);
  23551. }
  23552. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23553. {
  23554. throwUnexpected();
  23555. }
  23556. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23557. {
  23558. return NULL;
  23559. }
  23560. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23561. {
  23562. throwUnexpected();
  23563. }
  23564. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23565. {
  23566. throwUnexpected();
  23567. }
  23568. };
  23569. class CIterationActivityGraph : public CActivityGraph
  23570. {
  23571. IHThorArg * colocalParent;
  23572. unsigned fixedParentExtractSize;
  23573. const byte * fixedParentExtract;
  23574. unsigned graphOutputActivityIndex;
  23575. public:
  23576. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  23577. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  23578. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  23579. {
  23580. graphOutputActivityIndex = 0;
  23581. loopCounter = _loopCounter;
  23582. colocalParent = _colocalParent;
  23583. graphSlaveContext.set(ctx);
  23584. graphSlaveContext.setLoopCounter(loopCounter);
  23585. graphCodeContext.set(ctx->queryCodeContext());
  23586. fixedParentExtractSize = parentExtractSize;
  23587. fixedParentExtract = parentExtract;
  23588. }
  23589. void createIterationGraph()
  23590. {
  23591. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23592. ForEachItemIn(idx1, graphDefinition)
  23593. activities.append(*LINK(pseudoActivity));
  23594. graphOutputActivityIndex = queryGraphOutputIndex();
  23595. recursiveCreateGraph(graphOutputActivityIndex);
  23596. }
  23597. unsigned queryGraphOutputIndex() const
  23598. {
  23599. ForEachItemIn(i, graphDefinition)
  23600. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23601. return i;
  23602. throwUnexpected();
  23603. }
  23604. void recursiveCreateGraph(unsigned whichActivity)
  23605. {
  23606. //Check to see if already created
  23607. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23608. if (prevActivity.queryId() != 0)
  23609. {
  23610. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23611. return;
  23612. }
  23613. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23614. IRoxieServerActivity * activity = NULL;
  23615. if (donor.isGraphInvariant())
  23616. {
  23617. ThorActivityKind kind = donor.getKind();
  23618. switch (kind)
  23619. {
  23620. case TAKif:
  23621. case TAKchildif:
  23622. case TAKcase:
  23623. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23624. {
  23625. Owned<IHThorArg> helper = &donor.getHelper();
  23626. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23627. helper->onStart(fixedParentExtract, NULL);
  23628. unsigned branch;
  23629. switch (kind)
  23630. {
  23631. case TAKif: case TAKchildif:
  23632. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23633. break;
  23634. case TAKcase: case TAKchildcase:
  23635. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23636. if (branch >= donor.numInputs())
  23637. branch = donor.numInputs() - 1;
  23638. break;
  23639. default:
  23640. throwUnexpected();
  23641. }
  23642. helper.clear();
  23643. unsigned outputidx;
  23644. unsigned source = donor.getInput(branch, outputidx);
  23645. if (source ==(unsigned) -1)
  23646. activity = createRoxieServerNullActivity(&donor, probeManager);
  23647. else
  23648. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23649. activities.replace(*activity, whichActivity);
  23650. activity->onCreate(&graphSlaveContext, colocalParent);
  23651. if (source ==(unsigned) -1)
  23652. return;
  23653. recursiveCreateGraph(source);
  23654. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23655. break;
  23656. }
  23657. }
  23658. }
  23659. if (!activity)
  23660. {
  23661. activity = donor.createActivity(probeManager);
  23662. activities.replace(*activity, whichActivity);
  23663. activity->onCreate(&graphSlaveContext, colocalParent);
  23664. activity->resetOutputsUsed();
  23665. unsigned inputidx = 0;
  23666. loop
  23667. {
  23668. unsigned outputidx;
  23669. unsigned source = donor.getInput(inputidx, outputidx);
  23670. if (source==(unsigned) -1)
  23671. break;
  23672. recursiveCreateGraph(source);
  23673. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23674. inputidx++;
  23675. }
  23676. }
  23677. IntArray &dependencies = donor.queryDependencies();
  23678. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23679. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23680. ForEachItemIn(idx2, dependencies)
  23681. {
  23682. unsigned input = dependencies.item(idx2);
  23683. recursiveCreateGraph(input);
  23684. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23685. }
  23686. }
  23687. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23688. {
  23689. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23690. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23691. }
  23692. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23693. {
  23694. ForEachItemIn(i, activities)
  23695. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23696. }
  23697. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23698. {
  23699. ForEachItemIn(i, activities)
  23700. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23701. }
  23702. };
  23703. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23704. {
  23705. StringAttr graphName;
  23706. ActivityArray & graphDefinition;
  23707. IProbeManager *probeManager;
  23708. unsigned id;
  23709. IRoxieSlaveContext * ctx;
  23710. IHThorArg * colocalParent;
  23711. public:
  23712. IMPLEMENT_IINTERFACE;
  23713. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23714. : probeManager(_probeManager), graphDefinition(x)
  23715. {
  23716. graphName.set(_graphName);
  23717. id = _id;
  23718. ctx = NULL;
  23719. colocalParent = NULL;
  23720. }
  23721. virtual const char *queryName() const { return graphName.get(); }
  23722. virtual void abort() { throwUnexpected(); }
  23723. virtual void reset() { }
  23724. virtual void execute() { throwUnexpected(); }
  23725. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23726. virtual void noteException(IException *E) { throwUnexpected(); }
  23727. virtual void checkAbort() { throwUnexpected(); }
  23728. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23729. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23730. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23731. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23732. {
  23733. ctx = _ctx;
  23734. colocalParent = _colocalParent;
  23735. }
  23736. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23737. {
  23738. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23739. ret->createIterationGraph();
  23740. return ret.getClear();
  23741. }
  23742. };
  23743. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23744. {
  23745. if (childFactories.isDelayed())
  23746. {
  23747. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23748. }
  23749. else
  23750. {
  23751. Owned<IProbeManager> childProbe;
  23752. if (_probeManager)
  23753. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23754. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23755. ret->createGraph();
  23756. if (_probeManager)
  23757. _probeManager->endChildGraph(childProbe, parentActivity);
  23758. return ret.getClear();
  23759. }
  23760. }
  23761. //================================================================================================================
  23762. #ifdef _USE_CPPUNIT
  23763. #include "unittests.hpp"
  23764. // 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...
  23765. #if _MSC_VER==1200
  23766. #undef protected
  23767. #endif
  23768. static const char *sortAlgorithm;
  23769. class TestMetaData : public CInterface, implements IOutputMetaData
  23770. {
  23771. public:
  23772. IMPLEMENT_IINTERFACE;
  23773. virtual size32_t getRecordSize(const void *) { return 10; }
  23774. virtual size32_t getMinRecordSize() const { return 10; }
  23775. virtual size32_t getFixedSize() const { return 10; }
  23776. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23777. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23778. virtual unsigned getMetaFlags() { return 0; }
  23779. virtual void destruct(byte * self) {}
  23780. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23781. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23782. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23783. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23784. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23785. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23786. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23787. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  23788. } testMeta;
  23789. class TestInput : public CInterface, implements IRoxieInput
  23790. {
  23791. char const * const *input;
  23792. IRoxieSlaveContext *ctx;
  23793. unsigned endSeen;
  23794. bool eof;
  23795. unsigned count;
  23796. ActivityTimeAccumulator totalCycles;
  23797. size32_t recordSize;
  23798. unsigned activityId;
  23799. public:
  23800. enum { STATEreset, STATEstarted, STATEstopped } state;
  23801. bool allRead;
  23802. unsigned repeat;
  23803. IMPLEMENT_IINTERFACE;
  23804. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23805. {
  23806. ctx = _ctx;
  23807. input = _input;
  23808. count = 0;
  23809. eof = false;
  23810. allRead = false;
  23811. endSeen = 0;
  23812. recordSize = testMeta.getFixedSize();
  23813. state = STATEreset;
  23814. activityId = 1;
  23815. repeat = 0;
  23816. }
  23817. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23818. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23819. {
  23820. ASSERT(state == STATEreset);
  23821. }
  23822. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23823. {
  23824. ASSERT(state == STATEreset);
  23825. state = STATEstarted;
  23826. }
  23827. virtual IRoxieServerActivity *queryActivity()
  23828. {
  23829. throwUnexpected();
  23830. }
  23831. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23832. {
  23833. throwUnexpected();
  23834. }
  23835. virtual void stop(bool aborting)
  23836. {
  23837. state = STATEstopped;
  23838. }
  23839. virtual void reset()
  23840. {
  23841. ASSERT(state == STATEstopped);
  23842. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  23843. }
  23844. virtual void resetEOF()
  23845. {
  23846. throwUnexpected();
  23847. }
  23848. virtual void checkAbort() {}
  23849. virtual unsigned queryId() const { return activityId; };
  23850. virtual const void *nextInGroup()
  23851. {
  23852. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  23853. ASSERT(state == STATEstarted);
  23854. ASSERT(allRead || !eof);
  23855. if (eof)
  23856. return NULL;
  23857. again:
  23858. const char *nextSource = input[count++];
  23859. if (nextSource)
  23860. {
  23861. endSeen = 0;
  23862. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23863. memset(ret, 0, recordSize);
  23864. strncpy((char *) ret, nextSource, recordSize);
  23865. return ret;
  23866. }
  23867. else if (repeat)
  23868. {
  23869. repeat--;
  23870. count = 0;
  23871. goto again;
  23872. }
  23873. else
  23874. {
  23875. endSeen++;
  23876. if (endSeen==2)
  23877. eof = true;
  23878. return NULL;
  23879. }
  23880. }
  23881. virtual bool nextGroup(ConstPointerArray & group)
  23882. {
  23883. const void * next;
  23884. while ((next = nextInGroup()) != NULL)
  23885. group.append(next);
  23886. if (group.ordinality())
  23887. return true;
  23888. return false;
  23889. }
  23890. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  23891. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  23892. virtual IRoxieInput *queryInput(unsigned idx) const
  23893. {
  23894. return NULL;
  23895. }
  23896. };
  23897. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23898. public:
  23899. struct CompareClass : public ICompare {
  23900. virtual int docompare(const void * _left, const void * _right) const {
  23901. return memcmp(_left, _right, 5);
  23902. }
  23903. } compare;
  23904. virtual ICompare * queryCompare() { return &compare; }
  23905. virtual IOutputMetaData * queryOutputMeta()
  23906. {
  23907. return &testMeta;
  23908. }
  23909. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23910. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23911. };
  23912. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23913. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23914. static bool isDedup;
  23915. public:
  23916. struct CompareClass : public ICompare {
  23917. virtual int docompare(const void * _left, const void * _right) const {
  23918. return memcmp(_left, _right, 5);
  23919. }
  23920. } compare;
  23921. virtual ICompare * queryCompare() { return &compare; }
  23922. virtual IOutputMetaData * queryOutputMeta()
  23923. {
  23924. return &testMeta;
  23925. }
  23926. virtual bool dedup() { return isDedup; }
  23927. };
  23928. bool MergeActivityTest::isDedup = false;
  23929. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23930. struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
  23931. public:
  23932. virtual unsigned numBranches() { return 2; }
  23933. virtual IOutputMetaData * queryOutputMeta()
  23934. {
  23935. return &testMeta;
  23936. }
  23937. };
  23938. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  23939. class CcdServerTest : public CppUnit::TestFixture
  23940. {
  23941. CPPUNIT_TEST_SUITE(CcdServerTest);
  23942. CPPUNIT_TEST(testSetup);
  23943. CPPUNIT_TEST(testHeapSort);
  23944. CPPUNIT_TEST(testInsertionSort);
  23945. CPPUNIT_TEST(testQuickSort);
  23946. CPPUNIT_TEST(testMerge);
  23947. CPPUNIT_TEST(testMergeDedup);
  23948. CPPUNIT_TEST(testMiscellaneous);
  23949. CPPUNIT_TEST(testSplitter);
  23950. CPPUNIT_TEST(testCleanup);
  23951. CPPUNIT_TEST_SUITE_END();
  23952. protected:
  23953. SlaveContextLogger logctx;
  23954. Owned<const IQueryDll> queryDll;
  23955. Owned<IRoxiePackage> package;
  23956. Owned<IPropertyTree> stateInfo;
  23957. Owned<IQueryFactory> queryFactory;
  23958. Owned<IRoxieSlaveContext> ctx;
  23959. void testSetup()
  23960. {
  23961. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  23962. }
  23963. void testCleanup()
  23964. {
  23965. roxiemem::releaseRoxieHeap();
  23966. }
  23967. void init()
  23968. {
  23969. package.setown(createRoxiePackage(NULL, NULL));
  23970. queryDll.setown(createExeQueryDll("roxie"));
  23971. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  23972. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  23973. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  23974. queryActiveTimer()->reset();
  23975. }
  23976. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  23977. {
  23978. testActivity(activity, input, NULL, output);
  23979. }
  23980. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  23981. {
  23982. TestInput in(ctx, input);
  23983. TestInput in2(ctx, input2);
  23984. activity->setInput(0, &in);
  23985. if (input2)
  23986. activity->setInput(1, &in2);
  23987. IRoxieInput *out = activity->queryOutput(outputIdx);
  23988. IOutputMetaData *meta = out->queryOutputMeta();
  23989. void *buf = alloca(meta->getFixedSize());
  23990. for (unsigned iteration = 0; iteration < 8; iteration++)
  23991. {
  23992. // 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)
  23993. // This should be true whether we read all, some, or none of the data.
  23994. // Should not matter if an activity is not started
  23995. if (iteration % 4 == 0)
  23996. activity->onCreate(ctx, NULL);
  23997. unsigned count = 0;
  23998. if (iteration % 4 != 3)
  23999. {
  24000. activity->start(0, NULL, false);
  24001. ASSERT(in.state == TestInput::STATEstarted);
  24002. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  24003. loop
  24004. {
  24005. const void *next = out->nextInGroup();
  24006. if (!next)
  24007. {
  24008. ASSERT(output[count++] == NULL);
  24009. next = out->nextInGroup();
  24010. if (!next)
  24011. {
  24012. ASSERT(output[count++] == NULL);
  24013. break;
  24014. }
  24015. }
  24016. ASSERT(output[count] != NULL);
  24017. unsigned outsize = meta->getRecordSize(next);
  24018. memset(buf, 0, outsize);
  24019. strncpy((char *) buf, output[count++], outsize);
  24020. ASSERT(memcmp(next, buf, outsize) == 0);
  24021. ReleaseRoxieRow(next);
  24022. if (iteration % 4 == 2)
  24023. break;
  24024. }
  24025. if (iteration % 4 != 2)
  24026. {
  24027. // Check that reading after end is harmless
  24028. in.allRead = true;
  24029. const void *next = out->nextInGroup();
  24030. ASSERT(next == NULL);
  24031. }
  24032. }
  24033. activity->stop(false);
  24034. ASSERT(in.state == TestInput::STATEstopped);
  24035. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  24036. activity->reset();
  24037. ASSERT(in.state == TestInput::STATEreset);
  24038. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  24039. ctx->queryRowManager().reportLeaks();
  24040. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24041. }
  24042. }
  24043. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  24044. {
  24045. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24046. TestInput in(ctx, input);
  24047. in.repeat = repeat;
  24048. activity->setInput(0, &in);
  24049. ArrayOf<IRoxieInput *> out;
  24050. for (unsigned i = 0; i < numOutputs; i++)
  24051. {
  24052. out.append(activity->queryOutput(i));
  24053. }
  24054. activity->onCreate(ctx, NULL);
  24055. class casyncfor: public CAsyncFor
  24056. {
  24057. public:
  24058. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  24059. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  24060. {}
  24061. void Do(unsigned i)
  24062. {
  24063. IRoxieInput *out = outputs.item(i);
  24064. out->start(0, NULL, false);
  24065. IOutputMetaData *meta = out->queryOutputMeta();
  24066. void *buf = alloca(meta->getFixedSize());
  24067. unsigned count = 0;
  24068. unsigned repeats = repeat;
  24069. loop
  24070. {
  24071. const void *next = out->nextInGroup();
  24072. if (!next)
  24073. {
  24074. ASSERT(repeats==0);
  24075. ASSERT(output[count++] == NULL);
  24076. next = out->nextInGroup();
  24077. if (!next)
  24078. {
  24079. ASSERT(output[count++] == NULL);
  24080. break;
  24081. }
  24082. }
  24083. if (output[count] == NULL && repeats)
  24084. {
  24085. repeats--;
  24086. count = 0;
  24087. }
  24088. ASSERT(output[count] != NULL);
  24089. unsigned outsize = meta->getRecordSize(next);
  24090. memset(buf, 0, outsize);
  24091. strncpy((char *) buf, output[count++], outsize);
  24092. ASSERT(memcmp(next, buf, outsize) == 0);
  24093. ReleaseRoxieRow(next);
  24094. }
  24095. out->stop(false);
  24096. }
  24097. private:
  24098. IRoxieServerActivity *activity;
  24099. ArrayOf<IRoxieInput *> &outputs;
  24100. char const * const *input;
  24101. char const * const *output;
  24102. unsigned repeat;
  24103. CcdServerTest *parent;
  24104. } afor(this, activity, out, input, output, repeat);
  24105. afor.For(numOutputs, numOutputs);
  24106. ASSERT(in.state == TestInput::STATEstopped);
  24107. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  24108. {
  24109. out.item(i2)->reset();
  24110. }
  24111. ASSERT(in.state == TestInput::STATEreset);
  24112. ctx->queryRowManager().reportLeaks();
  24113. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  24114. }
  24115. static int compareFunc(const void *l, const void *r)
  24116. {
  24117. return strcmp(*(char **) l, *(char **) r);
  24118. }
  24119. void testSort(unsigned type)
  24120. {
  24121. init();
  24122. sortAlgorithm = NULL;
  24123. if (type==2)
  24124. sortAlgorithm = "heapSort";
  24125. else if (type == 1)
  24126. sortAlgorithm = "insertionSort";
  24127. else
  24128. sortAlgorithm = "quickSort";
  24129. DBGLOG("Testing %s activity", sortAlgorithm);
  24130. Owned<IPropertyTree> dummyNode = createPTree("node");
  24131. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  24132. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24133. const char * test[] = { NULL, NULL };
  24134. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24135. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  24136. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24137. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24138. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24139. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  24140. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24141. testActivity(activity, test, test);
  24142. testActivity(activity, test12345, test12345);
  24143. testActivity(activity, test54321, test12345);
  24144. testActivity(activity, test11111, test11111);
  24145. testActivity(activity, test11111_12345, test11111_12345);
  24146. testActivity(activity, test11111_54321, test11111_12345);
  24147. testActivity(activity, test54321_54321, test12345_12345);
  24148. // A few larger tests
  24149. char *input[2002];
  24150. char *output[2002];
  24151. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  24152. unsigned i;
  24153. // identical
  24154. for (i=0; i<2000; i++)
  24155. {
  24156. input[i] = new char[11];
  24157. output[i] = new char[11];
  24158. sprintf(input[i], "1");
  24159. sprintf(output[i], "1");
  24160. }
  24161. testActivity(activity, input, output);
  24162. // Ascending
  24163. for (i=0; i<2000; i++)
  24164. {
  24165. sprintf(input[i], "%04d", i);
  24166. sprintf(output[i], "%04d", i);
  24167. }
  24168. testActivity(activity, input, output);
  24169. // Almost sorted
  24170. for (i=0; i<20; i++)
  24171. {
  24172. unsigned h = i*100;
  24173. sprintf(input[h], "%04d", 1900-h);
  24174. }
  24175. testActivity(activity, input, output);
  24176. // Descending
  24177. for (i=0; i<2000; i++)
  24178. {
  24179. sprintf(input[i], "%04d", 1999-i);
  24180. sprintf(output[i], "%04d", i);
  24181. }
  24182. testActivity(activity, input, output);
  24183. // Random
  24184. for (i=0; i<2000; i++)
  24185. {
  24186. unsigned r = rand() % 1500;
  24187. sprintf(input[i], "%04d", r);
  24188. sprintf(output[i], "%04d", r);
  24189. }
  24190. qsort(output, 2000, sizeof(output[0]), compareFunc);
  24191. testActivity(activity, input, output);
  24192. #if 0
  24193. // Random
  24194. #define BIGSORTSIZE 1000000
  24195. char **linput = new char*[BIGSORTSIZE +2];
  24196. char **loutput = new char *[BIGSORTSIZE+2];
  24197. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  24198. for (i=0; i<BIGSORTSIZE; i++)
  24199. {
  24200. unsigned r = rand() % 15000;
  24201. linput[i] = loutput[i] = new char[11];
  24202. sprintf(linput[i], "%04d", r);
  24203. }
  24204. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  24205. testActivity(activity, linput, loutput);
  24206. for (i=0; i<BIGSORTSIZE; i++)
  24207. {
  24208. delete [] linput[i];
  24209. }
  24210. delete [] linput;
  24211. delete [] loutput;
  24212. #endif
  24213. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  24214. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  24215. factory->resetNodeProgressInfo();
  24216. if (type)
  24217. {
  24218. // Other than quicksort, it's supposed to be stable. Let's check that it is
  24219. // All sort identical
  24220. for (i=0; i<2000; i++)
  24221. {
  24222. sprintf(input[i], "1 %d", i);
  24223. sprintf(output[i], "1 %d", i);
  24224. }
  24225. testActivity(activity, input, output);
  24226. // Already sorted
  24227. for (i=0; i<2000; i++)
  24228. {
  24229. sprintf(input[i], "%04d %d", i / 10, i);
  24230. sprintf(output[i], "%04d %d", i / 10, i);
  24231. }
  24232. testActivity(activity, input, output);
  24233. // Reverse order
  24234. for (i=0; i<2000; i++)
  24235. {
  24236. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  24237. sprintf(output[i], "%04d %d", i / 10, i%10);
  24238. }
  24239. testActivity(activity, input, output);
  24240. }
  24241. for (i=0; i<2000; i++)
  24242. {
  24243. delete [] input[i];
  24244. delete [] output[i];
  24245. }
  24246. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  24247. }
  24248. void testQuickSort()
  24249. {
  24250. testSort(0);
  24251. }
  24252. void testInsertionSort()
  24253. {
  24254. testSort(1);
  24255. }
  24256. void testHeapSort()
  24257. {
  24258. testSort(2);
  24259. }
  24260. void testMerge()
  24261. {
  24262. DBGLOG("testMerge");
  24263. init();
  24264. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24265. factory->setInput(0,0,0);
  24266. factory->setInput(1,0,0);
  24267. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24268. const char * test[] = { NULL, NULL };
  24269. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24270. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  24271. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24272. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  24273. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24274. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24275. 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 };
  24276. testActivity(activity, test, test, test);
  24277. testActivity(activity, test12345, test, test12345);
  24278. testActivity(activity, test, test12345, test12345);
  24279. testActivity(activity, test12345, test12345, test1122334455);
  24280. testActivity(activity, test11111, test, test11111);
  24281. testActivity(activity, test, test11111, test11111);
  24282. testActivity(activity, test11111, test11111, test1111111111);
  24283. testActivity(activity, test11111_12345, test, test1111112345);
  24284. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  24285. // Should really test WHICH side gets kept...
  24286. // Should test with more than 2 inputs...
  24287. DBGLOG("testMerge done");
  24288. }
  24289. void testMergeDedup()
  24290. {
  24291. DBGLOG("testMergeDedup");
  24292. init();
  24293. MergeActivityTest::isDedup = true;
  24294. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  24295. factory->setInput(0,0,0);
  24296. factory->setInput(1,0,0);
  24297. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24298. const char * test[] = { NULL, NULL };
  24299. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24300. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  24301. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  24302. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  24303. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  24304. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  24305. testActivity(activity, test, test11111, test11111);
  24306. testActivity(activity, test, test, test);
  24307. testActivity(activity, test12345, test, test12345);
  24308. testActivity(activity, test, test12345, test12345);
  24309. testActivity(activity, test12345, test12345, test12345);
  24310. testActivity(activity, test11111_12345, test, test1111112345);
  24311. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  24312. // Should really test WHICH side gets kept...
  24313. // Should test with more than 2 inputs...
  24314. DBGLOG("testMergeDedup done");
  24315. }
  24316. void doTestSplitter(unsigned numOutputs)
  24317. {
  24318. DBGLOG("testSplit %d", numOutputs);
  24319. init();
  24320. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs);
  24321. factory->setInput(0,0,0);
  24322. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  24323. const char * test[] = { NULL, NULL };
  24324. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  24325. unsigned start = msTick();
  24326. testSplitActivity(factory, test, test, numOutputs, 0);
  24327. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  24328. testSplitActivity(factory, test12345, test12345, numOutputs, 1000000);
  24329. unsigned elapsed = msTick() - start;
  24330. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  24331. }
  24332. void testSplitter()
  24333. {
  24334. doTestSplitter(1);
  24335. doTestSplitter(2);
  24336. doTestSplitter(3);
  24337. doTestSplitter(10);
  24338. }
  24339. void testMiscellaneous()
  24340. {
  24341. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  24342. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  24343. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  24344. ASSERT(sizeof(CJoinGroup) <= 120);
  24345. }
  24346. };
  24347. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  24348. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  24349. #endif