ccdserver.cpp 1018 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include "rtlcommon.hpp"
  40. #include <algorithm>
  41. #include "dafdesc.hpp"
  42. #include "dautils.hpp"
  43. #include "ftbase.ipp"
  44. #include "eclhelper_base.hpp"
  45. #include "ccd.hpp"
  46. #include "ccdserver.hpp"
  47. #include "ccdcontext.hpp"
  48. #include "ccdactivities.hpp"
  49. #include "ccdquery.hpp"
  50. #include "ccdstate.hpp"
  51. #include "ccdqueue.ipp"
  52. #include "ccdsnmp.hpp"
  53. #include "ccddali.hpp"
  54. #include "jsmartsock.hpp"
  55. #include "dllserver.hpp"
  56. #include "workflow.hpp"
  57. #include "roxiemem.hpp"
  58. #include "roxierowbuff.hpp"
  59. #include "roxiehelper.hpp"
  60. #include "roxielmj.hpp"
  61. #include "roxierow.hpp"
  62. #include "thorplugin.hpp"
  63. #include "keybuild.hpp"
  64. #include "thorstrand.hpp"
  65. #include "rtldynfield.hpp"
  66. #define MAX_HTTP_HEADERSIZE 8000
  67. #define MIN_PAYLOAD_SIZE 800
  68. #ifdef _WIN32
  69. #pragma warning(disable : 4355)
  70. #endif
  71. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  72. #define PROBE
  73. #ifdef _DEBUG
  74. //#define FAKE_EXCEPTIONS
  75. //#define TRACE_JOINGROUPS
  76. //#define TRACE_SPLIT
  77. //#define _CHECK_HEAPSORT
  78. //#undef PARALLEL_EXECUTE
  79. //#define TRACE_SEEK_REQUESTS
  80. #endif
  81. using roxiemem::OwnedRoxieRow;
  82. using roxiemem::OwnedRoxieString;
  83. using roxiemem::OwnedConstRoxieRow;
  84. using roxiemem::IRowManager;
  85. using roxiemem::ReleaseRoxieRows;
  86. // 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...
  87. #if _MSC_VER==1200
  88. #define protected public
  89. #endif
  90. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  91. #define TRACE_STRANDS
  92. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  93. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  94. //=================================================================================
  95. class RestartableThread : public CInterface
  96. {
  97. class MyThread : public Thread
  98. {
  99. Linked<RestartableThread> owner;
  100. public:
  101. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  102. {
  103. }
  104. virtual int run()
  105. {
  106. owner->started.signal();
  107. return owner->run();
  108. }
  109. };
  110. friend class MyThread;
  111. Semaphore started;
  112. Owned<MyThread> thread;
  113. CriticalSection crit;
  114. StringAttr name;
  115. public:
  116. RestartableThread(const char *_name) : name(_name)
  117. {
  118. }
  119. virtual void start(const char *namePrefix)
  120. {
  121. StringBuffer s(namePrefix);
  122. s.append(name);
  123. {
  124. CriticalBlock b(crit);
  125. assertex(!thread);
  126. thread.setown(new MyThread(this, s));
  127. thread->start();
  128. }
  129. started.wait();
  130. }
  131. virtual void join()
  132. {
  133. {
  134. Owned<Thread> tthread;
  135. {
  136. CriticalBlock b(crit);
  137. tthread.setown(thread.getClear());
  138. }
  139. if (tthread)
  140. tthread->join();
  141. }
  142. }
  143. virtual int run() = 0;
  144. };
  145. //================================================================================
  146. //The following don't link their arguments because that creates a circular reference
  147. //But I wish there was a better way
  148. class IndirectAgentContext : implements IRoxieAgentContext, public CInterface
  149. {
  150. public:
  151. IndirectAgentContext(IRoxieAgentContext * _ctx) : ctx(_ctx) {}
  152. IMPLEMENT_IINTERFACE
  153. // void set(IRoxieAgentContext * _ctx) { ctx = _ctx; }
  154. virtual ICodeContext *queryCodeContext()
  155. {
  156. return ctx->queryCodeContext();
  157. }
  158. virtual void checkAbort()
  159. {
  160. ctx->checkAbort();
  161. }
  162. virtual void notifyAbort(IException *E)
  163. {
  164. ctx->notifyAbort(E);
  165. }
  166. virtual IActivityGraph * queryChildGraph(unsigned id)
  167. {
  168. return ctx->queryChildGraph(id);
  169. }
  170. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  171. {
  172. ctx->noteChildGraph(id, childGraph) ;
  173. }
  174. virtual IRowManager &queryRowManager()
  175. {
  176. return ctx->queryRowManager();
  177. }
  178. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  179. {
  180. ctx->noteStatistic(kind, value);
  181. }
  182. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  183. {
  184. ctx->mergeStats(from);
  185. }
  186. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  187. {
  188. ctx->gatherStats(merged);
  189. }
  190. virtual bool collectingDetailedStatistics() const
  191. {
  192. return ctx->collectingDetailedStatistics();
  193. }
  194. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  195. {
  196. ctx->CTXLOGva(format, args);
  197. }
  198. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  199. {
  200. ctx->CTXLOGa(category, prefix, text);
  201. }
  202. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  203. {
  204. ctx->logOperatorExceptionVA(E, file, line, format, args);
  205. }
  206. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  207. {
  208. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  209. }
  210. virtual void CTXLOGl(LogItem *log) const
  211. {
  212. ctx->CTXLOGl(log);
  213. }
  214. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const override
  215. {
  216. return ctx->getLogPrefix(ret);
  217. }
  218. virtual unsigned queryTraceLevel() const
  219. {
  220. return ctx->queryTraceLevel();
  221. }
  222. virtual bool isIntercepted() const
  223. {
  224. return ctx->isIntercepted();
  225. }
  226. virtual bool isBlind() const
  227. {
  228. return ctx->isBlind();
  229. }
  230. virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid) override
  231. {
  232. ctx->setGlobalId(id, ep, pid);
  233. }
  234. virtual void setCallerId(const char *id) override
  235. {
  236. ctx->setCallerId(id);
  237. }
  238. virtual const char *queryGlobalId() const
  239. {
  240. return ctx->queryGlobalId();
  241. }
  242. virtual const char *queryCallerId() const override
  243. {
  244. return ctx->queryCallerId();
  245. }
  246. virtual const char *queryLocalId() const
  247. {
  248. return ctx->queryLocalId();
  249. }
  250. virtual void setHttpIdHeaders(const char *global, const char *caller)
  251. {
  252. ctx->setHttpIdHeaders(global, caller);
  253. }
  254. virtual const char *queryGlobalIdHttpHeader() const
  255. {
  256. return ctx->queryGlobalIdHttpHeader();
  257. }
  258. virtual const char *queryCallerIdHttpHeader() const
  259. {
  260. return ctx->queryCallerIdHttpHeader();
  261. }
  262. virtual const QueryOptions &queryOptions() const
  263. {
  264. return ctx->queryOptions();
  265. }
  266. virtual void addAgentsReplyLen(unsigned len)
  267. {
  268. ctx->addAgentsReplyLen(len);
  269. }
  270. virtual const char *queryAuthToken()
  271. {
  272. return ctx->queryAuthToken();
  273. }
  274. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt, bool isPrivilegedUser)
  275. {
  276. return ctx->resolveLFN(filename, isOpt, isPrivilegedUser);
  277. }
  278. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters, bool isPrivilegedUser)
  279. {
  280. return ctx->createLFN(filename, overwrite, extend, clusters, isPrivilegedUser);
  281. }
  282. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal, bool isPrivilegedUser)
  283. {
  284. ctx->onFileCallback(header, lfn, isOpt, isLocal, isPrivilegedUser);
  285. }
  286. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  287. {
  288. return ctx->getLibraryGraph(extra, parentActivity);
  289. }
  290. virtual IProbeManager *queryProbeManager() const
  291. {
  292. return ctx->queryProbeManager();
  293. }
  294. virtual IDebuggableContext *queryDebugContext() const
  295. {
  296. return ctx->queryDebugContext();
  297. }
  298. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  299. {
  300. ctx->printResults(output, name, sequence);
  301. }
  302. virtual void setWUState(WUState state)
  303. {
  304. ctx->setWUState(state);
  305. }
  306. virtual bool checkWuAborted()
  307. {
  308. return ctx->checkWuAborted();
  309. }
  310. virtual IWorkUnit *updateWorkUnit() const
  311. {
  312. return ctx->updateWorkUnit();
  313. }
  314. virtual IConstWorkUnit *queryWorkUnit() const
  315. {
  316. return ctx->queryWorkUnit();
  317. }
  318. virtual IRoxieServerContext *queryServerContext()
  319. {
  320. return ctx->queryServerContext();
  321. }
  322. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  323. {
  324. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  325. }
  326. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  327. {
  328. return ctx->getRowAllocatorEx(meta, activityId, flags);
  329. }
  330. protected:
  331. IRoxieAgentContext * ctx;
  332. };
  333. //=================================================================================
  334. #define RESULT_FLUSH_THRESHOLD 10000u
  335. #ifdef _DEBUG
  336. #define SOAP_SPLIT_THRESHOLD 100u
  337. #define SOAP_SPLIT_RESERVE 200u
  338. #else
  339. #define SOAP_SPLIT_THRESHOLD 64000u
  340. #define SOAP_SPLIT_RESERVE 65535u
  341. #endif
  342. //=================================================================================
  343. // General activity statistics
  344. static const StatisticsMapping actStatistics({StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  345. StNumRowsProcessed, StNumSlaves, StNumStarts, StNumStops, StNumStrands,
  346. StNumScansPerRow, StNumAllocations, StNumAllocationScans,
  347. StTimeFirstExecute, StCycleLocalExecuteCycles, StCycleTotalExecuteCycles});
  348. static const StatisticsMapping joinStatistics({StNumAtmostTriggered}, actStatistics);
  349. static const StatisticsMapping keyedJoinStatistics({ StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  350. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  351. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  352. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  353. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  354. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  355. StNumDiskRejected}, joinStatistics);
  356. static const StatisticsMapping indexStatistics({StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  357. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  358. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  359. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  360. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  361. StNumIndexRowsRead}, actStatistics);
  362. static const StatisticsMapping diskStatistics({StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  363. StNumDiskRejected }, actStatistics);
  364. static const StatisticsMapping soapStatistics({ StTimeSoapcall }, actStatistics);
  365. static const StatisticsMapping groupStatistics({ StNumGroups, StNumGroupMax }, actStatistics);
  366. static const StatisticsMapping sortStatistics({ StTimeSortElapsed }, actStatistics);
  367. static const StatisticsMapping indexWriteStatistics({ StNumDuplicateKeys }, actStatistics);
  368. //=================================================================================
  369. const static unsigned minus1U = (0U-1U);
  370. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  371. {
  372. protected:
  373. IntArray dependencies; // things I am dependent on
  374. IntArray dependencyIndexes; // things I am dependent on
  375. IntArray dependencyControlIds; // things I am dependent on
  376. StringArray dependencyEdgeIds; // How to describe them to the debugger
  377. unsigned dependentCount; // things dependent on me
  378. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  379. bool optStableInput = true; // is the input forced to ordered?
  380. bool optUnstableInput = false; // is the input forced to unordered?
  381. bool optUnordered = false; // is the output specified as unordered?
  382. bool isCodeSigned = false;
  383. unsigned heapFlags;
  384. mutable RelaxedAtomic<__int64> processed = {0};
  385. mutable RelaxedAtomic<__int64> started = {0};
  386. public:
  387. IMPLEMENT_IINTERFACE;
  388. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  389. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  390. {
  391. dependentCount = 0;
  392. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  393. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  394. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  395. isCodeSigned = ::isActivityCodeSigned(_graphNode);
  396. }
  397. ~CRoxieServerActivityFactoryBase()
  398. {
  399. }
  400. StringBuffer &toString(StringBuffer &ret) const
  401. {
  402. return ret.appendf("%p", this);
  403. }
  404. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  405. {
  406. dependencies.append(_source);
  407. dependencyIndexes.append(_sourceIdx);
  408. dependencyControlIds.append(controlId);
  409. dependencyEdgeIds.append(edgeId);
  410. }
  411. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  412. {
  413. if (optStableInput)
  414. return true;
  415. if (optUnstableInput)
  416. return false;
  417. if (optUnordered)
  418. return false;
  419. return consumerOrdered;
  420. }
  421. virtual void noteDependent(unsigned target)
  422. {
  423. dependentCount++;
  424. }
  425. virtual IntArray &queryDependencies() { return dependencies; }
  426. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  427. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  428. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  429. virtual unsigned queryId() const { return id; }
  430. virtual unsigned querySubgraphId() const { return subgraphId; }
  431. virtual ThorActivityKind getKind() const { return kind; }
  432. virtual IOutputMetaData * queryOutputMeta() const
  433. {
  434. return meta;
  435. }
  436. virtual bool isSink() const
  437. {
  438. return false;
  439. }
  440. virtual bool isFunction() const
  441. {
  442. return false;
  443. }
  444. virtual bool isGraphInvariant() const
  445. {
  446. return false;
  447. }
  448. virtual IHThorArg &getHelper() const
  449. {
  450. return *helperFactory();
  451. }
  452. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  453. {
  454. arg.Release();
  455. throwUnexpected();
  456. }
  457. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  458. {
  459. CActivityFactory::mergeStats(from);
  460. }
  461. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  462. {
  463. dbgassertex(!_idx);
  464. if (likely(_processed))
  465. processed += _processed;
  466. }
  467. virtual void noteStarted() const
  468. {
  469. started++;
  470. }
  471. virtual void noteStarted(unsigned idx) const
  472. {
  473. throwUnexpected(); // should be implemented/required by multiOutput cases only
  474. }
  475. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  476. {
  477. if (output == 0)
  478. {
  479. putStatsValue(&edge, "NumRowsProcessed", "sum", processed);
  480. auto _started = started.load();
  481. if (_started)
  482. putStatsValue(&edge, "NumStarts", "sum", _started);
  483. }
  484. else
  485. IERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  486. }
  487. virtual void getNodeProgressInfo(IPropertyTree &node) const
  488. {
  489. CActivityFactory::getNodeProgressInfo(node);
  490. auto _started = started.load();
  491. if (_started)
  492. putStatsValue(&node, "_roxieStarted", "sum", _started);
  493. }
  494. virtual void resetNodeProgressInfo()
  495. {
  496. CActivityFactory::resetNodeProgressInfo();
  497. processed = 0;
  498. started = 0;
  499. }
  500. virtual void getActivityMetrics(StringBuffer &reply) const
  501. {
  502. CActivityFactory::getActivityMetrics(reply);
  503. putStatsValue(reply, "NumStarts", "sum", started);
  504. CriticalBlock b(statsCrit);
  505. putStatsValue(reply, "TimeTotalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeTotalExecute)/1000));
  506. putStatsValue(reply, "TimeLocalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeLocalExecute)/1000));
  507. }
  508. virtual unsigned __int64 queryLocalTimeNs() const
  509. {
  510. return mystats.getSerialStatisticValue(StTimeLocalExecute);
  511. }
  512. virtual IQueryFactory &queryQueryFactory() const
  513. {
  514. return CActivityFactory::queryQueryFactory();
  515. }
  516. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  517. {
  518. return CActivityFactory::queryChildQuery(idx, id);
  519. }
  520. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  521. {
  522. CActivityFactory::addChildQuery(id, childQuery);
  523. }
  524. virtual void onCreateChildQueries(IRoxieAgentContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  525. {
  526. ForEachItemIn(idx, childQueries)
  527. {
  528. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  529. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  530. childGraphs.item(idx).onCreate(colocalArg);
  531. }
  532. }
  533. IActivityGraph * createChildGraph(IRoxieAgentContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  534. {
  535. unsigned match = childQueryIndexes.find(childId);
  536. assertex(match != NotFound);
  537. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  538. graph->onCreate(colocalArg);
  539. return graph.getClear();
  540. }
  541. virtual IRoxieServerSideCache *queryServerSideCache() const
  542. {
  543. return NULL; // Activities that wish to support server-side caching will need to do better....
  544. }
  545. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  546. {
  547. // Most activities have nothing to say...
  548. }
  549. virtual const StatisticsMapping &queryStatsMapping() const
  550. {
  551. return actStatistics; // Overridden by anyone that needs more
  552. }
  553. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  554. {
  555. return (roxiemem::RoxieHeapFlags)heapFlags;
  556. }
  557. virtual bool isActivityCodeSigned() const
  558. {
  559. return isCodeSigned;
  560. }
  561. };
  562. class CRoxieServerMultiInputInfo
  563. {
  564. private:
  565. UnsignedArray inputs;
  566. UnsignedArray inputIndexes;
  567. public:
  568. void set(unsigned idx, unsigned source, unsigned sourceidx)
  569. {
  570. if (idx==inputs.length())
  571. {
  572. inputs.append(source);
  573. inputIndexes.append(sourceidx);
  574. }
  575. else
  576. {
  577. while (!inputs.isItem(idx))
  578. {
  579. inputs.append(0);
  580. inputIndexes.append(0);
  581. }
  582. inputs.replace(source, idx);
  583. inputIndexes.replace(sourceidx, idx);
  584. }
  585. }
  586. unsigned get(unsigned idx, unsigned &sourceidx) const
  587. {
  588. if (inputs.isItem(idx))
  589. {
  590. sourceidx = inputIndexes.item(idx);
  591. return inputs.item(idx);
  592. }
  593. else
  594. return (unsigned) -1;
  595. }
  596. inline unsigned ordinality() const { return inputs.ordinality(); }
  597. };
  598. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  599. {
  600. private:
  601. CRoxieServerMultiInputInfo inputs;
  602. public:
  603. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  604. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  605. {
  606. }
  607. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  608. {
  609. inputs.set(idx, source, sourceidx);
  610. }
  611. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  612. {
  613. return inputs.get(idx, sourceidx);
  614. }
  615. virtual unsigned numInputs() const { return inputs.ordinality(); }
  616. };
  617. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  618. {
  619. Owned<IException> wrapped;
  620. ThorActivityKind kind;
  621. unsigned queryId;
  622. public:
  623. IMPLEMENT_IINTERFACE;
  624. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  625. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  626. {
  627. }
  628. virtual int errorCode() const { return wrapped->errorCode(); }
  629. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  630. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  631. };
  632. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  633. {
  634. protected:
  635. unsigned input;
  636. unsigned inputidx;
  637. public:
  638. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  639. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  640. {
  641. input = (unsigned) -1;
  642. inputidx = 0;
  643. }
  644. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  645. {
  646. if (idx != 0)
  647. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  648. if (input != (unsigned) -1)
  649. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, sanitizeSourceFile(__FILE__), __LINE__);
  650. input = source;
  651. inputidx = sourceidx;
  652. }
  653. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  654. {
  655. if (!idx)
  656. {
  657. sourceidx = inputidx;
  658. return input;
  659. }
  660. return (unsigned) -1;
  661. }
  662. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  663. };
  664. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  665. {
  666. protected:
  667. unsigned numOutputs = 0;
  668. RelaxedAtomic<__int64> *processedArray = nullptr;
  669. RelaxedAtomic<__int64> *startedArray = nullptr;
  670. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  672. {
  673. }
  674. ~CRoxieServerMultiOutputFactory()
  675. {
  676. delete [] processedArray;
  677. delete [] startedArray;
  678. }
  679. void setNumOutputs(unsigned num)
  680. {
  681. numOutputs = num;
  682. if (!num)
  683. num = 1; // Even sink activities like to track how many records they process
  684. processedArray = new RelaxedAtomic<__int64>[num];
  685. startedArray = new RelaxedAtomic<__int64>[num];
  686. for (unsigned i = 0; i < num; i++)
  687. {
  688. processedArray[i] = 0;
  689. startedArray[i] = 0;
  690. }
  691. }
  692. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  693. {
  694. assertex(numOutputs ? idx < numOutputs : idx==0);
  695. putStatsValue(&edge, "NumRowsProcessed", "sum", processedArray[idx]);
  696. putStatsValue(&edge, "NumStarts", "sum", startedArray[idx]);
  697. }
  698. virtual void resetNodeProgressInfo()
  699. {
  700. CRoxieServerActivityFactory::resetNodeProgressInfo();
  701. for (unsigned i = 0; i < numOutputs; i++)
  702. {
  703. processedArray[i] = 0;
  704. startedArray[i] = 0;
  705. }
  706. }
  707. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  708. {
  709. assertex(numOutputs ? idx < numOutputs : idx==0);
  710. processedArray[idx] += _processed;
  711. }
  712. virtual void noteStarted(unsigned idx) const
  713. {
  714. assertex(numOutputs ? idx < numOutputs : idx==0);
  715. startedArray[idx]++;
  716. }
  717. };
  718. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  719. {
  720. protected:
  721. bool isInternal;
  722. bool isRoot;
  723. unsigned usageCount;
  724. public:
  725. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  726. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  727. {
  728. usageCount = _usageCount;
  729. isRoot = _isRoot;
  730. isInternal = false; // filled in by derived class constructor
  731. }
  732. virtual bool isSink() const
  733. {
  734. //If an internal result has as many dependencies (within the graph) as uses (which includes from outside the graph) then don't execute it unconditionally.
  735. bool internalSpillAllUsesWithinGraph = (isInternal && dependentCount && dependentCount==usageCount);
  736. //only a sink if a root activity
  737. return isRoot && !internalSpillAllUsesWithinGraph;
  738. }
  739. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  740. {
  741. // 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
  742. // Just leave it blank is safest.
  743. }
  744. };
  745. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  746. const char *queryStateText(activityState state)
  747. {
  748. switch (state)
  749. {
  750. case STATEreset: return "reset";
  751. case STATEstarted: return "started";
  752. case STATEstopped: return "stopped";
  753. case STATEstarting: return "starting"; // Used by a splitter to indicate it has seen a stop but not yet seen a start(), nor has it seen stop() on all output adaptors
  754. default: return "unknown";
  755. }
  756. }
  757. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  758. class CParallelActivityExecutor : public CAsyncFor
  759. {
  760. public:
  761. unsigned parentExtractSize;
  762. const byte * parentExtract;
  763. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  764. parentExtractSize(_parentExtractSize), parentExtract(_parentExtract), activities(_activities) { }
  765. void Do(unsigned i)
  766. {
  767. activities.item(i).execute(parentExtractSize, parentExtract);
  768. }
  769. private:
  770. IRoxieServerActivityCopyArray & activities;
  771. };
  772. extern IEngineRowStream * ensureSingleStream(IRoxieAgentContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  773. {
  774. if (instreams.length() != 1)
  775. {
  776. assertex(instreams.length());
  777. if (!junction)
  778. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  779. ForEachItemIn(stream, instreams)
  780. {
  781. junction->setInput(stream, instreams.item(stream));
  782. }
  783. return junction->queryOutput(0);
  784. }
  785. else
  786. return instreams.item(0);
  787. }
  788. extern IEngineRowStream *connectSingleStream(IRoxieAgentContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  789. {
  790. if (input)
  791. {
  792. PointerArrayOf<IEngineRowStream> instreams;
  793. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  794. return ensureSingleStream(ctx, instreams, junction);
  795. }
  796. else
  797. return NULL;
  798. }
  799. extern IEngineRowStream *connectSingleStream(IRoxieAgentContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  800. {
  801. Owned<IStrandJunction> junction;
  802. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  803. assertex(!junction);
  804. return result;
  805. }
  806. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  807. {
  808. friend class StrandProcessor;
  809. protected:
  810. IFinalRoxieInput *input;
  811. unsigned sourceIdx;
  812. IEngineRowStream *inputStream;
  813. Owned<IStrandJunction> junction;
  814. IHThorArg &basehelper;
  815. IRoxieAgentContext *ctx;
  816. class InterceptRegisterTimer : public IndirectCodeContext
  817. {
  818. public:
  819. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  820. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  821. {
  822. if (activityId == activity.queryId())
  823. return activity.registerTimer(activityId, name);
  824. else
  825. return ctx->registerTimer(activityId, name);
  826. }
  827. private:
  828. CRoxieServerActivity &activity;
  829. } interceptedCtx;
  830. const IRoxieServerActivityFactory *factory;
  831. IRoxieServerActivityCopyArray dependencies;
  832. IntArray dependencyIndexes;
  833. IntArray dependencyControlIds;
  834. IArrayOf<IActivityGraph> childGraphs;
  835. CachedOutputMetaData meta;
  836. IHThorArg *colocalParent;
  837. IEngineRowAllocator *rowAllocator;
  838. CriticalSection statecrit;
  839. CriticalSection statscrit;
  840. mutable CRuntimeStatisticCollection stats;
  841. MapStringToMyClass<ThorSectionTimer> functionTimers;
  842. ActivityTimeAccumulator activityStats;
  843. IProbeManager *probeManager = NULL;
  844. unsigned processed;
  845. unsigned numStarts = 0;
  846. unsigned activityId;
  847. activityState state;
  848. bool createPending;
  849. bool debugging;
  850. bool timeActivities;
  851. bool aborted;
  852. bool connected = false;
  853. bool collectFactoryStatistics = false;
  854. public:
  855. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  856. CRoxieServerActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  857. : basehelper(_factory->getHelper()),
  858. ctx(_ctx),
  859. interceptedCtx(*this),
  860. factory(_factory),
  861. stats(_factory->queryStatsMapping()),
  862. probeManager(_probeManager),
  863. activityId(_factory->queryId())
  864. {
  865. input = NULL;
  866. sourceIdx = 0;
  867. inputStream = NULL;
  868. meta.set(basehelper.queryOutputMeta());
  869. processed = 0;
  870. state=STATEreset;
  871. rowAllocator = NULL;
  872. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  873. colocalParent = NULL;
  874. createPending = true;
  875. timeActivities = defaultTimeActivities;
  876. collectFactoryStatistics = defaultCollectFactoryStatistics && !debugging && factory;
  877. aborted = false;
  878. }
  879. CRoxieServerActivity(IRoxieAgentContext *_ctx, IHThorArg & _helper)
  880. : basehelper(_helper), ctx(_ctx),
  881. interceptedCtx(*this), factory(NULL), stats(allStatistics)
  882. {
  883. activityId = 0;
  884. input = NULL;
  885. sourceIdx = 0;
  886. inputStream = NULL;
  887. ctx = NULL;
  888. meta.set(basehelper.queryOutputMeta());
  889. processed = 0;
  890. state=STATEreset;
  891. rowAllocator = NULL;
  892. debugging = false;
  893. colocalParent = NULL;
  894. createPending = true;
  895. timeActivities = defaultTimeActivities;
  896. collectFactoryStatistics = false; // since no factory
  897. aborted = false;
  898. }
  899. ~CRoxieServerActivity()
  900. {
  901. basehelper.Release();
  902. ::Release(rowAllocator);
  903. }
  904. virtual void beforeDispose() override
  905. {
  906. if (traceStartStop)
  907. {
  908. // There was an old comment here stating // Note- CTXLOG may not be safe
  909. // There were problems in the destruction order of graphs that might mean an IndirectAgentContext
  910. // was released while activities still referenced it.
  911. // However these should now all be fixed
  912. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  913. if (watchActivityId && watchActivityId==activityId)
  914. {
  915. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  916. }
  917. }
  918. if (state!=STATEreset)
  919. {
  920. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  921. state = STATEreset; // bit pointless but there you go...
  922. }
  923. }
  924. const IResolvedFile *resolveLFNIndex(const char *filename, bool isOpt, bool isPrivilegedUser)
  925. {
  926. const IResolvedFile *ret = resolveLFN(filename, isOpt, isPrivilegedUser);
  927. if (ret && !ret->isKey())
  928. throw MakeStringException(0, "Attempting to read flat file as an index: %s", filename);
  929. return ret;
  930. }
  931. const IResolvedFile *resolveLFNFlat(const char *filename, bool isOpt, bool isPrivilegedUser)
  932. {
  933. const IResolvedFile *ret = resolveLFN(filename, isOpt, isPrivilegedUser);
  934. if (ret && ret->isKey())
  935. throw MakeStringException(0, "Attempting to read index as a flat file: %s", filename);
  936. return ret;
  937. }
  938. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  939. {
  940. if (!factory)
  941. return;
  942. //Collate the stats for this activity from various different sources.
  943. CRuntimeStatisticCollection mergedStats(stats.queryMapping());
  944. gatherStats(mergedStats);
  945. //Because subgraphs are flattened in roxie the subgraph needs to be selected for each activity
  946. if (statsBuilder)
  947. statsBuilder->beginSubGraphScope(factory->querySubgraphId());
  948. //Still needed even if statsBuilder is null to update values in the factory
  949. updateEdgeStats(statsBuilder);
  950. if (statsBuilder)
  951. {
  952. StatsActivityScope ac(*statsBuilder, activityId);
  953. mergedStats.recordStatistics(*statsBuilder);
  954. //close the subgraph scope from the previous if()
  955. statsBuilder->endScope();
  956. }
  957. //Update the statistics accumulated over all the queries
  958. if (collectFactoryStatistics)
  959. factory->mergeStats(mergedStats);
  960. //Updates the query summary statistics
  961. if (ctx)
  962. ctx->queryCodeContext()->queryContextLogger().mergeStats(mergedStats);
  963. ForEachItemIn(i, childGraphs)
  964. childGraphs.item(i).gatherStatistics(statsBuilder);
  965. }
  966. virtual const IRoxieContextLogger &queryLogCtx()const
  967. {
  968. return *this;
  969. }
  970. inline const StatisticsMapping & queryStatsMapping() const
  971. {
  972. return factory ? factory->queryStatsMapping() : actStatistics;
  973. }
  974. virtual bool collectingDetailedStatistics() const
  975. {
  976. return ctx && ctx->collectingDetailedStatistics();
  977. }
  978. virtual void mergeStats(MemoryBuffer &buf)
  979. {
  980. stats.deserializeMerge(buf);
  981. }
  982. virtual void mergeStats(const CRuntimeStatisticCollection & childStats)
  983. {
  984. CriticalBlock b(statscrit);
  985. stats.merge(childStats);
  986. }
  987. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  988. {
  989. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  990. ISectionTimer *timer = functionTimers.getValue(name);
  991. if (!timer)
  992. {
  993. timer = ThorSectionTimer::createTimer(stats, name);
  994. functionTimers.setValue(name, timer);
  995. timer->Release(); // Value returned is not linked
  996. }
  997. return timer;
  998. }
  999. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles)
  1000. {
  1001. CriticalBlock cb(statscrit);
  1002. processed += strandProcessed;
  1003. activityStats.merge(strandCycles);
  1004. }
  1005. inline void ensureRowAllocator()
  1006. {
  1007. if (!rowAllocator)
  1008. rowAllocator = createRowAllocator(meta.queryOriginal());
  1009. }
  1010. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  1011. {
  1012. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  1013. }
  1014. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  1015. {
  1016. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  1017. }
  1018. inline ICodeContext *queryCodeContext()
  1019. {
  1020. return ctx->queryCodeContext();
  1021. }
  1022. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  1023. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  1024. {
  1025. if (ctx)
  1026. ctx->CTXLOGa(category, prefix, text);
  1027. else
  1028. DBGLOG("[%s] %s", prefix, text);
  1029. }
  1030. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  1031. {
  1032. if (ctx)
  1033. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  1034. else
  1035. {
  1036. StringBuffer ss;
  1037. ss.appendf("[%s] ERROR", prefix);
  1038. if (E)
  1039. ss.append(": ").append(E->errorCode());
  1040. if (file)
  1041. ss.appendf(": %s(%d) ", file, line);
  1042. if (E)
  1043. E->errorMessage(ss.append(": "));
  1044. if (format)
  1045. {
  1046. ss.append(": ").valist_appendf(format, args);
  1047. }
  1048. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1049. }
  1050. }
  1051. virtual void CTXLOGl(LogItem *log) const
  1052. {
  1053. if (ctx)
  1054. ctx->CTXLOGl(log);
  1055. else
  1056. {
  1057. assert(ctx);
  1058. log->Release(); // Should never happen
  1059. }
  1060. }
  1061. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1062. {
  1063. stats.addStatistic(kind, value);
  1064. }
  1065. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1066. {
  1067. stats.merge(from);
  1068. }
  1069. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1070. {
  1071. merged.merge(stats);
  1072. if (rowAllocator)
  1073. rowAllocator->gatherStats(merged);
  1074. activityStats.addStatistics(merged);
  1075. merged.mergeStatistic(StCycleLocalExecuteCycles, queryLocalCycles());
  1076. }
  1077. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1078. {
  1079. if (ctx)
  1080. ctx->getLogPrefix(ret);
  1081. return ret.append('@').append(activityId);
  1082. }
  1083. virtual bool isIntercepted() const
  1084. {
  1085. return ctx ? ctx->isIntercepted() : false;
  1086. }
  1087. virtual bool isBlind() const
  1088. {
  1089. return ctx ? ctx->isBlind() : blindLogging;
  1090. }
  1091. virtual unsigned queryTraceLevel() const
  1092. {
  1093. if (ctx)
  1094. return ctx->queryTraceLevel();
  1095. else
  1096. return traceLevel;
  1097. }
  1098. virtual void setGlobalId(const char *id, SocketEndpoint&ep, unsigned pid) override
  1099. {
  1100. if (ctx)
  1101. ctx->setGlobalId(id, ep, pid);
  1102. }
  1103. virtual void setCallerId(const char *id) override
  1104. {
  1105. if (ctx)
  1106. ctx->setCallerId(id);
  1107. }
  1108. virtual const char *queryGlobalId() const
  1109. {
  1110. return ctx ? ctx->queryGlobalId() : nullptr;
  1111. }
  1112. virtual const char *queryCallerId() const override
  1113. {
  1114. return ctx ? ctx->queryCallerId() : nullptr;
  1115. }
  1116. virtual const char *queryLocalId() const
  1117. {
  1118. return ctx ? ctx->queryLocalId() : nullptr;
  1119. }
  1120. virtual void setHttpIdHeaders(const char *global, const char *caller)
  1121. {
  1122. if (ctx)
  1123. ctx->setHttpIdHeaders(global, caller);
  1124. }
  1125. virtual const char *queryGlobalIdHttpHeader() const
  1126. {
  1127. return ctx ? ctx->queryGlobalIdHttpHeader() : "HPCC-Global-Id";
  1128. }
  1129. virtual const char *queryCallerIdHttpHeader() const
  1130. {
  1131. return ctx ? ctx->queryCallerIdHttpHeader() : "HPCC-Caller-Id";
  1132. }
  1133. virtual bool isPassThrough()
  1134. {
  1135. return false;
  1136. }
  1137. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt, bool isPrivilegedUser)
  1138. {
  1139. return ctx->resolveLFN(filename, isOpt, isPrivilegedUser);
  1140. }
  1141. virtual const IResolvedFile *queryVarFileInfo() const
  1142. {
  1143. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1144. return NULL;
  1145. }
  1146. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1147. {
  1148. throwUnexpected(); // should be implemented in more derived class wherever needed
  1149. }
  1150. virtual IRoxieAgentContext *queryContext()
  1151. {
  1152. return ctx;
  1153. }
  1154. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1155. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1156. virtual IRoxieServerActivity *queryActivity() { return this; }
  1157. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1158. virtual bool needsAllocator() const { return false; }
  1159. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1160. {
  1161. colocalParent = _colocalParent;
  1162. createPending = true;
  1163. if (needsAllocator())
  1164. ensureRowAllocator();
  1165. processed = 0;
  1166. if (factory)
  1167. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1168. if (ctx)
  1169. {
  1170. timeActivities = ctx->queryOptions().timeActivities;
  1171. collectFactoryStatistics = ctx->queryOptions().collectFactoryStatistics && !debugging && factory;
  1172. }
  1173. }
  1174. virtual void onCreate(IHThorArg *_colocalParent)
  1175. {
  1176. _onCreate(_colocalParent, 1);
  1177. }
  1178. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1179. {
  1180. //This should only be called after onStart has been called on the helper
  1181. assertex(!createPending);
  1182. assertex(state==STATEstarted);
  1183. unsigned startlen = out.length();
  1184. basehelper.serializeCreateContext(out);
  1185. basehelper.serializeStartContext(out);
  1186. if (queryTraceLevel() > 10)
  1187. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1188. }
  1189. virtual void serializeExtra(MemoryBuffer &out) {}
  1190. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1191. {
  1192. CriticalBlock cb(statecrit);
  1193. if (state != STATEreset && state != STATEstarting)
  1194. {
  1195. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1196. }
  1197. state=STATEstarted;
  1198. numStarts++;
  1199. #ifdef TRACE_STARTSTOP
  1200. if (traceStartStop)
  1201. {
  1202. CTXLOG("start %p %d", this, activityId);
  1203. if (watchActivityId && watchActivityId==activityId)
  1204. {
  1205. CTXLOG("WATCH: start %p %d", this, activityId);
  1206. }
  1207. }
  1208. #endif
  1209. executeDependencies(parentExtractSize, parentExtract, 0);
  1210. if (input)
  1211. input->start(parentExtractSize, parentExtract, paused);
  1212. ensureCreated();
  1213. basehelper.onStart(parentExtract, NULL);
  1214. if (collectFactoryStatistics)
  1215. factory->noteStarted();
  1216. startJunction(junction);
  1217. }
  1218. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1219. {
  1220. //MORE: Create a filtered list and then use asyncfor
  1221. ForEachItemIn(idx, dependencies)
  1222. {
  1223. if (dependencyControlIds.item(idx) == (int) controlId)
  1224. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1225. }
  1226. }
  1227. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1228. {
  1229. ForEachItemIn(idx, dependencies)
  1230. {
  1231. if (dependencyControlIds.item(idx) == (int) controlId)
  1232. dependencies.item(idx).stop();
  1233. }
  1234. }
  1235. virtual unsigned __int64 queryTotalCycles() const
  1236. {
  1237. return activityStats.totalCycles;
  1238. }
  1239. virtual unsigned __int64 queryLocalCycles() const
  1240. {
  1241. __int64 ret = activityStats.totalCycles;
  1242. if (input) ret -= input->queryTotalCycles();
  1243. if (ret < 0)
  1244. ret = 0;
  1245. return ret;
  1246. }
  1247. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1248. {
  1249. if (idx==0)
  1250. return input;
  1251. else
  1252. return NULL;
  1253. }
  1254. inline void ensureCreated()
  1255. {
  1256. if (createPending)
  1257. {
  1258. createPending = false;
  1259. interceptedCtx.set(ctx->queryCodeContext());
  1260. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1261. }
  1262. }
  1263. virtual void stop()
  1264. {
  1265. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1266. if (state != STATEstopped)
  1267. {
  1268. CriticalBlock cb(statecrit);
  1269. if (state != STATEstopped)
  1270. {
  1271. #ifdef TRACE_STARTSTOP
  1272. if (traceStartStop)
  1273. {
  1274. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1275. if (watchActivityId && watchActivityId==activityId)
  1276. {
  1277. CTXLOG("WATCH: stop %p %d", this, activityId);
  1278. }
  1279. }
  1280. #endif
  1281. state=STATEstopped;
  1282. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1283. ForEachItemIn(idx, dependencies)
  1284. {
  1285. if (dependencyControlIds.item(idx) == 0)
  1286. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1287. }
  1288. if (inputStream)
  1289. inputStream->stop();
  1290. }
  1291. }
  1292. }
  1293. virtual void abort()
  1294. {
  1295. aborted = true;
  1296. // MORE - should abort dependencies here?
  1297. stop();
  1298. }
  1299. inline void reset()
  1300. {
  1301. if (state != STATEreset)
  1302. {
  1303. CriticalBlock cb(statecrit);
  1304. if (state != STATEreset)
  1305. {
  1306. if (state==STATEstarted || state==STATEstarting)
  1307. {
  1308. if (ctx->queryOptions().failOnLeaks)
  1309. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1310. if (traceStartStop || traceLevel > 2)
  1311. CTXLOG("STATE: activity %d reset without stop", activityId);
  1312. stop();
  1313. }
  1314. state = STATEreset;
  1315. #ifdef TRACE_STARTSTOP
  1316. if (traceStartStop)
  1317. {
  1318. CTXLOG("reset %p %d", this, activityId);
  1319. if (watchActivityId && watchActivityId==activityId)
  1320. {
  1321. CTXLOG("WATCH: reset %p %d", this, activityId);
  1322. }
  1323. }
  1324. #endif
  1325. resetJunction(junction);
  1326. ForEachItemIn(idx, dependencies)
  1327. dependencies.item(idx).reset();
  1328. if (input)
  1329. input->reset();
  1330. }
  1331. }
  1332. aborted = false;
  1333. }
  1334. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1335. {
  1336. dependencies.append(source);
  1337. dependencyIndexes.append(sourceIdx);
  1338. dependencyControlIds.append(controlId);
  1339. }
  1340. virtual void resetEOF()
  1341. {
  1342. //would make more sense if the default implementation (and eof member) were in the base class
  1343. }
  1344. // Sink activities should override this....
  1345. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1346. {
  1347. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1348. }
  1349. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1350. {
  1351. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1352. }
  1353. virtual void stopSink(unsigned idx)
  1354. {
  1355. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1356. }
  1357. virtual void connectInputStreams(bool consumerOrdered)
  1358. {
  1359. if (input && !inputStream)
  1360. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1361. if (!connected)
  1362. {
  1363. connectDependencies();
  1364. connected = true;
  1365. }
  1366. }
  1367. void connectDependencies()
  1368. {
  1369. ForEachItemIn(i, dependencies)
  1370. dependencies.item(i).connectInputStreams(true);
  1371. }
  1372. virtual __int64 evaluate()
  1373. {
  1374. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1375. }
  1376. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1377. {
  1378. return NULL;
  1379. }
  1380. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1381. {
  1382. return false;
  1383. }
  1384. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1385. {
  1386. assertex(!idx);
  1387. input = _in;
  1388. sourceIdx = _sourceIdx;
  1389. inputStream = NULL;
  1390. }
  1391. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1392. {
  1393. if (!factory)
  1394. return true;
  1395. //Grouping implies the stream processing must be ordered - I think this always applies
  1396. IFinalRoxieInput * curInput = queryInput(idx);
  1397. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1398. return true;
  1399. return factory->isInputOrdered(consumerOrdered, idx);
  1400. }
  1401. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1402. {
  1403. assertex(!idx);
  1404. // By default, activities are assumed NOT to support streams
  1405. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1406. connectInputStreams(inputOrdered);
  1407. // Return a single stream
  1408. streams.append(this);
  1409. return NULL;
  1410. }
  1411. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1412. {
  1413. if (idx == (unsigned) -1)
  1414. idx = 0;
  1415. return idx ? NULL : this;
  1416. }
  1417. virtual IOutputMetaData *queryOutputMeta() const
  1418. {
  1419. return meta.queryOriginal();
  1420. }
  1421. virtual unsigned queryId() const
  1422. {
  1423. return activityId;
  1424. }
  1425. virtual unsigned querySubgraphId() const
  1426. {
  1427. return factory->querySubgraphId();
  1428. }
  1429. virtual void checkAbort()
  1430. {
  1431. ctx->checkAbort();
  1432. }
  1433. IException *makeWrappedException(IException *e)
  1434. {
  1435. StringBuffer msg;
  1436. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1437. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1438. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1439. return e;
  1440. else
  1441. return new CWrappedException(e, activityKind, activityId);
  1442. }
  1443. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1444. {
  1445. }
  1446. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1447. {
  1448. }
  1449. virtual void resetOutputsUsed()
  1450. {
  1451. }
  1452. virtual void noteOutputUsed()
  1453. {
  1454. }
  1455. virtual IRoxieServerSideCache *queryServerSideCache() const
  1456. {
  1457. return factory->queryServerSideCache();
  1458. }
  1459. virtual const IRoxieServerActivityFactory *queryFactory() const
  1460. {
  1461. return factory;
  1462. }
  1463. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1464. {
  1465. addEdgeStats(statsBuilder, 0, numStarts, processed, 1);
  1466. }
  1467. inline ThorActivityKind getKind() const
  1468. {
  1469. return factory->getKind();
  1470. }
  1471. inline bool isSink() const
  1472. {
  1473. return (factory != NULL) && factory->isSink();
  1474. }
  1475. void addEdgeStats(IStatisticGatherer * statsBuilder, unsigned oid, unsigned starts, unsigned _processed, unsigned _strands) const
  1476. {
  1477. if (statsBuilder)
  1478. {
  1479. StatsEdgeScope scope(*statsBuilder, activityId, oid);
  1480. if (_strands)
  1481. statsBuilder->addStatistic(StNumStrands, _strands);
  1482. if (starts != 0)
  1483. {
  1484. statsBuilder->addStatistic(StNumRowsProcessed, _processed);
  1485. statsBuilder->addStatistic(StNumStarts, starts);
  1486. // Assume number of starts = number of stops since stats only ever gathered when a query is complete
  1487. statsBuilder->addStatistic(StNumStops, starts);
  1488. statsBuilder->addStatistic(StNumSlaves, 1); // Arguable
  1489. }
  1490. }
  1491. if (collectFactoryStatistics)
  1492. factory->noteProcessed(oid, processed);
  1493. }
  1494. protected:
  1495. RecordTranslationMode getEnableFieldTranslation() const
  1496. {
  1497. return factory->queryQueryFactory().queryOptions().enableFieldTranslation;
  1498. }
  1499. };
  1500. //=====================================================================================================
  1501. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1502. {
  1503. protected:
  1504. bool prefiltered;
  1505. bool eof;
  1506. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1507. {
  1508. prefiltered = !any;
  1509. eof = prefiltered;
  1510. if (!prefiltered)
  1511. {
  1512. input->start(parentExtractSize, parentExtract, false);
  1513. startJunction(junction);
  1514. }
  1515. else
  1516. {
  1517. if (traceStartStop)
  1518. CTXLOG("lateStart activity stopping input early as prefiltered");
  1519. inputStream->stop();
  1520. }
  1521. }
  1522. public:
  1523. CRoxieServerLateStartActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1524. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1525. {
  1526. prefiltered = false;
  1527. eof = false;
  1528. }
  1529. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1530. {
  1531. IFinalRoxieInput *saveInput = input;
  1532. Owned<IStrandJunction> saveJunction = junction.getClear();
  1533. input = NULL; // Make sure parent does not start the chain yet
  1534. try
  1535. {
  1536. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1537. }
  1538. catch (...)
  1539. {
  1540. // Make sure we restore these even if there is an exception thrown during start
  1541. input = saveInput;
  1542. junction.setown(saveJunction.getClear());
  1543. throw;
  1544. }
  1545. input = saveInput;
  1546. junction.setown(saveJunction.getClear());
  1547. }
  1548. virtual void stop()
  1549. {
  1550. if (!prefiltered && inputStream)
  1551. {
  1552. inputStream->stop();
  1553. }
  1554. else if (traceStartStop)
  1555. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1556. IEngineRowStream *save = inputStream;
  1557. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1558. CRoxieServerActivity::stop();
  1559. inputStream = save;
  1560. }
  1561. virtual void reset()
  1562. {
  1563. CRoxieServerActivity::reset();
  1564. prefiltered = false;
  1565. }
  1566. };
  1567. //=================================================================================
  1568. class StrandOptions
  1569. {
  1570. // Typically set from hints, common to many stranded activities
  1571. public:
  1572. explicit StrandOptions(IPropertyTree &_graphNode)
  1573. {
  1574. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1575. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1576. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1577. numStrands = getAffinityCpus();
  1578. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1579. }
  1580. StrandOptions(const StrandOptions &from, IRoxieAgentContext *ctx)
  1581. {
  1582. numStrands = from.numStrands;
  1583. blockSize = from.blockSize;
  1584. if (!blockSize)
  1585. blockSize = ctx->queryOptions().strandBlockSize;
  1586. if (numStrands == 0)
  1587. numStrands = ctx->queryOptions().forceNumStrands;
  1588. }
  1589. public:
  1590. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1591. unsigned blockSize = 0;
  1592. };
  1593. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1594. {
  1595. protected:
  1596. CRoxieServerActivity &parent;
  1597. IEngineRowAllocator *rowAllocator;
  1598. IEngineRowStream *inputStream;
  1599. ActivityTimeAccumulator activityStats;
  1600. mutable CRuntimeStatisticCollection stats;
  1601. unsigned processed = 0;
  1602. unsigned numProcessedLastGroup = 0;
  1603. const bool timeActivities;
  1604. bool stopped = false;
  1605. std::atomic<bool> abortRequested;
  1606. public:
  1607. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1608. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1609. {
  1610. if (needsAllocator)
  1611. {
  1612. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1613. }
  1614. else
  1615. rowAllocator = NULL;
  1616. }
  1617. ~StrandProcessor()
  1618. {
  1619. ::Release(rowAllocator);
  1620. }
  1621. virtual void start()
  1622. {
  1623. processed = 0;
  1624. numProcessedLastGroup = 0;
  1625. activityStats.reset();
  1626. }
  1627. virtual void stop()
  1628. {
  1629. if (!stopped)
  1630. {
  1631. if (inputStream)
  1632. inputStream->stop();
  1633. parent.stop();
  1634. //It would be preferrable to move activityStats (+processed?) to gatherStats(), but because of
  1635. //the way firstRow is associated with startCycles it would require an extra parameter
  1636. //which is not consistent with the other gatherStats() calls, or extra logic in the stats classes.
  1637. parent.mergeStrandStats(processed, activityStats);
  1638. }
  1639. stopped = true;
  1640. }
  1641. virtual void reset()
  1642. {
  1643. stopped = false;
  1644. abortRequested.store(false, std::memory_order_relaxed);
  1645. }
  1646. virtual void resetEOF()
  1647. {
  1648. inputStream->resetEOF();
  1649. }
  1650. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1651. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1652. void gatherStats(CRuntimeStatisticCollection & mergedStats) const
  1653. {
  1654. mergedStats.merge(stats);
  1655. if (rowAllocator)
  1656. rowAllocator->gatherStats(mergedStats);
  1657. }
  1658. const ActivityTimeAccumulator& queryTimings() const { return activityStats; }
  1659. };
  1660. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1661. {
  1662. protected:
  1663. StrandOptions strandOptions;
  1664. IArrayOf<StrandProcessor> strands;
  1665. Owned<IStrandBranch> branch;
  1666. Owned<IStrandJunction> splitter;
  1667. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1668. std::atomic<unsigned> active;
  1669. public:
  1670. CRoxieServerStrandedActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1671. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1672. strandOptions(_strandOptions, ctx)
  1673. {
  1674. active = 0;
  1675. }
  1676. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1677. {
  1678. CRoxieServerActivity::gatherStats(merged);
  1679. ForEachItemIn(i, strands)
  1680. strands.item(i).gatherStats(merged);
  1681. }
  1682. virtual void onCreate(IHThorArg *_colocalArg)
  1683. {
  1684. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1685. }
  1686. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1687. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1688. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1689. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1690. virtual void reset()
  1691. {
  1692. assertex(active==0);
  1693. activityStats.reset();
  1694. ForEachItemIn(idx, strands)
  1695. {
  1696. strands.item(idx).reset();
  1697. activityStats.merge(strands.item(idx).queryTimings());
  1698. }
  1699. resetJunction(splitter);
  1700. CRoxieServerActivity::reset();
  1701. resetJunction(sourceJunction);
  1702. }
  1703. virtual void stop()
  1704. {
  1705. // Called from the strands... which should ensure that stop is not called more than once per strand
  1706. //The first strand to call
  1707. if (active)
  1708. --active;
  1709. if (!active)
  1710. CRoxieServerActivity::stop();
  1711. }
  1712. void requestAbort()
  1713. {
  1714. ForEachItemIn(idx, strands)
  1715. strands.item(idx).requestAbort();
  1716. }
  1717. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1718. {
  1719. assertex(idx == 0);
  1720. assertex(strands.empty());
  1721. CRoxieServerActivity::connectDependencies();
  1722. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1723. //Note, numStrands == 1 is an explicit request to disable threading
  1724. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1725. {
  1726. //Check to see if the consumer's settings should override
  1727. if (strandOptions.numStrands == 0)
  1728. {
  1729. strandOptions.numStrands = consumerOptions->numStrands;
  1730. strandOptions.blockSize = consumerOptions->blockSize;
  1731. }
  1732. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1733. {
  1734. strandOptions.numStrands = consumerOptions->numStrands;
  1735. }
  1736. }
  1737. Owned <IStrandJunction> recombiner;
  1738. if (input)
  1739. {
  1740. if (strandOptions.numStrands == 1)
  1741. {
  1742. // 1 means explicitly requested single-strand.
  1743. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1744. strands.append(*createStrandProcessor(instream));
  1745. }
  1746. else
  1747. {
  1748. PointerArrayOf<IEngineRowStream> instreams;
  1749. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1750. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1751. {
  1752. assertex(recombiner == NULL);
  1753. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1754. if (inputOrdered)
  1755. {
  1756. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1757. splitter.set(branch->queryInputJunction());
  1758. recombiner.set(branch->queryOutputJunction());
  1759. }
  1760. else
  1761. {
  1762. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1763. }
  1764. splitter->setInput(0, instreams.item(0));
  1765. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1766. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1767. }
  1768. else
  1769. {
  1770. // Ignore my hint and just use the width already split into...
  1771. ForEachItemIn(strandNo, instreams)
  1772. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1773. }
  1774. }
  1775. }
  1776. else
  1777. {
  1778. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1779. for (unsigned i=0; i < numStrands; i++)
  1780. strands.append(*createStrandSourceProcessor(inputOrdered));
  1781. if (inputOrdered && (numStrands > 1))
  1782. {
  1783. if (consumerOptions)
  1784. {
  1785. //If the output activities are also stranded then need to create a version of the branch
  1786. bool isGrouped = queryOutputMeta()->isGrouped();
  1787. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1788. sourceJunction.set(branch->queryInputJunction());
  1789. recombiner.set(branch->queryOutputJunction());
  1790. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1791. //This is different from the branch above. The first "junction" has the source activity as the input, and the outputs as the result of the activity
  1792. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1793. {
  1794. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1795. streams.append(sourceJunction->queryOutput(strandNo));
  1796. }
  1797. #ifdef TRACE_STRANDS
  1798. if (traceLevel > 2)
  1799. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1800. #endif
  1801. return recombiner.getClear();
  1802. }
  1803. else
  1804. {
  1805. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1806. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1807. }
  1808. }
  1809. }
  1810. ForEachItemIn(i, strands)
  1811. streams.append(&strands.item(i));
  1812. #ifdef TRACE_STRANDS
  1813. if (traceLevel > 2)
  1814. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1815. #endif
  1816. return recombiner.getClear();
  1817. }
  1818. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1819. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1820. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1821. virtual const void * nextRow()
  1822. {
  1823. throwUnexpected();
  1824. }
  1825. inline unsigned numStrands() const { return strands.ordinality(); }
  1826. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1827. {
  1828. addEdgeStats(statsBuilder, 0, numStarts, processed, strands.ordinality());
  1829. }
  1830. protected:
  1831. void onStartStrands()
  1832. {
  1833. ForEachItemIn(idx, strands)
  1834. {
  1835. strands.item(idx).start();
  1836. active++;
  1837. }
  1838. }
  1839. };
  1840. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1841. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1842. {
  1843. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1844. startJunction(splitter);
  1845. }
  1846. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1847. {
  1848. protected:
  1849. bool prefiltered;
  1850. bool eof;
  1851. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1852. {
  1853. prefiltered = !any;
  1854. eof = prefiltered;
  1855. if (!prefiltered)
  1856. {
  1857. //At this point
  1858. input->start(parentExtractSize, parentExtract, false);
  1859. startJunction(splitter);
  1860. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1861. startJunction(sourceJunction);
  1862. }
  1863. else
  1864. {
  1865. if (traceStartStop)
  1866. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1867. ForEachItemIn(idx, strands)
  1868. strands.item(idx).stop();
  1869. }
  1870. }
  1871. public:
  1872. CRoxieServerStrandedLateStartActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1873. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1874. {
  1875. prefiltered = false;
  1876. eof = false;
  1877. }
  1878. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1879. {
  1880. IFinalRoxieInput *save = input;
  1881. input = NULL; // Make sure parent does not start the chain yet - but we do want to do the dependencies (because the decision about whether to start may depend on them)
  1882. try
  1883. {
  1884. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1885. }
  1886. catch (...)
  1887. {
  1888. // Make sure we restore these even if there is an exception thrown during start
  1889. input = save;
  1890. throw;
  1891. }
  1892. input = save;
  1893. }
  1894. virtual void reset()
  1895. {
  1896. CRoxieServerStrandedActivity::reset();
  1897. prefiltered = false;
  1898. }
  1899. };
  1900. //=====================================================================================================
  1901. atomic_t nextInstanceId;
  1902. extern unsigned getNextInstanceId()
  1903. {
  1904. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1905. }
  1906. atomic_t nextRuid;
  1907. ruid_t getNextRuid()
  1908. {
  1909. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1910. while (ret < RUID_FIRST)
  1911. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1912. return ret;
  1913. }
  1914. void setStartRuid(unsigned restarts)
  1915. {
  1916. atomic_set(&nextRuid, restarts * 0x10000);
  1917. atomic_set(&nextInstanceId, restarts * 10000);
  1918. }
  1919. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1920. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1921. {
  1922. int code;
  1923. public:
  1924. LimitSkipException(int _code) { code = _code; }
  1925. IMPLEMENT_IINTERFACE;
  1926. virtual int errorCode() const { return code; }
  1927. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1928. virtual MessageAudience errorAudience() const { return MSGAUD_programmer; }
  1929. };
  1930. IException *makeLimitSkipException(bool isKeyed)
  1931. {
  1932. // We need to make sure what we throw is IException not something derived from it....
  1933. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1934. }
  1935. //=================================================================================
  1936. interface IRecordPullerCallback : extends IExceptionHandler
  1937. {
  1938. virtual void processRow(const void *row) = 0;
  1939. virtual void processEOG() = 0;
  1940. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1941. virtual void processDone() = 0;
  1942. };
  1943. class RecordPullerThread : public RestartableThread
  1944. {
  1945. protected:
  1946. IFinalRoxieInput *input;
  1947. Owned<IStrandJunction> junction;
  1948. unsigned sourceIdx = 0;
  1949. IEngineRowStream *inputStream;
  1950. IRecordPullerCallback *helper;
  1951. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1952. bool groupAtOnce, eog;
  1953. std::atomic<bool> eof;
  1954. CriticalSection crit;
  1955. public:
  1956. RecordPullerThread(bool _groupAtOnce)
  1957. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1958. {
  1959. input = NULL;
  1960. inputStream = NULL;
  1961. helper = NULL;
  1962. eof = eog = FALSE;
  1963. }
  1964. inline unsigned __int64 queryTotalCycles() const
  1965. {
  1966. return input->queryTotalCycles();
  1967. }
  1968. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1969. {
  1970. helper = _helper;
  1971. input = _input;
  1972. sourceIdx = _sourceIdx;
  1973. }
  1974. IFinalRoxieInput *queryInput() const
  1975. {
  1976. return input;
  1977. }
  1978. virtual void connectInputStreams(IRoxieAgentContext *ctx, bool consumerOrdered)
  1979. {
  1980. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1981. }
  1982. IEngineRowStream *queryStream() const
  1983. {
  1984. return inputStream;
  1985. }
  1986. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieAgentContext *ctx)
  1987. {
  1988. eof = false;
  1989. eog = false;
  1990. input->start(parentExtractSize, parentExtract, paused);
  1991. startJunction(junction);
  1992. try
  1993. {
  1994. if (preload && !paused)
  1995. {
  1996. if (traceLevel > 4)
  1997. DBGLOG("Preload fetching first %d records", preload);
  1998. if (groupAtOnce)
  1999. pullGroups(preload);
  2000. else
  2001. pullRecords(preload);
  2002. }
  2003. if (eof)
  2004. {
  2005. if (traceLevel > 4)
  2006. DBGLOG("No need to start puller after preload");
  2007. helper->processDone();
  2008. }
  2009. else
  2010. {
  2011. if (!noThread)
  2012. {
  2013. StringBuffer logPrefix("[");
  2014. if (ctx) ctx->getLogPrefix(logPrefix);
  2015. logPrefix.append("] ");
  2016. RestartableThread::start(logPrefix);
  2017. started.wait();
  2018. }
  2019. }
  2020. }
  2021. catch (IException *e)
  2022. {
  2023. helper->fireException(e);
  2024. }
  2025. catch (...)
  2026. {
  2027. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  2028. }
  2029. }
  2030. void stop()
  2031. {
  2032. if (traceStartStop)
  2033. DBGLOG("RecordPullerThread::stop");
  2034. {
  2035. CriticalBlock c(crit); // stop is called on our consumer's thread. We need to take care calling stop for our input to make sure it is not in mid-nextRow etc etc.
  2036. if (inputStream)
  2037. inputStream->stop();
  2038. eof = true;
  2039. }
  2040. RestartableThread::join();
  2041. }
  2042. void reset()
  2043. {
  2044. input->reset();
  2045. resetJunction(junction);
  2046. }
  2047. virtual int run()
  2048. {
  2049. started.signal();
  2050. try
  2051. {
  2052. if (groupAtOnce)
  2053. pullGroups((unsigned) -1);
  2054. else
  2055. pullRecords((unsigned) -1);
  2056. helper->processDone();
  2057. }
  2058. catch (IException *e)
  2059. {
  2060. helper->fireException(e);
  2061. }
  2062. catch (...)
  2063. {
  2064. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  2065. }
  2066. return 0;
  2067. }
  2068. void done()
  2069. {
  2070. helper->processDone();
  2071. }
  2072. bool pullRecords(unsigned preload)
  2073. {
  2074. if (eof)
  2075. return false;
  2076. while (preload && !eof)
  2077. {
  2078. const void * row = nullptr;
  2079. {
  2080. CriticalBlock c(crit); // See comments in stop for why this is needed
  2081. if (!eof)
  2082. row = inputStream->nextRow();
  2083. }
  2084. if (row)
  2085. {
  2086. eog = false;
  2087. helper->processRow(row);
  2088. }
  2089. else if (!eog)
  2090. {
  2091. helper->processEOG();
  2092. eog = true;
  2093. }
  2094. else
  2095. {
  2096. eof = true;
  2097. return false;
  2098. }
  2099. if (preload != (unsigned) -1)
  2100. preload--;
  2101. }
  2102. return true;
  2103. }
  2104. void pullGroups(unsigned preload)
  2105. {
  2106. ConstPointerArray thisGroup;
  2107. unsigned rowsDone = 0;
  2108. while (preload && !eof)
  2109. {
  2110. const void *row = nullptr;
  2111. {
  2112. CriticalBlock c(crit);
  2113. if (!eof)
  2114. row = inputStream->nextRow();
  2115. }
  2116. if (row)
  2117. {
  2118. thisGroup.append(row);
  2119. rowsDone++;
  2120. }
  2121. else if (thisGroup.length())
  2122. {
  2123. helper->processGroup(thisGroup);
  2124. thisGroup.kill();
  2125. if (preload != (unsigned) -1)
  2126. {
  2127. if (preload > rowsDone)
  2128. preload -= rowsDone;
  2129. else
  2130. break;
  2131. }
  2132. rowsDone = 0;
  2133. }
  2134. else
  2135. {
  2136. eof = true;
  2137. break;
  2138. }
  2139. }
  2140. }
  2141. };
  2142. //=================================================================================
  2143. #define READAHEAD_SIZE 1000
  2144. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2145. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2146. {
  2147. QueueOf<const void, true> buffer;
  2148. InterruptableSemaphore ready;
  2149. InterruptableSemaphore space;
  2150. CriticalSection crit;
  2151. bool eof;
  2152. bool disabled;
  2153. IRoxieAgentContext *ctx;
  2154. RecordPullerThread puller;
  2155. unsigned preload;
  2156. cycle_t totalCycles;
  2157. bool timeActivities;
  2158. public:
  2159. IMPLEMENT_IINTERFACE;
  2160. CRoxieServerReadAheadInput(IRoxieAgentContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2161. {
  2162. eof = false;
  2163. disabled = (ctx->queryDebugContext() != NULL);
  2164. totalCycles = 0;
  2165. timeActivities = ctx->queryOptions().timeActivities;
  2166. }
  2167. virtual IRoxieServerActivity *queryActivity()
  2168. {
  2169. return puller.queryInput()->queryActivity();
  2170. }
  2171. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2172. {
  2173. assertex(!idx);
  2174. puller.connectInputStreams(ctx, consumerOrdered);
  2175. streams.append(this);
  2176. return NULL;
  2177. }
  2178. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2179. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2180. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2181. {
  2182. return puller.queryInput()->queryIndexReadActivity();
  2183. }
  2184. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2185. {
  2186. eof = false;
  2187. if (disabled)
  2188. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2189. else
  2190. {
  2191. space.reinit(READAHEAD_SIZE);
  2192. ready.reinit();
  2193. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2194. }
  2195. }
  2196. virtual void stop()
  2197. {
  2198. if (disabled)
  2199. puller.queryStream()->stop();
  2200. else
  2201. {
  2202. space.interrupt();
  2203. ready.interrupt();
  2204. puller.stop();
  2205. }
  2206. }
  2207. virtual void reset()
  2208. {
  2209. if (disabled)
  2210. puller.queryInput()->reset();
  2211. else
  2212. {
  2213. puller.reset();
  2214. ForEachItemIn(idx1, buffer)
  2215. ReleaseRoxieRow(buffer.item(idx1));
  2216. buffer.clear();
  2217. }
  2218. }
  2219. virtual void resetEOF()
  2220. {
  2221. throwUnexpected();
  2222. }
  2223. virtual IOutputMetaData * queryOutputMeta() const
  2224. {
  2225. return puller.queryInput()->queryOutputMeta();
  2226. }
  2227. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2228. {
  2229. assertex(!idx);
  2230. puller.setInput(this, _sourceIdx, _in);
  2231. }
  2232. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2233. {
  2234. if (idx==0)
  2235. return puller.queryInput();
  2236. else
  2237. return NULL;
  2238. }
  2239. virtual unsigned __int64 queryTotalCycles() const
  2240. {
  2241. return totalCycles;
  2242. }
  2243. virtual const void * nextRow()
  2244. {
  2245. SimpleActivityTimer t(totalCycles, timeActivities);
  2246. if (disabled)
  2247. return puller.queryStream()->nextRow();
  2248. else
  2249. {
  2250. for (;;)
  2251. {
  2252. {
  2253. CriticalBlock b(crit);
  2254. if (eof && !buffer.ordinality())
  2255. return NULL; // eof
  2256. }
  2257. ready.wait();
  2258. const void *ret;
  2259. {
  2260. CriticalBlock b(crit);
  2261. ret = buffer.dequeue();
  2262. }
  2263. space.signal();
  2264. return ret;
  2265. }
  2266. }
  2267. }
  2268. virtual bool fireException(IException *e)
  2269. {
  2270. // called from puller thread on failure
  2271. ready.interrupt(LINK(e));
  2272. space.interrupt(e);
  2273. return true;
  2274. }
  2275. virtual void processRow(const void *row)
  2276. {
  2277. {
  2278. CriticalBlock b(crit);
  2279. buffer.enqueue(row);
  2280. }
  2281. ready.signal();
  2282. space.wait();
  2283. }
  2284. virtual void processGroup(const ConstPointerArray &rows)
  2285. {
  2286. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2287. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2288. // if group was larger than max(space)
  2289. {
  2290. CriticalBlock b(crit);
  2291. ForEachItemIn(idx, rows)
  2292. buffer.enqueue(rows.item(idx));
  2293. buffer.enqueue(NULL);
  2294. }
  2295. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2296. {
  2297. ready.signal();
  2298. space.wait();
  2299. }
  2300. }
  2301. virtual void processEOG()
  2302. {
  2303. // Used when output is not grouped - just ignore
  2304. }
  2305. virtual void processDone()
  2306. {
  2307. CriticalBlock b(crit);
  2308. eof = true;
  2309. ready.signal();
  2310. }
  2311. };
  2312. //=================================================================================
  2313. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2314. {
  2315. protected:
  2316. IFinalRoxieInput *input1;
  2317. IEngineRowStream *inputStream1;
  2318. Owned<IStrandJunction> junction1;
  2319. unsigned sourceIdx1 = 0;
  2320. Owned<CRoxieServerReadAheadInput> puller;
  2321. public:
  2322. CRoxieServerTwoInputActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2323. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2324. {
  2325. input1 = NULL;
  2326. inputStream1 = NULL;
  2327. }
  2328. ~CRoxieServerTwoInputActivity()
  2329. {
  2330. }
  2331. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2332. {
  2333. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2334. input1->start(parentExtractSize, parentExtract, paused);
  2335. startJunction(junction1);
  2336. }
  2337. virtual void stop()
  2338. {
  2339. inputStream1->stop();
  2340. CRoxieServerActivity::stop();
  2341. }
  2342. virtual unsigned __int64 queryLocalCycles() const
  2343. {
  2344. __int64 ret;
  2345. __int64 inputCycles = input->queryTotalCycles();
  2346. __int64 input1Cycles = input1->queryTotalCycles();
  2347. if (puller)
  2348. ret = activityStats.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2349. else
  2350. ret = activityStats.totalCycles - (inputCycles + input1Cycles);
  2351. if (ret < 0)
  2352. ret = 0;
  2353. return ret;
  2354. }
  2355. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2356. {
  2357. switch (idx)
  2358. {
  2359. case 0:
  2360. return input;
  2361. case 1:
  2362. return input1;
  2363. default:
  2364. return NULL;
  2365. }
  2366. }
  2367. virtual void reset()
  2368. {
  2369. CRoxieServerActivity::reset();
  2370. if (input1)
  2371. input1->reset();
  2372. resetJunction(junction1);
  2373. }
  2374. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2375. {
  2376. switch(idx)
  2377. {
  2378. case 0:
  2379. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2380. break;
  2381. case 1:
  2382. input1 = _in;
  2383. sourceIdx1 = _sourceIdx;
  2384. break;
  2385. default:
  2386. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2387. }
  2388. }
  2389. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2390. {
  2391. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2392. //Assumes input1 will be stranded if any.
  2393. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2394. }
  2395. };
  2396. //=================================================================================
  2397. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2398. {
  2399. protected:
  2400. unsigned numInputs;
  2401. unsigned numStreams;
  2402. IFinalRoxieInput **inputArray;
  2403. unsigned *sourceIdxArray;
  2404. IEngineRowStream **streamArray;
  2405. Owned<IStrandJunction> *junctionArray;
  2406. public:
  2407. CRoxieServerMultiInputBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2408. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2409. {
  2410. numStreams = numInputs;
  2411. inputArray = new IFinalRoxieInput*[numInputs];
  2412. sourceIdxArray = new unsigned[numInputs];
  2413. streamArray = new IEngineRowStream*[numStreams];
  2414. junctionArray = new Owned<IStrandJunction>[numStreams];
  2415. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2416. {
  2417. inputArray[i1] = NULL;
  2418. sourceIdxArray[i1] = 0;
  2419. }
  2420. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2421. streamArray[i2] = NULL;
  2422. }
  2423. ~CRoxieServerMultiInputBaseActivity()
  2424. {
  2425. delete [] inputArray;
  2426. delete [] sourceIdxArray;
  2427. delete [] streamArray;
  2428. delete [] junctionArray;
  2429. }
  2430. virtual unsigned __int64 queryLocalCycles() const
  2431. {
  2432. __int64 localCycles = activityStats.totalCycles;
  2433. for (unsigned i = 0; i < numInputs; i++)
  2434. localCycles -= inputArray[i]->queryTotalCycles();
  2435. if (localCycles < 0)
  2436. localCycles = 0;
  2437. return localCycles;
  2438. }
  2439. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2440. {
  2441. if (idx < numInputs)
  2442. return inputArray[idx];
  2443. else
  2444. return NULL;
  2445. }
  2446. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2447. {
  2448. return queryInput(idx);
  2449. }
  2450. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2451. {
  2452. if (whichInput < numInputs)
  2453. return streamArray[whichInput];
  2454. else
  2455. return NULL;
  2456. }
  2457. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2458. {
  2459. if (idx < numInputs)
  2460. return junctionArray[idx];
  2461. else
  2462. return NULL;
  2463. }
  2464. virtual void reset()
  2465. {
  2466. for (unsigned i = 0; i < numInputs; i++)
  2467. inputArray[i]->reset();
  2468. for (unsigned iS = 0; iS < numStreams; iS++)
  2469. {
  2470. resetJunction(junctionArray[iS]);
  2471. }
  2472. CRoxieServerActivity::reset();
  2473. }
  2474. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2475. {
  2476. assertex(idx < numInputs && idx < numStreams);
  2477. inputArray[idx] = _in;
  2478. sourceIdxArray[idx] = _sourceIdx;
  2479. }
  2480. virtual void connectInputStreams(bool consumerOrdered)
  2481. {
  2482. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2483. connectSingleInputStreams(consumerOrdered);
  2484. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  2485. }
  2486. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2487. {
  2488. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2489. }
  2490. protected:
  2491. void connectSingleInputStreams(bool consumerOrdered)
  2492. {
  2493. for (unsigned i = 0; i < numInputs; i++)
  2494. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2495. }
  2496. };
  2497. //=================================================================================
  2498. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2499. {
  2500. public:
  2501. CRoxieServerMultiInputActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2502. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2503. {
  2504. }
  2505. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2506. {
  2507. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2508. for (unsigned i = 0; i < numInputs; i++)
  2509. {
  2510. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2511. }
  2512. for (unsigned iS = 0; iS < numStreams; iS++)
  2513. {
  2514. startJunction(junctionArray[iS]);
  2515. }
  2516. }
  2517. virtual void stop()
  2518. {
  2519. for (unsigned i = 0; i < numStreams; i++)
  2520. {
  2521. streamArray[i]->stop();
  2522. }
  2523. CRoxieServerMultiInputBaseActivity::stop();
  2524. }
  2525. };
  2526. //=====================================================================================================
  2527. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2528. {
  2529. protected:
  2530. unsigned numOutputs;
  2531. bool executed;
  2532. bool *stopped;
  2533. CriticalSection ecrit;
  2534. Owned<IException> exception;
  2535. public:
  2536. CRoxieServerInternalSinkActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2537. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2538. {
  2539. executed = false;
  2540. stopped = new bool[numOutputs];
  2541. for (unsigned s = 0; s < numOutputs; s++)
  2542. stopped[s] = false;
  2543. }
  2544. ~CRoxieServerInternalSinkActivity()
  2545. {
  2546. delete [] stopped;
  2547. }
  2548. virtual void reset()
  2549. {
  2550. for (unsigned s = 0; s < numOutputs; s++)
  2551. stopped[s] = false;
  2552. executed = false;
  2553. exception.clear();
  2554. CRoxieServerActivity::reset();
  2555. }
  2556. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2557. {
  2558. return NULL;
  2559. }
  2560. virtual void stopSink(unsigned outputIdx)
  2561. {
  2562. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2563. {
  2564. stopped[outputIdx] = true;
  2565. for (unsigned s = 0; s < numOutputs; s++)
  2566. if (!stopped[s])
  2567. return;
  2568. stop(); // all outputs stopped - stop parent.
  2569. }
  2570. }
  2571. virtual const void *nextRow()
  2572. {
  2573. throwUnexpected(); // I am nobody's input
  2574. }
  2575. virtual void onExecute() = 0;
  2576. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2577. {
  2578. CriticalBlock b(ecrit);
  2579. if (exception)
  2580. throw exception.getLink();
  2581. if (!executed)
  2582. {
  2583. try
  2584. {
  2585. start(parentExtractSize, parentExtract, false);
  2586. {
  2587. ActivityTimer t(activityStats, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2588. onExecute();
  2589. }
  2590. stop();
  2591. executed = true;
  2592. }
  2593. catch (IException *E)
  2594. {
  2595. exception.set(E); // (or maybe makeWrappedException?)
  2596. abort();
  2597. throw;
  2598. }
  2599. catch (...)
  2600. {
  2601. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2602. abort();
  2603. throw;
  2604. }
  2605. }
  2606. }
  2607. };
  2608. //=================================================================================
  2609. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2610. {
  2611. protected:
  2612. Owned<IMessageResult> result;
  2613. Owned<IRoxieQueryPacket> packet;
  2614. Linked<IRoxieServerQueryPacket> continuation;
  2615. unsigned hash;
  2616. unsigned seq;
  2617. unsigned lastDebugSequence;
  2618. Owned<IRoxieQueryPacket> lastDebugResponse;
  2619. ILRUChain *prev;
  2620. ILRUChain *next;
  2621. bool delayed;
  2622. public:
  2623. IMPLEMENT_IINTERFACE;
  2624. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2625. {
  2626. hash = 0;
  2627. seq = 0;
  2628. prev = NULL;
  2629. next = NULL;
  2630. delayed = false;
  2631. lastDebugSequence = 0;
  2632. }
  2633. virtual IRoxieQueryPacket *queryPacket() const
  2634. {
  2635. return packet;
  2636. }
  2637. virtual bool isContinuation() const
  2638. {
  2639. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2640. }
  2641. virtual bool isDelayed() const
  2642. {
  2643. return delayed;
  2644. }
  2645. virtual bool isEnd() const
  2646. {
  2647. return false;
  2648. }
  2649. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2650. {
  2651. return false;
  2652. }
  2653. virtual bool hasResult() const
  2654. {
  2655. return result != NULL;
  2656. }
  2657. virtual bool hasContinuation() const
  2658. {
  2659. return continuation != NULL;
  2660. }
  2661. virtual void setDelayed(bool _delayed)
  2662. {
  2663. delayed = _delayed;
  2664. }
  2665. virtual void setPacket(IRoxieQueryPacket *_packet)
  2666. {
  2667. packet.setown(_packet);
  2668. }
  2669. virtual void setSequence(unsigned _seq)
  2670. {
  2671. assertex(!IsShared());
  2672. seq = _seq;
  2673. }
  2674. virtual unsigned getSequence() const
  2675. {
  2676. return seq;
  2677. }
  2678. IMessageResult *getResult()
  2679. {
  2680. return result.getLink();
  2681. }
  2682. IMessageResult *queryResult()
  2683. {
  2684. return result;
  2685. }
  2686. void setResult(IMessageResult *r)
  2687. {
  2688. result.setown(r);
  2689. }
  2690. IRoxieServerQueryPacket *queryContinuation()
  2691. {
  2692. return continuation;
  2693. }
  2694. void setContinuation(IRoxieServerQueryPacket *c)
  2695. {
  2696. continuation.setown(c);
  2697. }
  2698. virtual unsigned queryHash() const
  2699. {
  2700. return hash;
  2701. }
  2702. virtual void setHash(unsigned _hash)
  2703. {
  2704. hash = _hash;
  2705. }
  2706. virtual ILRUChain *queryPrev() const { return prev; }
  2707. virtual ILRUChain *queryNext() const { return next; }
  2708. virtual void setPrev(ILRUChain *p) { prev = p; }
  2709. virtual void setNext(ILRUChain *n) { next = n; }
  2710. virtual void unchain()
  2711. {
  2712. if (prev && next)
  2713. {
  2714. prev->setNext(next);
  2715. next->setPrev(prev);
  2716. }
  2717. next = NULL;
  2718. prev = NULL;
  2719. }
  2720. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2721. {
  2722. if (sequence == lastDebugSequence)
  2723. return lastDebugResponse.getLink();
  2724. else if (sequence > lastDebugSequence)
  2725. {
  2726. lastDebugResponse.clear();
  2727. return NULL;
  2728. }
  2729. else
  2730. throwUnexpected();
  2731. }
  2732. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2733. {
  2734. lastDebugSequence = sequence;
  2735. lastDebugResponse.set(response);
  2736. }
  2737. };
  2738. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2739. {
  2740. public:
  2741. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2742. {
  2743. }
  2744. virtual bool isEnd() const
  2745. {
  2746. return true;
  2747. }
  2748. };
  2749. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2750. {
  2751. unsigned __int64 rowLimit;
  2752. unsigned __int64 keyedLimit;
  2753. unsigned __int64 stopAfter;
  2754. public:
  2755. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2756. {
  2757. rowLimit = _rowLimit;
  2758. keyedLimit = _keyedLimit;
  2759. stopAfter = _stopAfter;
  2760. }
  2761. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2762. {
  2763. _rowLimit = rowLimit;
  2764. _keyedLimit = keyedLimit;
  2765. _stopAfter = stopAfter;
  2766. return true;
  2767. }
  2768. };
  2769. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2770. {
  2771. protected:
  2772. unsigned cacheTableSize;
  2773. unsigned cacheTableSpace;
  2774. IRoxieServerQueryPacket **cacheTable;
  2775. mutable ILRUChain *prev;
  2776. mutable ILRUChain *next;
  2777. mutable CriticalSection crit;
  2778. virtual ILRUChain *queryPrev() const { return prev; }
  2779. virtual ILRUChain *queryNext() const { return next; }
  2780. virtual void setPrev(ILRUChain *p) { prev = p; }
  2781. virtual void setNext(ILRUChain *n) { next = n; }
  2782. virtual void unchain()
  2783. {
  2784. prev->setNext(next);
  2785. next->setPrev(prev);
  2786. next = NULL;
  2787. prev = NULL;
  2788. }
  2789. void moveToHead(IRoxieServerQueryPacket *mru)
  2790. {
  2791. mru->unchain();
  2792. mru->setNext(next);
  2793. next->setPrev(mru);
  2794. mru->setPrev(this);
  2795. next = mru;
  2796. }
  2797. IRoxieServerQueryPacket *removeLRU()
  2798. {
  2799. if (next==this)
  2800. assertex(next != this);
  2801. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2802. goer->unchain(); // NOTE - this will modify the value of next
  2803. return goer;
  2804. }
  2805. void removeEntry(IRoxieServerQueryPacket *goer)
  2806. {
  2807. unsigned v = goer->queryHash() % cacheTableSize;
  2808. for (;;)
  2809. {
  2810. IRoxieServerQueryPacket *found = cacheTable[v];
  2811. assertex(found);
  2812. if (found == goer)
  2813. {
  2814. cacheTable[v] = NULL;
  2815. unsigned vn = v;
  2816. for (;;)
  2817. {
  2818. vn++;
  2819. if (vn==cacheTableSize) vn = 0;
  2820. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2821. if (!found2)
  2822. break;
  2823. unsigned vm = found2->queryHash() % cacheTableSize;
  2824. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2825. {
  2826. cacheTable[v] = found2;
  2827. v = vn;
  2828. cacheTable[v] = NULL;
  2829. }
  2830. }
  2831. cacheTableSpace++;
  2832. break;
  2833. }
  2834. v++;
  2835. if (v==cacheTableSize)
  2836. v = 0;
  2837. }
  2838. goer->Release();
  2839. }
  2840. public:
  2841. CRoxieServerSideCache(unsigned _cacheSize)
  2842. {
  2843. cacheTableSize = (_cacheSize*4)/3;
  2844. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2845. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2846. cacheTableSpace = _cacheSize;
  2847. prev = this;
  2848. next = this;
  2849. }
  2850. ~CRoxieServerSideCache()
  2851. {
  2852. for (unsigned i = 0; i < cacheTableSize; i++)
  2853. {
  2854. ::Release(cacheTable[i]);
  2855. }
  2856. delete [] cacheTable;
  2857. }
  2858. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2859. {
  2860. unsigned hash = p->hash();
  2861. unsigned et = hash % cacheTableSize;
  2862. if (traceServerSideCache)
  2863. {
  2864. StringBuffer s;
  2865. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2866. }
  2867. CriticalBlock b(crit);
  2868. for (;;)
  2869. {
  2870. IRoxieServerQueryPacket *found = cacheTable[et];
  2871. if (!found)
  2872. return NULL;
  2873. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2874. {
  2875. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2876. if (traceServerSideCache)
  2877. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2878. logctx.noteStatistic(StNumServerCacheHits, 1);
  2879. return NULL;
  2880. // 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....
  2881. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2882. //ret->setResult(found->getResult());
  2883. //return ret;
  2884. }
  2885. et++;
  2886. if (et == cacheTableSize)
  2887. et = 0;
  2888. }
  2889. }
  2890. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2891. {
  2892. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2893. {
  2894. unsigned hash = out->queryPacket()->hash();
  2895. out->setHash(hash);
  2896. unsigned et = hash % cacheTableSize;
  2897. if (traceServerSideCache)
  2898. {
  2899. StringBuffer s;
  2900. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2901. }
  2902. CriticalBlock b(crit);
  2903. for (;;)
  2904. {
  2905. IRoxieServerQueryPacket *found = cacheTable[et];
  2906. if (!found)
  2907. {
  2908. if (cacheTableSpace)
  2909. {
  2910. out->setResult(LINK(in));
  2911. cacheTable[et] = LINK(out);
  2912. cacheTableSpace--;
  2913. moveToHead(out);
  2914. break;
  2915. }
  2916. else
  2917. {
  2918. IRoxieServerQueryPacket *goer = removeLRU();
  2919. removeEntry(goer);
  2920. et = hash % cacheTableSize;
  2921. continue;
  2922. }
  2923. }
  2924. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2925. {
  2926. moveToHead(found);
  2927. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2928. // multiple copies of a agent query are in-flight at once.
  2929. }
  2930. et++;
  2931. if (et == cacheTableSize)
  2932. et = 0;
  2933. }
  2934. }
  2935. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2936. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2937. }
  2938. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2939. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2940. // more than make up for it
  2941. };
  2942. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2943. {
  2944. ConstPointerArray &data;
  2945. Linked<IMessageResult> result;
  2946. public:
  2947. IMPLEMENT_IINTERFACE;
  2948. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2949. : data(_data), result(_result)
  2950. {
  2951. }
  2952. virtual bool atEOF() const
  2953. {
  2954. return data.length()==0;
  2955. }
  2956. virtual bool isSerialized() const
  2957. {
  2958. return false;
  2959. }
  2960. virtual const void * getNext(int length)
  2961. {
  2962. if (!data.length())
  2963. return NULL;
  2964. const void *ret = data.item(0);
  2965. data.remove(0);
  2966. return ret;
  2967. }
  2968. };
  2969. // MORE - should possibly move more over to the lazy version used in indexread?
  2970. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2971. {
  2972. ConstPointerArray data;
  2973. public:
  2974. IMPLEMENT_IINTERFACE;
  2975. CRowArrayMessageResult()
  2976. {
  2977. }
  2978. ~CRowArrayMessageResult()
  2979. {
  2980. ReleaseRoxieRows(data);
  2981. }
  2982. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2983. {
  2984. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2985. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2986. }
  2987. virtual const void *getMessageHeader(unsigned &length) const
  2988. {
  2989. throwUnexpected(); // should never get called - I don't have a header available
  2990. }
  2991. virtual const void *getMessageMetadata(unsigned &length) const
  2992. {
  2993. length = 0;
  2994. return NULL;
  2995. }
  2996. virtual void discard() const
  2997. {
  2998. throwUnexpected();
  2999. }
  3000. void append(const void *row)
  3001. {
  3002. data.append(row);
  3003. }
  3004. };
  3005. void throwRemoteException(IMessageUnpackCursor *extra)
  3006. {
  3007. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3008. if (rowlen)
  3009. {
  3010. char *xml = (char *) extra->getNext(*rowlen);
  3011. ReleaseRoxieRow(rowlen);
  3012. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  3013. ReleaseRoxieRow(xml);
  3014. unsigned code = p->getPropInt("Code", 0);
  3015. const char *msg = p->queryProp("Message");
  3016. if (!msg)
  3017. msg = xml;
  3018. throw MakeStringException(code, "%s", msg);
  3019. }
  3020. throwUnexpected();
  3021. }
  3022. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  3023. {
  3024. friend class CRemoteResultMerger;
  3025. class CRemoteResultMerger
  3026. {
  3027. class HeapEntry : public CInterface
  3028. {
  3029. private:
  3030. CRemoteResultAdaptor &adaptor;
  3031. IMessageUnpackCursor *cursor;
  3032. public:
  3033. const void *current;
  3034. bool isLast;
  3035. bool lastIsComplete;
  3036. IRoxieServerQueryPacket *packet;
  3037. unsigned seq;
  3038. public:
  3039. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  3040. {
  3041. cursor = _cursor;
  3042. lastIsComplete = _lastIsComplete;
  3043. return next();
  3044. }
  3045. public:
  3046. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  3047. {
  3048. cursor = NULL;
  3049. current = NULL;
  3050. isLast = false;
  3051. lastIsComplete = true;
  3052. }
  3053. ~HeapEntry()
  3054. {
  3055. ::Release(packet);
  3056. ::Release(cursor);
  3057. ReleaseRoxieRow(current);
  3058. }
  3059. bool isCompleteMatch() const
  3060. {
  3061. if (!isLast || lastIsComplete)
  3062. return true;
  3063. else
  3064. return false;
  3065. }
  3066. const void *next()
  3067. {
  3068. if (cursor)
  3069. {
  3070. ReleaseClearRoxieRow(current);
  3071. current = adaptor.getRow(cursor);
  3072. isLast = cursor->atEOF();
  3073. if (!current)
  3074. {
  3075. cursor->Release();
  3076. cursor = NULL;
  3077. }
  3078. }
  3079. return current;
  3080. }
  3081. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  3082. {
  3083. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  3084. unsigned skipped = 0;
  3085. for (;;)
  3086. {
  3087. int c = compare->docompare(current, seek, numFields);
  3088. //If larger than the seek values, then we may be allowed to return an inexact match,
  3089. //if equal then it is required to be an exact match,
  3090. if (c > 0)
  3091. {
  3092. if (!requireExactMatch || isCompleteMatch())
  3093. break;
  3094. }
  3095. else if ((c == 0) && isCompleteMatch())
  3096. break;
  3097. skipped++;
  3098. if (!next())
  3099. break;
  3100. }
  3101. return skipped;
  3102. }
  3103. };
  3104. CRemoteResultAdaptor &adaptor;
  3105. CIArrayOf<HeapEntry> heapEntries;
  3106. UnsignedArray heap;
  3107. IRowManager *rowManager;
  3108. unsigned numPending;
  3109. unsigned numFields;
  3110. bool endSeen;
  3111. bool remakePending;
  3112. IRangeCompare *compare;
  3113. bool deferredContinuation;
  3114. inline int doCompare(unsigned l, unsigned r)
  3115. {
  3116. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  3117. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  3118. return ret;
  3119. }
  3120. void makeHeap()
  3121. {
  3122. /* Permute blocks to establish the heap property
  3123. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  3124. The children of p must both be greater than or equal to p
  3125. The parent of a child c is given by p = (c-1)/2
  3126. */
  3127. unsigned i;
  3128. unsigned n = heap.length();
  3129. unsigned *s = heap.getArray();
  3130. for (i=1; i<n; i++)
  3131. {
  3132. unsigned r = s[i];
  3133. int c = i; /* child */
  3134. while (c > 0)
  3135. {
  3136. int p = (c-1)/2; /* parent */
  3137. if ( doCompare( s[c], s[p] ) >= 0 )
  3138. break;
  3139. s[c] = s[p];
  3140. s[p] = r;
  3141. c = p;
  3142. }
  3143. }
  3144. remakePending = false;
  3145. }
  3146. void remakeHeap()
  3147. {
  3148. /* The row associated with block[0] will have changed
  3149. This code restores the heap property
  3150. */
  3151. unsigned p = 0; /* parent */
  3152. unsigned n = heap.length();
  3153. unsigned *s = heap.getArray();
  3154. while (1)
  3155. {
  3156. unsigned c = p*2 + 1; /* child */
  3157. if ( c >= n )
  3158. break;
  3159. /* Select smaller child */
  3160. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3161. /* If child is greater or equal than parent then we are done */
  3162. if ( doCompare( s[c], s[p] ) >= 0 )
  3163. break;
  3164. /* Swap parent and child */
  3165. unsigned r = s[c];
  3166. s[c] = s[p];
  3167. s[p] = r;
  3168. /* child becomes parent */
  3169. p = c;
  3170. }
  3171. remakePending = false;
  3172. }
  3173. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3174. {
  3175. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3176. IMessageResult *result = p->queryResult();
  3177. assertex(result);
  3178. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3179. {
  3180. heapEntries.append(h);
  3181. heap.append(heap.ordinality());
  3182. }
  3183. else
  3184. h.Release();
  3185. }
  3186. void removeHeap(unsigned idx)
  3187. {
  3188. heapEntries.remove(idx);
  3189. ForEachItemIn(i, heap)
  3190. {
  3191. unsigned v = heap.item(i);
  3192. assertex(v != idx);
  3193. if (v > idx)
  3194. heap.replace(v-1, i);
  3195. }
  3196. }
  3197. bool isCompleteMatchFlag(IMessageResult *result)
  3198. {
  3199. unsigned metaLen;
  3200. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3201. if (metaLen)
  3202. {
  3203. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3204. if (continuationLen >= sizeof(bool))
  3205. {
  3206. metaInfo += sizeof(unsigned short);
  3207. return *(bool *) metaInfo;
  3208. }
  3209. }
  3210. return true; // if no continuation info, last row was complete.
  3211. }
  3212. public:
  3213. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3214. {
  3215. init(NULL, NULL);
  3216. }
  3217. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3218. {
  3219. if (meta)
  3220. {
  3221. numFields = meta->getNumFields();
  3222. compare = meta->queryCompare();
  3223. }
  3224. else
  3225. {
  3226. numFields = 0;
  3227. compare = NULL;
  3228. }
  3229. rowManager = _rowManager;
  3230. numPending = 0;
  3231. endSeen = false;
  3232. remakePending = false;
  3233. deferredContinuation = false;
  3234. }
  3235. void reset()
  3236. {
  3237. heapEntries.kill();
  3238. heap.kill();
  3239. numPending = 0;
  3240. endSeen = false;
  3241. remakePending = false;
  3242. deferredContinuation = false;
  3243. }
  3244. inline bool noteEndSeen()
  3245. {
  3246. bool hadSeen = endSeen;
  3247. if (!endSeen)
  3248. makeHeap();
  3249. endSeen = true;
  3250. return !hadSeen;
  3251. }
  3252. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3253. {
  3254. if (!p->isContinuation())
  3255. append(p, seq);
  3256. else
  3257. {
  3258. ForEachItemIn(idx, heapEntries)
  3259. {
  3260. HeapEntry &h = heapEntries.item(idx);
  3261. if (h.packet == p)
  3262. {
  3263. IMessageResult *result = p->queryResult();
  3264. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3265. {
  3266. heap.zap(idx);
  3267. removeHeap(idx);
  3268. }
  3269. numPending--;
  3270. if (!numPending)
  3271. makeHeap();
  3272. return;
  3273. }
  3274. }
  3275. }
  3276. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3277. return;
  3278. }
  3279. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3280. {
  3281. HeapEntry &entry = heapEntries.item(idx);
  3282. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3283. if (!entry.current)
  3284. {
  3285. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3286. if (continuation)
  3287. {
  3288. continuation->Link();
  3289. entry.packet->Release();
  3290. entry.packet = continuation;
  3291. if (continuation->hasResult())
  3292. {
  3293. IMessageResult *result = continuation->queryResult();
  3294. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3295. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3296. }
  3297. else
  3298. {
  3299. if (continuation->isDelayed())
  3300. {
  3301. continuation->setDelayed(false);
  3302. MemoryBuffer serializedSkip;
  3303. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3304. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3305. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3306. adaptor.sentsome.signal();
  3307. }
  3308. numPending++;
  3309. }
  3310. }
  3311. else
  3312. {
  3313. heap.zap(idx);
  3314. removeHeap(idx);
  3315. idx--;
  3316. }
  3317. }
  3318. return skipped;
  3319. }
  3320. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3321. {
  3322. // We discard all rows < seekval from all entries in heap
  3323. // If this results in additional agent requests, we return NULL so that we can wait for them
  3324. // If not, we rebuild the heap (if any were skipped) and return the first row
  3325. deferredContinuation = false;
  3326. if (heap.length())
  3327. {
  3328. unsigned skipped = 0;
  3329. unsigned idx = 0;
  3330. while(heapEntries.isItem(idx))
  3331. {
  3332. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3333. idx++;
  3334. }
  3335. if (numPending)
  3336. return NULL; // can't answer yet, need more results from agents
  3337. else
  3338. {
  3339. if (skipped)
  3340. makeHeap();
  3341. return next(wasCompleteMatch, stepExtra);
  3342. }
  3343. }
  3344. else
  3345. return NULL;
  3346. }
  3347. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3348. {
  3349. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3350. if (continuation)
  3351. {
  3352. if (continuation->isDelayed() && canDefer)
  3353. {
  3354. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3355. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3356. deferredContinuation = true;
  3357. }
  3358. else
  3359. {
  3360. deferredContinuation = false;
  3361. continuation->Link();
  3362. topEntry.packet->Release();
  3363. topEntry.packet = continuation;
  3364. if (continuation->hasResult())
  3365. {
  3366. IMessageResult *result = continuation->queryResult();
  3367. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3368. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3369. }
  3370. else
  3371. {
  3372. if (continuation->isDelayed()) // has the continuation been requested yet?
  3373. {
  3374. continuation->Link();
  3375. topEntry.packet->Release();
  3376. topEntry.packet = continuation;
  3377. continuation->setDelayed(false);
  3378. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3379. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3380. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3381. adaptor.sentsome.signal();
  3382. }
  3383. numPending++; // we are waiting for one that is already in flight
  3384. }
  3385. }
  3386. return true; // next not known yet
  3387. }
  3388. else
  3389. return false;
  3390. }
  3391. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3392. {
  3393. OwnedConstRoxieRow ret;
  3394. if (heap.length())
  3395. {
  3396. if (deferredContinuation)
  3397. {
  3398. unsigned top = heap.item(0);
  3399. HeapEntry &topEntry = heapEntries.item(top);
  3400. doContinuation(topEntry, false);
  3401. return NULL;
  3402. }
  3403. if (remakePending)
  3404. remakeHeap();
  3405. unsigned top = heap.item(0);
  3406. HeapEntry &topEntry = heapEntries.item(top);
  3407. ret.set(topEntry.current);
  3408. wasCompleteMatch = topEntry.isCompleteMatch();
  3409. const void *next = topEntry.next();
  3410. if (!next)
  3411. {
  3412. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3413. {
  3414. unsigned last = heap.popGet();
  3415. if (heap.length())
  3416. heap.replace(last, 0);
  3417. removeHeap(top);
  3418. }
  3419. }
  3420. remakePending = true;
  3421. }
  3422. return ret.getClear();
  3423. }
  3424. bool ready()
  3425. {
  3426. return endSeen && numPending == 0;
  3427. }
  3428. };
  3429. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3430. {
  3431. if (serverSideCache && !debugContext)
  3432. {
  3433. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3434. if (ret)
  3435. {
  3436. p->Release();
  3437. cached = true;
  3438. return ret;
  3439. }
  3440. }
  3441. cached = false;
  3442. return new CRoxieServerQueryPacket(p);
  3443. }
  3444. #ifdef _DEBUG
  3445. void dumpPending()
  3446. {
  3447. CriticalBlock b(pendingCrit);
  3448. ForEachItemIn(idx, pending)
  3449. {
  3450. IRoxieServerQueryPacket &p = pending.item(idx);
  3451. StringBuffer s;
  3452. unsigned __int64 dummy;
  3453. if (p.isEnd())
  3454. s.append("END");
  3455. else if (p.isLimit(dummy, dummy, dummy))
  3456. s.append("LIMIT");
  3457. else
  3458. {
  3459. IRoxieQueryPacket *i = p.queryPacket();
  3460. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3461. if (i)
  3462. {
  3463. RoxiePacketHeader &header = i->queryHeader();
  3464. header.toString(s);
  3465. }
  3466. }
  3467. DBGLOG("Pending %d %s", idx, s.str());
  3468. }
  3469. }
  3470. #endif
  3471. void abortPending()
  3472. {
  3473. CriticalBlock b(pendingCrit);
  3474. ForEachItemIn(idx, pending)
  3475. {
  3476. IRoxieServerQueryPacket &p = pending.item(idx);
  3477. if (!p.hasResult())
  3478. {
  3479. IRoxieQueryPacket *i = p.queryPacket();
  3480. if (i)
  3481. {
  3482. RoxiePacketHeader &header = i->queryHeader();
  3483. ROQ->sendAbort(header, activity.queryLogCtx());
  3484. }
  3485. }
  3486. }
  3487. pending.kill();
  3488. }
  3489. void checkDelayed()
  3490. {
  3491. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3492. {
  3493. bool allDelayed = true;
  3494. CriticalBlock b(pendingCrit);
  3495. unsigned sendIdx = (unsigned) -1;
  3496. ForEachItemIn(idx, pending)
  3497. {
  3498. IRoxieServerQueryPacket &p = pending.item(idx);
  3499. if (p.queryPacket())
  3500. {
  3501. if (p.isDelayed())
  3502. {
  3503. if (sendIdx == (unsigned) -1)
  3504. sendIdx = idx;
  3505. }
  3506. else if (!p.hasResult())
  3507. {
  3508. allDelayed = false;
  3509. break;
  3510. }
  3511. }
  3512. }
  3513. if (allDelayed && sendIdx != (unsigned) -1)
  3514. {
  3515. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3516. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3517. pending.item(sendIdx).setDelayed(false);
  3518. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3519. sentsome.signal();
  3520. }
  3521. }
  3522. else if (deferredStart)
  3523. {
  3524. CriticalBlock b(pendingCrit);
  3525. ForEachItemIn(idx, pending)
  3526. {
  3527. IRoxieServerQueryPacket &p = pending.item(idx);
  3528. if (p.isDelayed())
  3529. {
  3530. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3531. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3532. p.setDelayed(false);
  3533. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3534. sentsome.signal();
  3535. }
  3536. }
  3537. deferredStart = false;
  3538. }
  3539. }
  3540. void retryPending()
  3541. {
  3542. CriticalBlock b(pendingCrit);
  3543. checkDelayed();
  3544. ForEachItemIn(idx, pending)
  3545. {
  3546. IRoxieServerQueryPacket &p = pending.item(idx);
  3547. if (!p.hasResult() && !p.isDelayed())
  3548. {
  3549. IRoxieQueryPacket *i = p.queryPacket();
  3550. if (i)
  3551. {
  3552. if (!i->queryHeader().retry())
  3553. {
  3554. StringBuffer s;
  3555. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from agent(s) for %s in activity %d", i->queryHeader().toString(s).str(), activity.queryId());
  3556. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3557. throw E;
  3558. }
  3559. if (!localAgent)
  3560. {
  3561. ROQ->sendPacket(i, activity.queryLogCtx());
  3562. retriesSent++;
  3563. }
  3564. }
  3565. }
  3566. }
  3567. }
  3568. class ChannelBuffer
  3569. {
  3570. protected:
  3571. unsigned bufferLeft;
  3572. MemoryBuffer buffer;
  3573. char *nextBuf;
  3574. unsigned overflowSequence;
  3575. unsigned channel; // == bonded channel
  3576. bool needsFlush;
  3577. InterruptableSemaphore flowController;
  3578. const CRemoteResultAdaptor &owner;
  3579. CriticalSection crit;
  3580. public:
  3581. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : channel(_channel), flowController(perChannelFlowLimit), owner(_owner)
  3582. {
  3583. overflowSequence = 0;
  3584. needsFlush = false;
  3585. bufferLeft = 0;
  3586. nextBuf = NULL;
  3587. }
  3588. void init(unsigned minSize)
  3589. {
  3590. assertex(!buffer.length());
  3591. if (minSize < MIN_PAYLOAD_SIZE)
  3592. minSize = MIN_PAYLOAD_SIZE;
  3593. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3594. unsigned bufferSize = headerSize+minSize;
  3595. if (bufferSize < mtu_size)
  3596. bufferSize = mtu_size;
  3597. buffer.reserveTruncate(bufferSize);
  3598. bufferLeft = bufferSize - headerSize;
  3599. assertex(buffer.toByteArray());
  3600. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3601. needsFlush = false;
  3602. }
  3603. inline IRoxieQueryPacket *flush()
  3604. {
  3605. CriticalBlock cb(crit);
  3606. Owned<IRoxieQueryPacket> ret;
  3607. if (needsFlush)
  3608. {
  3609. buffer.setLength(nextBuf - buffer.toByteArray());
  3610. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3611. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3612. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3613. byte * tgt = (byte*)(h+1);
  3614. owner.copyHeader(tgt, channel);
  3615. ret.setown(createRoxiePacket(buffer));
  3616. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3617. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3618. else
  3619. overflowSequence++;
  3620. needsFlush = false;
  3621. bufferLeft = 0;
  3622. if (owner.flowControlled)
  3623. {
  3624. CriticalUnblock cub(crit);
  3625. while (!flowController.wait(1000))
  3626. {
  3627. StringBuffer s;
  3628. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3629. }
  3630. }
  3631. }
  3632. return ret.getClear();
  3633. }
  3634. inline void signal()
  3635. {
  3636. if (owner.flowControlled)
  3637. flowController.signal();
  3638. }
  3639. inline void interrupt(IException *e)
  3640. {
  3641. flowController.interrupt(e);
  3642. }
  3643. inline void *getBuffer(unsigned size)
  3644. {
  3645. CriticalBlock cb(crit);
  3646. if (bufferLeft >= size)
  3647. {
  3648. needsFlush = true;
  3649. void * ret = nextBuf;
  3650. nextBuf += size;
  3651. bufferLeft -= size;
  3652. return ret;
  3653. }
  3654. else if (!needsFlush)
  3655. {
  3656. init(size);
  3657. return getBuffer(size);
  3658. }
  3659. else if (owner.mergeOrder)
  3660. {
  3661. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3662. }
  3663. else
  3664. return NULL; // will force it to flush and start a new packet
  3665. }
  3666. };
  3667. private:
  3668. friend class CRemoteResultMerger;
  3669. bool allread;
  3670. bool contextCached;
  3671. bool preserveOrder;
  3672. bool eogSent = false;
  3673. InterruptableSemaphore sentsome;
  3674. Owned <IMessageCollator> mc;
  3675. Owned<IMessageUnpackCursor> mu;
  3676. Owned<IMessageResult> mr;
  3677. ChannelBuffer **buffers;
  3678. IHThorArg &helper;
  3679. unsigned __int64 stopAfter;
  3680. unsigned resendSequence;
  3681. IHThorArg *colocalArg;
  3682. IArrayOf<IRoxieServerQueryPacket> pending;
  3683. CriticalSection pendingCrit;
  3684. IRoxieServerSideCache *serverSideCache;
  3685. unsigned sentSequence;
  3686. Owned<IOutputRowDeserializer> deserializer;
  3687. Owned<IEngineRowAllocator> rowAllocator;
  3688. CRemoteResultMerger merger;
  3689. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3690. MemoryBuffer tempRowBuffer;
  3691. Owned<ISerialStream> bufferStream;
  3692. CThorStreamDeserializerSource rowSource;
  3693. protected:
  3694. IRowManager *rowManager;
  3695. unsigned __int64 rowLimit;
  3696. unsigned __int64 keyedLimit;
  3697. IRoxieServerErrorHandler *errorHandler;
  3698. CachedOutputMetaData meta;
  3699. public:
  3700. ISteppingMeta *mergeOrder;
  3701. IRoxieAgentContext *ctx;
  3702. IDebuggableContext *debugContext;
  3703. IRoxieServerActivity &activity;
  3704. unsigned parentExtractSize;
  3705. const byte * parentExtract;
  3706. bool flowControlled;
  3707. bool deferredStart;
  3708. MemoryBuffer logInfo;
  3709. MemoryBuffer cachedContext;
  3710. const RemoteActivityId &remoteId;
  3711. ruid_t ruid;
  3712. mutable CriticalSection buffersCrit;
  3713. unsigned processed;
  3714. cycle_t totalCycles;
  3715. bool timeActivities;
  3716. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3717. const void *getRow(IMessageUnpackCursor *mu)
  3718. {
  3719. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3720. return mu->getNext(meta.getFixedSize());
  3721. else
  3722. {
  3723. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3724. if (rowlen)
  3725. {
  3726. RecordLengthType len = *rowlen;
  3727. ReleaseRoxieRow(rowlen);
  3728. const void *agentRec = mu->getNext(len);
  3729. if (deserializer && mu->isSerialized())
  3730. {
  3731. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3732. tempRowBuffer.setBuffer(len, const_cast<void *>(agentRec), false);
  3733. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3734. ReleaseRoxieRow(agentRec);
  3735. return rowBuilder.finalizeRowClear(outsize);
  3736. }
  3737. else
  3738. return agentRec;
  3739. }
  3740. else
  3741. return NULL;
  3742. }
  3743. }
  3744. private:
  3745. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3746. {
  3747. CriticalBlock cb(buffersCrit);
  3748. ChannelBuffer *b = buffers[channel];
  3749. if (!b && force)
  3750. {
  3751. if (!contextCached)
  3752. {
  3753. logInfo.clear();
  3754. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3755. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3756. const QueryOptions &options = ctx->queryOptions();
  3757. if (activity.queryLogCtx().isIntercepted())
  3758. loggingFlags |= LOGGING_INTERCEPTED;
  3759. if (options.timeActivities)
  3760. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3761. if (activity.queryLogCtx().isBlind())
  3762. loggingFlags |= LOGGING_BLIND;
  3763. if (options.checkingHeap)
  3764. loggingFlags |= LOGGING_CHECKINGHEAP;
  3765. if (ctx->queryWorkUnit())
  3766. loggingFlags |= LOGGING_WUID;
  3767. if (debugContext)
  3768. {
  3769. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3770. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3771. MemoryBuffer bpInfo;
  3772. debugContext->serialize(bpInfo);
  3773. bpInfo.append((__uint64)(memsize_t) &activity);
  3774. logInfo.append((unsigned short) bpInfo.length());
  3775. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3776. }
  3777. else
  3778. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3779. StringBuffer logPrefix;
  3780. activity.queryLogCtx().getLogPrefix(logPrefix);
  3781. logInfo.append(logPrefix);
  3782. activity.serializeCreateStartContext(cachedContext.clear());
  3783. activity.serializeExtra(cachedContext);
  3784. if (activity.queryVarFileInfo())
  3785. {
  3786. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3787. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3788. }
  3789. contextCached = true;
  3790. }
  3791. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3792. }
  3793. return b;
  3794. }
  3795. void processRow(const void *got)
  3796. {
  3797. processed++;
  3798. if (processed > rowLimit)
  3799. {
  3800. ReleaseRoxieRow(got);
  3801. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3802. throwUnexpected();
  3803. }
  3804. else if (processed > keyedLimit)
  3805. {
  3806. ReleaseRoxieRow(got);
  3807. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3808. throwUnexpected();
  3809. }
  3810. }
  3811. public:
  3812. IMPLEMENT_IINTERFACE;
  3813. CRemoteResultAdaptor(IRoxieAgentContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3814. : preserveOrder(_preserveOrder), helper(_helper), merger(*this), meta(_meta), activity(_activity), flowControlled(_flowControlled), remoteId(_remoteId)
  3815. {
  3816. ctx = _ctx;
  3817. errorHandler = _errorHandler;
  3818. colocalArg = NULL;
  3819. allread = false;
  3820. ruid = 0;
  3821. rowLimit = (unsigned __int64) -1;
  3822. keyedLimit = (unsigned __int64) -1;
  3823. contextCached = false;
  3824. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3825. buffers = new ChannelBuffer*[numChannels+1];
  3826. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3827. parentExtractSize = 0;
  3828. rowManager = NULL;
  3829. parentExtract = NULL;
  3830. debugContext = NULL;
  3831. mergeOrder = NULL;
  3832. deferredStart = false;
  3833. processed = 0;
  3834. sentSequence = 0;
  3835. resendSequence = 0;
  3836. totalCycles = 0;
  3837. serverSideCache = activity.queryServerSideCache();
  3838. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3839. rowSource.setStream(bufferStream);
  3840. timeActivities = defaultTimeActivities;
  3841. }
  3842. ~CRemoteResultAdaptor()
  3843. {
  3844. if (mc)
  3845. {
  3846. ROQ->queryReceiveManager()->detachCollator(mc);
  3847. mc.clear();
  3848. }
  3849. for (unsigned channel = 0; channel <= numChannels; channel++)
  3850. {
  3851. delete(buffers[channel]);
  3852. }
  3853. delete [] buffers;
  3854. }
  3855. void setMeta(IOutputMetaData *newmeta)
  3856. {
  3857. meta.set(newmeta);
  3858. }
  3859. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3860. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3861. virtual IRoxieServerActivity *queryActivity()
  3862. {
  3863. return &activity;
  3864. }
  3865. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3866. {
  3867. return NULL;
  3868. }
  3869. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3870. {
  3871. mergeOrder = _mergeOrder;
  3872. deferredStart = true;
  3873. }
  3874. void send(IRoxieQueryPacket *p)
  3875. {
  3876. if (p)
  3877. {
  3878. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3879. assertex(p->queryHeader().uid==ruid);
  3880. // MORE: Maybe we should base the fastlane flag on some other
  3881. // criteria !! (i.e A Roxie server prediction based on the
  3882. // activity type/activity behaviour/expected reply size .. etc).
  3883. //
  3884. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3885. // But this could still cause too many reply packets on the fatlane
  3886. // (higher priority output Q), which may cause the activities on the
  3887. // low priority output Q to not get service on time.
  3888. if ((colocalArg == 0) && // not a child query activity??
  3889. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3890. (p->queryHeader().overflowSequence == 0) &&
  3891. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3892. p->queryHeader().retries |= ROXIE_FASTLANE;
  3893. if (p->queryHeader().channel)
  3894. {
  3895. bool cached = false;
  3896. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3897. if (deferredStart)
  3898. rsqp->setDelayed(true);
  3899. rsqp->setSequence(sentSequence++);
  3900. {
  3901. CriticalBlock b(pendingCrit);
  3902. pending.append(*rsqp);
  3903. }
  3904. if (!deferredStart)
  3905. {
  3906. if (!cached)
  3907. ROQ->sendPacket(p, activity.queryLogCtx());
  3908. sentsome.signal();
  3909. }
  3910. }
  3911. else
  3912. {
  3913. // 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
  3914. // Need to add first, then send
  3915. unsigned i;
  3916. bool allCached = true;
  3917. for (i = 1; i <= numChannels; i++)
  3918. {
  3919. IRoxieQueryPacket *q = p->clonePacket(i);
  3920. bool thisChannelCached;
  3921. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3922. if (!thisChannelCached)
  3923. allCached = false;
  3924. rsqp->setSequence(sentSequence++);
  3925. if (deferredStart)
  3926. {
  3927. rsqp->setDelayed(true);
  3928. }
  3929. {
  3930. CriticalBlock b(pendingCrit);
  3931. pending.append(*rsqp);
  3932. }
  3933. if (!deferredStart)
  3934. sentsome.signal();
  3935. }
  3936. if (!allCached && !deferredStart)
  3937. ROQ->sendPacket(p, activity.queryLogCtx());
  3938. buffers[0]->signal(); // since replies won't come back on that channel...
  3939. p->Release();
  3940. }
  3941. }
  3942. }
  3943. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3944. {
  3945. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3946. size += sizeof(PartNoType);
  3947. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3948. char *buffer = (char *) b->getBuffer(size);
  3949. if (!buffer)
  3950. {
  3951. send(b->flush());
  3952. buffer = (char *) b->getBuffer(size);
  3953. }
  3954. PartNoType sp;
  3955. sp.partNo = partNo;
  3956. sp.fileNo = fileNo;
  3957. memcpy(buffer, &sp, sizeof(sp));
  3958. buffer += sizeof(sp);
  3959. return buffer;
  3960. }
  3961. void injectResult(IMessageResult *result)
  3962. {
  3963. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3964. f->setSequence(sentSequence++);
  3965. f->setResult(result);
  3966. CriticalBlock b(pendingCrit);
  3967. pending.append(*f);
  3968. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3969. }
  3970. void flush()
  3971. {
  3972. for (unsigned channel = 0; channel <= numChannels; channel++)
  3973. {
  3974. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3975. if (b)
  3976. send(b->flush());
  3977. }
  3978. }
  3979. void interruptBuffers(IException *e)
  3980. {
  3981. for (unsigned channel = 0; channel <= numChannels; channel++)
  3982. {
  3983. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3984. if (b)
  3985. b->interrupt(LINK(e));
  3986. }
  3987. }
  3988. void senddone()
  3989. {
  3990. CriticalBlock b(pendingCrit);
  3991. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3992. sentsome.signal();
  3993. }
  3994. bool fireException(IException *e)
  3995. {
  3996. {
  3997. CriticalBlock b(pendingCrit);
  3998. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3999. }
  4000. interruptBuffers(e);
  4001. if (mc)
  4002. mc->interrupt(LINK(e));
  4003. sentsome.interrupt(e);
  4004. return true;
  4005. }
  4006. virtual void onCreate(IHThorArg *_colocalArg)
  4007. {
  4008. debugContext = ctx->queryDebugContext();
  4009. colocalArg = _colocalArg;
  4010. if (meta.needsSerializeDisk())
  4011. {
  4012. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  4013. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  4014. }
  4015. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  4016. deferredStart = true;
  4017. timeActivities = ctx->queryOptions().timeActivities;
  4018. }
  4019. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4020. {
  4021. #ifdef TRACE_STARTSTOP
  4022. if (traceStartStop)
  4023. activity.queryLogCtx().CTXLOG("RRAonstart");
  4024. #endif
  4025. sentsome.reinit();
  4026. ruid = getNextRuid();
  4027. rowManager = &ctx->queryRowManager();
  4028. if (mergeOrder)
  4029. merger.init(mergeOrder, rowManager);
  4030. if (mc)
  4031. {
  4032. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  4033. }
  4034. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  4035. allread = false;
  4036. mu.clear();
  4037. contextCached = false;
  4038. processed = 0;
  4039. resendSequence = 0;
  4040. sentSequence = 0;
  4041. for (unsigned channel = 0; channel <= numChannels; channel++)
  4042. {
  4043. delete(buffers[channel]);
  4044. buffers[channel] = NULL;
  4045. }
  4046. flush();
  4047. parentExtractSize = _parentExtractSize;
  4048. parentExtract = _parentExtract;
  4049. }
  4050. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4051. {
  4052. #ifdef TRACE_STARTSTOP
  4053. if (traceStartStop)
  4054. activity.queryLogCtx().CTXLOG("RRAstart");
  4055. #endif
  4056. activity.start(parentExtractSize, parentExtract, paused);
  4057. }
  4058. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  4059. {
  4060. if (ctx->queryProbeManager())
  4061. {
  4062. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  4063. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  4064. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  4065. }
  4066. {
  4067. CriticalBlock b(pendingCrit);
  4068. if (pending.length())
  4069. {
  4070. #ifdef _DEBUG
  4071. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  4072. #endif
  4073. assertex(pending.length()==0);
  4074. }
  4075. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  4076. }
  4077. sentsome.signal();
  4078. rowLimit = _rowLimit;
  4079. keyedLimit = _keyedLimit;
  4080. stopAfter = _stopAfter;
  4081. }
  4082. virtual void stop()
  4083. {
  4084. #ifdef TRACE_STARTSTOP
  4085. if (traceStartStop)
  4086. activity.queryLogCtx().CTXLOG("RRAstop");
  4087. #endif
  4088. onStop();
  4089. activity.stop();
  4090. }
  4091. void onStop()
  4092. {
  4093. #ifdef TRACE_STARTSTOP
  4094. if (traceStartStop)
  4095. activity.queryLogCtx().CTXLOG("RRAonstop");
  4096. #endif
  4097. abortPending();
  4098. interruptBuffers(NULL);
  4099. sentsome.interrupt();
  4100. if (mc) // May not be set if start() chain threw exception
  4101. mc->interrupt();
  4102. }
  4103. virtual void reset()
  4104. {
  4105. #ifdef TRACE_STARTSTOP
  4106. if (traceStartStop)
  4107. activity.queryLogCtx().CTXLOG("RRAreset");
  4108. #endif
  4109. activity.reset();
  4110. onReset();
  4111. }
  4112. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  4113. {
  4114. // Make sure parent activity calls up the tree
  4115. PointerArrayOf<IEngineRowStream> instreams;
  4116. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  4117. assertex (junction == NULL);
  4118. // I return a single strand (we could change that sometime I guess...)
  4119. streams.append(this);
  4120. return NULL;
  4121. }
  4122. virtual void resetEOF()
  4123. {
  4124. throwUnexpected();
  4125. }
  4126. virtual void onReset()
  4127. {
  4128. #ifdef TRACE_STARTSTOP
  4129. if (traceStartStop)
  4130. activity.queryLogCtx().CTXLOG("RRAonreset");
  4131. #endif
  4132. if (mc)
  4133. ROQ->queryReceiveManager()->detachCollator(mc);
  4134. merger.reset();
  4135. pending.kill();
  4136. if (mc && ctx)
  4137. ctx->addAgentsReplyLen(mc->queryBytesReceived());
  4138. mc.clear(); // Or we won't free memory for graphs that get recreated
  4139. mu.clear(); //ditto
  4140. deferredStart = false;
  4141. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  4142. }
  4143. virtual IOutputMetaData * queryOutputMeta() const
  4144. {
  4145. return helper.queryOutputMeta();
  4146. }
  4147. virtual unsigned __int64 queryTotalCycles() const
  4148. {
  4149. return totalCycles;
  4150. }
  4151. void gatherStats(CRuntimeStatisticCollection & merged) const
  4152. {
  4153. if (rowAllocator)
  4154. rowAllocator->gatherStats(merged);
  4155. }
  4156. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4157. {
  4158. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4159. {
  4160. StringBuffer recstr;
  4161. unsigned i;
  4162. for (i = 0; i < seekLen; i++)
  4163. {
  4164. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4165. }
  4166. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4167. }
  4168. assertex(mergeOrder);
  4169. if (deferredStart)
  4170. {
  4171. CriticalBlock b(pendingCrit);
  4172. ForEachItemIn(idx, pending)
  4173. {
  4174. IRoxieServerQueryPacket &p = pending.item(idx);
  4175. if (p.isDelayed())
  4176. {
  4177. p.setDelayed(false);
  4178. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4179. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4180. MemoryBuffer serializedSkip;
  4181. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4182. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4183. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4184. sentsome.signal();
  4185. }
  4186. }
  4187. deferredStart = false;
  4188. }
  4189. SimpleActivityTimer t(totalCycles, timeActivities);
  4190. if (processed==stopAfter)
  4191. return NULL;
  4192. if (allread)
  4193. return NULL;
  4194. for (;;)
  4195. {
  4196. if (merger.ready())
  4197. {
  4198. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4199. if (got)
  4200. {
  4201. processRow(got);
  4202. return got;
  4203. }
  4204. }
  4205. if (!reload()) // MORE - should pass the seek info here...
  4206. return NULL;
  4207. }
  4208. }
  4209. virtual const void *nextRow()
  4210. {
  4211. // If we are merging then we need to do a heapsort on all
  4212. SimpleActivityTimer t(totalCycles, timeActivities);
  4213. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4214. {
  4215. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4216. }
  4217. for (;;)
  4218. {
  4219. checkDelayed();
  4220. if (processed==stopAfter)
  4221. return NULL;
  4222. if (allread)
  4223. return NULL;
  4224. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4225. const void *got = NULL;
  4226. if (mergeOrder && merger.ready())
  4227. {
  4228. bool matched = true;
  4229. got = merger.next(matched, dummySmartStepExtra);
  4230. }
  4231. else if (mu)
  4232. {
  4233. got = getRow(mu);
  4234. if (!got && meta.isGrouped() && !eogSent)
  4235. {
  4236. eogSent = true;
  4237. return NULL;
  4238. }
  4239. }
  4240. if (got)
  4241. {
  4242. processRow(got);
  4243. return got;
  4244. }
  4245. eogSent = false;
  4246. if (!reload())
  4247. return NULL;
  4248. }
  4249. }
  4250. bool reload()
  4251. {
  4252. // Wait for something to be returned from a agent....
  4253. mu.clear();
  4254. sentsome.wait();
  4255. // must be at least an endMarker on the queue since sentsome was signalled
  4256. {
  4257. CriticalBlock b(pendingCrit);
  4258. IRoxieServerQueryPacket &top = pending.item(0);
  4259. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4260. {
  4261. pending.remove(0);
  4262. return true;
  4263. }
  4264. else if (top.isEnd())
  4265. {
  4266. pending.remove(0);
  4267. allread = true;
  4268. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4269. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4270. return false;
  4271. }
  4272. else if (mergeOrder)
  4273. {
  4274. unsigned idx = 0;
  4275. bool added = false;
  4276. while (pending.isItem(idx))
  4277. {
  4278. IRoxieServerQueryPacket &item = pending.item(idx);
  4279. if (item.isEnd())
  4280. {
  4281. if (merger.noteEndSeen())
  4282. {
  4283. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4284. added = true;
  4285. }
  4286. break;
  4287. }
  4288. else if (item.hasResult())
  4289. {
  4290. merger.noteResult(&item, item.getSequence());
  4291. pending.remove(idx);
  4292. added = true;
  4293. }
  4294. else if (item.isContinuation())
  4295. idx++;
  4296. else
  4297. break;
  4298. }
  4299. if (added)
  4300. return true;
  4301. }
  4302. else if (top.hasResult())
  4303. {
  4304. mr.setown(pending.item(0).getResult());
  4305. mu.setown(mr->getCursor(rowManager));
  4306. pending.remove(0);
  4307. return true;
  4308. }
  4309. }
  4310. getNextUnpacker();
  4311. return true;
  4312. }
  4313. void getNextUnpacker()
  4314. {
  4315. mu.clear();
  4316. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4317. for (;;)
  4318. {
  4319. checkDelayed();
  4320. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4321. activity.queryContext()->checkAbort();
  4322. bool anyActivity;
  4323. if (ctxTraceLevel > 5)
  4324. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4325. mr.setown(mc->getNextResult(timeout, anyActivity));
  4326. if (ctxTraceLevel > 6)
  4327. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4328. activity.queryContext()->checkAbort();
  4329. if (mr)
  4330. {
  4331. unsigned roxieHeaderLen;
  4332. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4333. #ifdef _DEBUG
  4334. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4335. #endif
  4336. if (ctxTraceLevel > 5)
  4337. {
  4338. StringBuffer s;
  4339. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4340. }
  4341. CriticalBlock b(pendingCrit);
  4342. unsigned idx = 0;
  4343. IRoxieServerQueryPacket *original = NULL;
  4344. IRoxieQueryPacket *op;
  4345. while (pending.isItem(idx))
  4346. {
  4347. original = &pending.item(idx);
  4348. op = original->queryPacket();
  4349. if (op && header.matchPacket(op->queryHeader()))
  4350. break;
  4351. original = NULL;
  4352. idx++;
  4353. }
  4354. if (!original || original->hasResult())
  4355. {
  4356. switch (header.activityId)
  4357. {
  4358. case ROXIE_FILECALLBACK:
  4359. {
  4360. // tell agent to abort
  4361. //if (ctxTraceLevel > 5)
  4362. {
  4363. StringBuffer s;
  4364. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4365. }
  4366. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4367. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4368. if (len)
  4369. {
  4370. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4371. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4372. const char *rowdata = (const char *) row.get();
  4373. // bool isOpt = * (bool *) rowdata;
  4374. // bool isLocal = * (bool *) (rowdata+1);
  4375. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4376. }
  4377. else
  4378. throwUnexpected();
  4379. break;
  4380. }
  4381. // MORE - ROXIE_ALIVE perhaps should go here too
  4382. default:
  4383. if (ctxTraceLevel > 3)
  4384. activity.queryLogCtx().CTXLOG("Discarding packet %p %x - original %p is NULL or has result already", mr.get(), header.activityId, original);
  4385. mr->discard();
  4386. break;
  4387. }
  4388. mr.clear();
  4389. }
  4390. else
  4391. {
  4392. resultsReceived++;
  4393. switch (header.activityId)
  4394. {
  4395. case ROXIE_DEBUGCALLBACK:
  4396. {
  4397. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4398. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4399. if (len)
  4400. {
  4401. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4402. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4403. char *rowdata = (char *) row.get();
  4404. if (ctxTraceLevel > 5)
  4405. {
  4406. StringBuffer s;
  4407. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4408. }
  4409. MemoryBuffer agentInfo;
  4410. agentInfo.setBuffer(*rowlen, rowdata, false);
  4411. unsigned debugSequence;
  4412. agentInfo.read(debugSequence);
  4413. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4414. if (!reply)
  4415. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4416. if (reply)
  4417. {
  4418. original->setDebugResponse(debugSequence, reply);
  4419. ROQ->sendPacket(reply, activity.queryLogCtx());
  4420. }
  4421. }
  4422. else
  4423. throwUnexpected();
  4424. // MORE - somehow we need to make sure agent gets a reply even if I'm not waiting (in udp layer)
  4425. // Leave original message on pending queue in original location - this is not a reply to it.
  4426. break;
  4427. }
  4428. case ROXIE_FILECALLBACK:
  4429. {
  4430. // we need to send back to the agent a message containing the file info requested.
  4431. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4432. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4433. if (len)
  4434. {
  4435. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4436. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4437. const char *rowdata = (const char *) row.get();
  4438. bool isOpt = * (bool *) rowdata;
  4439. bool isLocal = * (bool *) (rowdata+1);
  4440. const char *lfn = rowdata+2;
  4441. if (ctxTraceLevel > 5)
  4442. {
  4443. StringBuffer s;
  4444. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4445. }
  4446. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal, defaultPrivilegedUser);
  4447. }
  4448. else
  4449. throwUnexpected();
  4450. // MORE - somehow we need to make sure agent gets a reply even if I'm not waiting (in udp layer)
  4451. // Leave original message on pending queue in original location - this is not a reply to it.
  4452. break;
  4453. }
  4454. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4455. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4456. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4457. throwUnexpected();
  4458. case ROXIE_LIMIT_EXCEEDED:
  4459. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4460. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4461. throwUnexpected();
  4462. case ROXIE_TRACEINFO:
  4463. {
  4464. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4465. for (;;)
  4466. {
  4467. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4468. if (rowlen)
  4469. {
  4470. char *logInfo = (char *) extra->getNext(*rowlen);
  4471. MemoryBuffer buf;
  4472. buf.setBuffer(*rowlen, logInfo, false);
  4473. switch ((TracingCategory) *logInfo)
  4474. {
  4475. case LOG_TRACING:
  4476. case LOG_ERROR:
  4477. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4478. break;
  4479. case LOG_STATVALUES:
  4480. buf.skip(1);
  4481. activity.mergeStats(buf);
  4482. break;
  4483. case LOG_CHILDCOUNT:
  4484. case LOG_CHILDSTATS:
  4485. //These need rethinking - all child stats should be serialized in a single block, and should be merged into
  4486. //the information for an activity, ready for reporting later
  4487. unsigned graphId, childId;
  4488. buf.skip(1);
  4489. buf.read(graphId);
  4490. buf.read(childId);
  4491. if (*logInfo == LOG_CHILDCOUNT)
  4492. {
  4493. unsigned idx;
  4494. unsigned childProcessed;
  4495. unsigned childStrands;
  4496. buf.read(idx);
  4497. buf.read(childProcessed);
  4498. buf.read(childStrands);
  4499. if (traceLevel > 5)
  4500. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4501. //activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4502. }
  4503. else
  4504. {
  4505. CRuntimeStatisticCollection childStats(allStatistics);
  4506. childStats.deserialize(buf);
  4507. if (traceLevel > 5)
  4508. {
  4509. StringBuffer s;
  4510. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4511. }
  4512. //activity.queryContext()->mergeActivityStats(childStats, graphId, childId);
  4513. activity.mergeStats(childStats);
  4514. }
  4515. }
  4516. ReleaseRoxieRow(rowlen);
  4517. ReleaseRoxieRow(logInfo);
  4518. }
  4519. else
  4520. break;
  4521. }
  4522. break;
  4523. }
  4524. case ROXIE_EXCEPTION:
  4525. if (ctxTraceLevel > 1)
  4526. {
  4527. StringBuffer s;
  4528. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4529. }
  4530. op->queryHeader().noteException(header.retries);
  4531. if (op->queryHeader().allChannelsFailed())
  4532. {
  4533. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4534. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4535. throwRemoteException(exceptionData);
  4536. }
  4537. // Leave it on pending queue in original location
  4538. break;
  4539. case ROXIE_ALIVE:
  4540. if (ctxTraceLevel > 4)
  4541. {
  4542. StringBuffer s;
  4543. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4544. }
  4545. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4546. // Leave it on pending queue in original location
  4547. break;
  4548. default:
  4549. if (header.retries & ROXIE_RETRIES_MASK)
  4550. retriesNeeded++;
  4551. unsigned metaLen;
  4552. const void *metaData = mr->getMessageMetadata(metaLen);
  4553. if (metaLen)
  4554. {
  4555. // We got back first chunk but there is more.
  4556. // resend the packet, with the cursor info provided.
  4557. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4558. if (ctxTraceLevel > 1)
  4559. {
  4560. StringBuffer s;
  4561. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4562. }
  4563. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4564. {
  4565. StringBuffer s;
  4566. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4567. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4568. throwUnexpected();
  4569. }
  4570. MemoryBuffer nextQuery;
  4571. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4572. nextQuery.append(metaLen, metaData);
  4573. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4574. nextQuery.append(op->getContextLength(), op->queryContextData());
  4575. if (resendSequence == CONTINUESEQUENCE_MAX)
  4576. {
  4577. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4578. resendSequence = 1;
  4579. }
  4580. else
  4581. resendSequence++;
  4582. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4583. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4584. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4585. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4586. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4587. fqp->setSequence(original->getSequence());
  4588. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4589. original->setContinuation(LINK(fqp));
  4590. if (mergeOrder)
  4591. fqp->setDelayed(true);
  4592. else
  4593. {
  4594. ROQ->sendPacket(resend, activity.queryLogCtx());
  4595. sentsome.signal();
  4596. }
  4597. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4598. }
  4599. else
  4600. {
  4601. if (serverSideCache)
  4602. serverSideCache->noteCachedResult(original, mr);
  4603. }
  4604. unsigned channel = header.channel;
  4605. {
  4606. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4607. if (b)
  4608. b->signal();
  4609. }
  4610. original->setResult(mr.getClear());
  4611. sentsome.signal();
  4612. return;
  4613. }
  4614. }
  4615. }
  4616. else
  4617. {
  4618. if (!anyActivity && !localAgent)
  4619. {
  4620. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4621. retryPending();
  4622. }
  4623. }
  4624. }
  4625. }
  4626. inline unsigned headerLength() const
  4627. {
  4628. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4629. }
  4630. void copyHeader(byte *tgt, unsigned channel) const
  4631. {
  4632. unsigned len = logInfo.length();
  4633. memcpy(tgt, logInfo.toByteArray(), len);
  4634. tgt += len;
  4635. *(unsigned *) tgt = parentExtractSize;
  4636. tgt += sizeof(unsigned);
  4637. if (parentExtractSize)
  4638. {
  4639. memcpy(tgt, parentExtract, parentExtractSize);
  4640. tgt += parentExtractSize;
  4641. }
  4642. if (cachedContext.length())
  4643. {
  4644. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4645. tgt += cachedContext.length();
  4646. }
  4647. }
  4648. };
  4649. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4650. {
  4651. Owned <IException> exception;
  4652. bool skipping;
  4653. ConstPointerArray buff;
  4654. unsigned index;
  4655. bool pulled;
  4656. void pullInput()
  4657. {
  4658. try
  4659. {
  4660. if (exception)
  4661. throw exception.getClear();
  4662. unsigned __int64 count = 0;
  4663. for (;;)
  4664. {
  4665. const void * next = CRemoteResultAdaptor::nextRow();
  4666. if (next == NULL)
  4667. {
  4668. next = CRemoteResultAdaptor::nextRow();
  4669. if(next == NULL)
  4670. break;
  4671. buff.append(NULL);
  4672. }
  4673. count++;
  4674. if (count > rowLimit)
  4675. {
  4676. ReleaseRoxieRow(next);
  4677. ReleaseRoxieRows(buff);
  4678. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4679. throwUnexpected();
  4680. }
  4681. else if (count > keyedLimit)
  4682. {
  4683. ReleaseRoxieRow(next);
  4684. ReleaseRoxieRows(buff);
  4685. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4686. throwUnexpected();
  4687. }
  4688. buff.append(next);
  4689. }
  4690. }
  4691. catch (IException *E)
  4692. {
  4693. if (QUERYINTERFACE(E, LimitSkipException))
  4694. {
  4695. Owned<IException> cleanup = E;
  4696. ReleaseRoxieRows(buff);
  4697. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4698. if (onfail)
  4699. buff.append(onfail);
  4700. }
  4701. else
  4702. throw;
  4703. }
  4704. pulled = true;
  4705. }
  4706. public:
  4707. CSkippableRemoteResultAdaptor(IRoxieAgentContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4708. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4709. {
  4710. skipping = _skipping;
  4711. index = 0;
  4712. pulled = false;
  4713. }
  4714. void setException(IException *E)
  4715. {
  4716. exception.setown(E);
  4717. }
  4718. virtual void onReset()
  4719. {
  4720. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4721. buff.kill();
  4722. index = 0;
  4723. pulled = false;
  4724. exception.clear();
  4725. CRemoteResultAdaptor::onReset();
  4726. }
  4727. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4728. {
  4729. index = 0;
  4730. pulled = false;
  4731. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4732. }
  4733. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4734. {
  4735. // 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
  4736. if (exception)
  4737. throw exception.getClear();
  4738. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4739. }
  4740. virtual const void *nextRow()
  4741. {
  4742. if (skipping)
  4743. {
  4744. if(!pulled)
  4745. pullInput();
  4746. if(buff.isItem(index))
  4747. {
  4748. const void * next = buff.item(index++);
  4749. if(next)
  4750. processed++;
  4751. return next;
  4752. }
  4753. return NULL;
  4754. }
  4755. else
  4756. {
  4757. if (exception)
  4758. throw exception.getClear();
  4759. return CRemoteResultAdaptor::nextRow();
  4760. }
  4761. }
  4762. };
  4763. //=================================================================================
  4764. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4765. {
  4766. IHThorApplyArg &helper;
  4767. public:
  4768. CRoxieServerApplyActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4769. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4770. {
  4771. }
  4772. virtual void onExecute()
  4773. {
  4774. helper.start();
  4775. for (;;)
  4776. {
  4777. const void * next = inputStream->ungroupedNextRow();
  4778. if (!next)
  4779. break;
  4780. helper.apply(next);
  4781. ReleaseRoxieRow(next);
  4782. }
  4783. helper.end();
  4784. }
  4785. };
  4786. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4787. {
  4788. bool isRoot;
  4789. public:
  4790. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4791. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4792. {
  4793. }
  4794. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  4795. {
  4796. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4797. }
  4798. virtual bool isSink() const
  4799. {
  4800. return isRoot;
  4801. }
  4802. };
  4803. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4804. {
  4805. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4806. }
  4807. //=================================================================================
  4808. class CRoxieServerNullActivity : public CRoxieServerActivity
  4809. {
  4810. public:
  4811. CRoxieServerNullActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4812. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4813. {
  4814. }
  4815. virtual const void *nextRow()
  4816. {
  4817. return NULL;
  4818. }
  4819. };
  4820. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4821. {
  4822. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4823. }
  4824. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4825. {
  4826. public:
  4827. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4828. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4829. {
  4830. }
  4831. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  4832. {
  4833. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4834. }
  4835. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4836. {
  4837. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4838. }
  4839. };
  4840. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4841. {
  4842. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4843. }
  4844. //=================================================================================
  4845. class CRoxieServerNullSinkActivity : public CRoxieServerInternalSinkActivity
  4846. {
  4847. public:
  4848. CRoxieServerNullSinkActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4849. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0)
  4850. {
  4851. }
  4852. //override execute() to ensure that start is nevr called on any input activities.
  4853. virtual void execute(unsigned parentExtractSize, const byte * parentExtract) override
  4854. {
  4855. CriticalBlock b(ecrit);
  4856. if (!executed)
  4857. {
  4858. executed = true;
  4859. stop();
  4860. }
  4861. }
  4862. virtual void onExecute() override
  4863. {
  4864. }
  4865. };
  4866. IRoxieServerActivity * createRoxieServerNullSinkActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4867. {
  4868. return new CRoxieServerNullSinkActivity(_ctx, _factory, _probeManager);
  4869. }
  4870. //=================================================================================
  4871. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4872. {
  4873. public:
  4874. CRoxieServerPassThroughActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4875. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4876. {
  4877. }
  4878. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4879. {
  4880. return input->gatherConjunctions(collector);
  4881. }
  4882. virtual void resetEOF()
  4883. {
  4884. inputStream->resetEOF();
  4885. }
  4886. virtual const void *nextRow()
  4887. {
  4888. const void * next = inputStream->nextRow();
  4889. if (next)
  4890. processed++;
  4891. return next;
  4892. }
  4893. virtual bool isPassThrough()
  4894. {
  4895. return true;
  4896. }
  4897. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4898. {
  4899. ActivityTimer t(activityStats, timeActivities);
  4900. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4901. if (next)
  4902. processed++;
  4903. return next;
  4904. }
  4905. IInputSteppingMeta * querySteppingMeta()
  4906. {
  4907. return input->querySteppingMeta();
  4908. }
  4909. };
  4910. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4911. {
  4912. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4913. }
  4914. //=================================================================================
  4915. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4916. {
  4917. protected:
  4918. bool eof;
  4919. bool first;
  4920. public:
  4921. CRoxieServerChildBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4922. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4923. {
  4924. eof = false;
  4925. first = true;
  4926. }
  4927. ~CRoxieServerChildBaseActivity()
  4928. {
  4929. }
  4930. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4931. {
  4932. eof = false;
  4933. first = true;
  4934. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4935. }
  4936. };
  4937. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4938. {
  4939. public:
  4940. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4941. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4942. {
  4943. }
  4944. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4945. {
  4946. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4947. }
  4948. };
  4949. //=================================================================================
  4950. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4951. {
  4952. IHThorChildIteratorArg &helper;
  4953. public:
  4954. CRoxieServerChildIteratorActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4955. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4956. {
  4957. }
  4958. virtual bool needsAllocator() const { return true; }
  4959. virtual const void *nextRow()
  4960. {
  4961. ActivityTimer t(activityStats, timeActivities);
  4962. if (eof)
  4963. return NULL;
  4964. bool ok;
  4965. if (first)
  4966. {
  4967. ok = helper.first();
  4968. first = false;
  4969. }
  4970. else
  4971. ok = helper.next();
  4972. try
  4973. {
  4974. while (ok)
  4975. {
  4976. processed++;
  4977. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4978. unsigned outSize = helper.transform(rowBuilder);
  4979. if (outSize)
  4980. return rowBuilder.finalizeRowClear(outSize);
  4981. ok = helper.next();
  4982. }
  4983. }
  4984. catch (IException *E)
  4985. {
  4986. throw makeWrappedException(E);
  4987. }
  4988. eof = true;
  4989. return NULL;
  4990. }
  4991. };
  4992. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4993. {
  4994. public:
  4995. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4996. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4997. {
  4998. }
  4999. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5000. {
  5001. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  5002. }
  5003. };
  5004. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5005. {
  5006. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5007. }
  5008. //=================================================================================
  5009. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  5010. {
  5011. IHThorChildNormalizeArg &helper;
  5012. public:
  5013. CRoxieServerChildNormalizeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5014. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  5015. {
  5016. }
  5017. virtual bool needsAllocator() const { return true; }
  5018. virtual const void *nextRow()
  5019. {
  5020. ActivityTimer t(activityStats, timeActivities);
  5021. if (eof)
  5022. return NULL;
  5023. bool ok;
  5024. if (first)
  5025. {
  5026. ok = helper.first();
  5027. first = false;
  5028. }
  5029. else
  5030. ok = helper.next();
  5031. if (ok)
  5032. {
  5033. try
  5034. {
  5035. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5036. do {
  5037. unsigned outSize = helper.transform(rowBuilder);
  5038. if (outSize)
  5039. {
  5040. processed++;
  5041. return rowBuilder.finalizeRowClear(outSize);
  5042. }
  5043. ok = helper.next();
  5044. }
  5045. while (ok);
  5046. }
  5047. catch (IException *E)
  5048. {
  5049. throw makeWrappedException(E);
  5050. }
  5051. }
  5052. eof = true;
  5053. return NULL;
  5054. }
  5055. };
  5056. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  5057. {
  5058. public:
  5059. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5060. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5061. {
  5062. }
  5063. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5064. {
  5065. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  5066. }
  5067. };
  5068. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5069. {
  5070. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5071. }
  5072. //=================================================================================
  5073. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  5074. {
  5075. IHThorChildAggregateArg &helper;
  5076. public:
  5077. CRoxieServerChildAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5078. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  5079. {
  5080. }
  5081. virtual bool needsAllocator() const { return true; }
  5082. virtual const void *nextRow()
  5083. {
  5084. ActivityTimer t(activityStats, timeActivities);
  5085. if (eof)
  5086. return NULL;
  5087. eof = true;
  5088. processed++;
  5089. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5090. helper.clearAggregate(rowBuilder);
  5091. helper.processRows(rowBuilder);
  5092. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  5093. return rowBuilder.finalizeRowClear(finalSize);
  5094. }
  5095. };
  5096. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5097. {
  5098. public:
  5099. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5100. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5101. {
  5102. }
  5103. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5104. {
  5105. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  5106. }
  5107. };
  5108. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5109. {
  5110. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5111. }
  5112. //=================================================================================
  5113. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  5114. {
  5115. IHThorChildGroupAggregateArg &helper;
  5116. RowAggregator aggregated;
  5117. public:
  5118. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  5119. CRoxieServerChildGroupAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5120. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  5121. aggregated(helper, helper)
  5122. {
  5123. }
  5124. void processRow(const void * next)
  5125. {
  5126. aggregated.addRow(next);
  5127. }
  5128. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5129. {
  5130. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5131. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  5132. }
  5133. virtual void reset()
  5134. {
  5135. aggregated.reset();
  5136. CRoxieServerChildBaseActivity::reset();
  5137. }
  5138. virtual bool needsAllocator() const { return true; }
  5139. virtual const void *nextRow()
  5140. {
  5141. ActivityTimer t(activityStats, timeActivities);
  5142. if (eof)
  5143. return NULL;
  5144. if (first)
  5145. {
  5146. helper.processRows(this);
  5147. first = false;
  5148. }
  5149. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  5150. if (next)
  5151. {
  5152. processed++;
  5153. return next->finalizeRowClear();
  5154. }
  5155. eof = true;
  5156. return NULL;
  5157. }
  5158. };
  5159. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5160. {
  5161. public:
  5162. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5163. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5164. {
  5165. }
  5166. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5167. {
  5168. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  5169. }
  5170. };
  5171. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5172. {
  5173. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5174. }
  5175. //=================================================================================
  5176. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  5177. {
  5178. IHThorChildThroughNormalizeArg &helper;
  5179. const void * lastInput;
  5180. unsigned numProcessedLastGroup;
  5181. bool ok;
  5182. public:
  5183. CRoxieServerChildThroughNormalizeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5184. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5185. {
  5186. lastInput = NULL;
  5187. numProcessedLastGroup = 0;
  5188. ok = false;
  5189. }
  5190. virtual void stop()
  5191. {
  5192. CRoxieServerChildBaseActivity::stop();
  5193. ReleaseRoxieRow(lastInput);
  5194. lastInput = NULL;
  5195. }
  5196. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5197. {
  5198. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5199. numProcessedLastGroup = processed;
  5200. ok = false;
  5201. }
  5202. virtual bool needsAllocator() const { return true; }
  5203. virtual const void *nextRow()
  5204. {
  5205. ActivityTimer t(activityStats, timeActivities);
  5206. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5207. for (;;)
  5208. {
  5209. if (ok)
  5210. ok = helper.next();
  5211. while (!ok)
  5212. {
  5213. ReleaseRoxieRow(lastInput);
  5214. lastInput = inputStream->nextRow();
  5215. if (!lastInput)
  5216. {
  5217. if (numProcessedLastGroup != processed)
  5218. {
  5219. numProcessedLastGroup = processed;
  5220. return NULL;
  5221. }
  5222. lastInput = inputStream->nextRow();
  5223. if (!lastInput)
  5224. return NULL;
  5225. }
  5226. ok = helper.first(lastInput);
  5227. }
  5228. try
  5229. {
  5230. do
  5231. {
  5232. unsigned outSize = helper.transform(rowBuilder);
  5233. if (outSize)
  5234. {
  5235. processed++;
  5236. return rowBuilder.finalizeRowClear(outSize);
  5237. }
  5238. ok = helper.next();
  5239. } while (ok);
  5240. }
  5241. catch (IException *E)
  5242. {
  5243. throw makeWrappedException(E);
  5244. }
  5245. }
  5246. }
  5247. };
  5248. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5249. {
  5250. public:
  5251. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5252. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5253. {
  5254. }
  5255. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5256. {
  5257. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5258. }
  5259. };
  5260. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5261. {
  5262. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5263. }
  5264. //=================================================================================
  5265. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5266. {
  5267. IHThorDistributionArg &helper;
  5268. public:
  5269. CRoxieServerDistributionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5270. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5271. {
  5272. }
  5273. virtual void onExecute()
  5274. {
  5275. MemoryAttr ma;
  5276. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5277. helper.clearAggregate(accumulator);
  5278. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5279. for (;;)
  5280. {
  5281. if (!nextrec)
  5282. {
  5283. nextrec.setown(inputStream->nextRow());
  5284. if (!nextrec)
  5285. break;
  5286. }
  5287. helper.process(accumulator, nextrec);
  5288. nextrec.setown(inputStream->nextRow());
  5289. }
  5290. StringBuffer result;
  5291. result.append("<XML>");
  5292. helper.gatherResult(accumulator, result);
  5293. result.append("</XML>");
  5294. helper.sendResult(result.length(), result.str());
  5295. helper.destruct(accumulator);
  5296. }
  5297. };
  5298. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5299. {
  5300. bool isRoot;
  5301. public:
  5302. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5303. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5304. {
  5305. }
  5306. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5307. {
  5308. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5309. }
  5310. virtual bool isSink() const
  5311. {
  5312. return isRoot;
  5313. }
  5314. };
  5315. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5316. {
  5317. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5318. }
  5319. //=================================================================================
  5320. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5321. {
  5322. IHThorLinkedRawIteratorArg &helper;
  5323. public:
  5324. CRoxieServerLinkedRawIteratorActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5325. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5326. {
  5327. }
  5328. virtual const void *nextRow()
  5329. {
  5330. ActivityTimer t(activityStats, timeActivities);
  5331. const void *ret =helper.next();
  5332. if (ret)
  5333. {
  5334. LinkRoxieRow(ret);
  5335. processed++;
  5336. }
  5337. return ret;
  5338. }
  5339. };
  5340. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5341. {
  5342. public:
  5343. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5344. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5345. {
  5346. }
  5347. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5348. {
  5349. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5350. }
  5351. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5352. {
  5353. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5354. }
  5355. };
  5356. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5357. {
  5358. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5359. }
  5360. //=================================================================================
  5361. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5362. {
  5363. public:
  5364. CRoxieServerDatasetResultActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5365. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5366. {
  5367. }
  5368. virtual const void *nextRow()
  5369. {
  5370. throwUnexpected();
  5371. }
  5372. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5373. {
  5374. try
  5375. {
  5376. start(parentExtractSize, parentExtract, false);
  5377. {
  5378. ActivityTimer t(activityStats, timeActivities);
  5379. MemoryBuffer result;
  5380. IRecordSize * inputMeta = input->queryOutputMeta();
  5381. for (;;)
  5382. {
  5383. const void *nextrec = inputStream->ungroupedNextRow();
  5384. if (!nextrec)
  5385. break;
  5386. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5387. ReleaseRoxieRow(nextrec);
  5388. }
  5389. retSize = result.length();
  5390. ret = result.detach();
  5391. }
  5392. stop();
  5393. reset();
  5394. }
  5395. catch(IException *E)
  5396. {
  5397. ctx->notifyAbort(E);
  5398. abort();
  5399. reset();
  5400. throw;
  5401. }
  5402. catch(...)
  5403. {
  5404. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5405. ctx->notifyAbort(E);
  5406. abort();
  5407. reset();
  5408. throw;
  5409. }
  5410. }
  5411. };
  5412. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5413. {
  5414. bool isRoot;
  5415. public:
  5416. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5417. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5418. {
  5419. }
  5420. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5421. {
  5422. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5423. }
  5424. virtual bool isSink() const
  5425. {
  5426. return isRoot;
  5427. }
  5428. };
  5429. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5430. {
  5431. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5432. }
  5433. //=================================================================================
  5434. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5435. {
  5436. IHThorInlineTableArg &helper;
  5437. __uint64 curRow;
  5438. __uint64 numRows;
  5439. public:
  5440. CRoxieServerInlineTableActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5441. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5442. {
  5443. curRow = 0;
  5444. numRows = 0;
  5445. }
  5446. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5447. {
  5448. curRow = 0;
  5449. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5450. numRows = helper.numRows();
  5451. }
  5452. virtual bool needsAllocator() const { return true; }
  5453. virtual const void *nextRow()
  5454. {
  5455. ActivityTimer t(activityStats, timeActivities);
  5456. // Filtering empty rows, returns the next valid row
  5457. while (curRow < numRows)
  5458. {
  5459. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5460. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5461. if (outSize)
  5462. {
  5463. processed++;
  5464. return rowBuilder.finalizeRowClear(outSize);
  5465. }
  5466. }
  5467. return NULL;
  5468. }
  5469. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5470. {
  5471. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5472. }
  5473. };
  5474. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5475. {
  5476. IHThorInlineTableArg &helper;
  5477. __uint64 numRows;
  5478. //An inline table that isn't stranded
  5479. class InlineTableSimpleProcessor : public StrandProcessor
  5480. {
  5481. protected:
  5482. IHThorInlineTableArg &helper;
  5483. __uint64 curRow;
  5484. __uint64 maxRows;
  5485. public:
  5486. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5487. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5488. {
  5489. }
  5490. virtual void start() override
  5491. {
  5492. StrandProcessor::start();
  5493. curRow = 0;
  5494. maxRows = queryParent().numRows;
  5495. }
  5496. virtual const void * nextRow()
  5497. {
  5498. ActivityTimer t(activityStats, timeActivities);
  5499. //Return rows while the current section is active
  5500. while (curRow < maxRows)
  5501. {
  5502. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5503. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5504. if (outSize)
  5505. {
  5506. processed++;
  5507. return rowBuilder.finalizeRowClear(outSize);
  5508. }
  5509. }
  5510. return NULL;
  5511. }
  5512. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5513. };
  5514. class InlineTableStrandProcessor : public StrandProcessor
  5515. {
  5516. protected:
  5517. IHThorInlineTableArg &helper;
  5518. unsigned whichStrand;
  5519. unsigned numStrands = 0;
  5520. __uint64 sectionSize;
  5521. __uint64 curRow = 0;
  5522. __uint64 sectionMaxRows = 0;
  5523. __uint64 maxRows = 0;
  5524. bool isOrdered;
  5525. bool eosPending;
  5526. public:
  5527. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5528. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5529. {
  5530. sectionSize = queryParent().strandOptions.blockSize;
  5531. eosPending = false;
  5532. }
  5533. virtual void start() override
  5534. {
  5535. StrandProcessor::start();
  5536. numStrands = queryParent().numStrands();
  5537. maxRows = queryParent().numRows;
  5538. curRow = std::min(whichStrand * sectionSize, maxRows);
  5539. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5540. eosPending = isOrdered && (curRow != maxRows);
  5541. }
  5542. virtual const void * nextRow()
  5543. {
  5544. ActivityTimer t(activityStats, timeActivities);
  5545. for (;;)
  5546. {
  5547. //Return rows while the current section is active
  5548. while (curRow < sectionMaxRows)
  5549. {
  5550. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5551. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5552. if (outSize)
  5553. {
  5554. processed++;
  5555. return rowBuilder.finalizeRowClear(outSize);
  5556. }
  5557. }
  5558. if (curRow == maxRows)
  5559. return NULL;
  5560. //Update current position to the next section
  5561. curRow += (numStrands - 1) * sectionSize;
  5562. if (curRow > maxRows)
  5563. curRow = maxRows;
  5564. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5565. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5566. if (eosPending)
  5567. {
  5568. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5569. eosPending = isOrdered && (curRow != maxRows);
  5570. return queryEndOfSectionMarker();
  5571. }
  5572. }
  5573. }
  5574. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5575. };
  5576. public:
  5577. CRoxieServerStrandedInlineTableActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5578. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5579. {
  5580. numRows = 0;
  5581. }
  5582. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5583. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5584. {
  5585. if (strandOptions.numStrands <= 1)
  5586. return new InlineTableSimpleProcessor(*this, helper);
  5587. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5588. }
  5589. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5590. {
  5591. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5592. numRows = helper.numRows();
  5593. onStartStrands();
  5594. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5595. }
  5596. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5597. {
  5598. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5599. }
  5600. };
  5601. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5602. {
  5603. StrandOptions strandOptions;
  5604. public:
  5605. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5606. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5607. {
  5608. optStableInput = false; // do not force the output to be ordered
  5609. }
  5610. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5611. {
  5612. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5613. }
  5614. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5615. {
  5616. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5617. }
  5618. };
  5619. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5620. {
  5621. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5622. }
  5623. //=================================================================================
  5624. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5625. {
  5626. IHThorWorkunitReadArg &helper;
  5627. CriticalSection readerCrit;
  5628. Owned<IWorkUnitRowReader> wuReader;
  5629. public:
  5630. CRoxieServerWorkUnitReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5631. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5632. {
  5633. }
  5634. virtual void onCreate(IHThorArg *_colocalParent)
  5635. {
  5636. CRoxieServerActivity::onCreate(_colocalParent);
  5637. if (!ctx->queryServerContext())
  5638. {
  5639. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in agent context");
  5640. }
  5641. }
  5642. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5643. {
  5644. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5645. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5646. OwnedRoxieString fromWuid(helper.getWUID());
  5647. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5648. // MORE _ should that be in onCreate?
  5649. }
  5650. virtual void reset()
  5651. {
  5652. {
  5653. CriticalBlock b(readerCrit);
  5654. wuReader.clear();
  5655. }
  5656. CRoxieServerActivity::reset();
  5657. };
  5658. virtual bool needsAllocator() const { return true; }
  5659. virtual const void *nextRow()
  5660. {
  5661. ActivityTimer t(activityStats, timeActivities);
  5662. Linked<IWorkUnitRowReader> useReader;
  5663. {
  5664. CriticalBlock b(readerCrit);
  5665. if (!wuReader)
  5666. return NULL;
  5667. useReader.set(wuReader);
  5668. }
  5669. const void *ret = useReader->nextRow();
  5670. if (ret)
  5671. processed++;
  5672. return ret;
  5673. }
  5674. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5675. {
  5676. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5677. }
  5678. };
  5679. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5680. {
  5681. public:
  5682. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5683. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5684. {
  5685. }
  5686. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  5687. {
  5688. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5689. }
  5690. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5691. {
  5692. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5693. }
  5694. };
  5695. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5696. {
  5697. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5698. }
  5699. //=================================================================================
  5700. interface ILocalGraphEx : public IEclGraphResults
  5701. {
  5702. public:
  5703. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5704. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5705. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5706. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5707. };
  5708. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5709. {
  5710. public:
  5711. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5712. IMPLEMENT_IINTERFACE
  5713. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5714. {
  5715. connectInputStreams(ctx, consumerOrdered);
  5716. streams.append(this);
  5717. return NULL;
  5718. }
  5719. void connectInputStreams(IRoxieAgentContext *ctx, bool consumerOrdered)
  5720. {
  5721. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5722. }
  5723. virtual IOutputMetaData * queryOutputMeta() const
  5724. {
  5725. return input->queryOutputMeta();
  5726. }
  5727. virtual unsigned __int64 queryTotalCycles() const
  5728. {
  5729. return input->queryTotalCycles();
  5730. }
  5731. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5732. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5733. virtual IRoxieServerActivity *queryActivity()
  5734. {
  5735. return input->queryActivity();
  5736. }
  5737. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5738. {
  5739. return input->queryIndexReadActivity();
  5740. }
  5741. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5742. {
  5743. CriticalBlock procedure(cs);
  5744. input->start(parentExtractSize, parentExtract, paused);
  5745. startJunction(junction);
  5746. }
  5747. virtual void stop()
  5748. {
  5749. CriticalBlock procedure(cs);
  5750. inputStream->stop();
  5751. }
  5752. virtual void reset()
  5753. {
  5754. CriticalBlock procedure(cs);
  5755. input->reset();
  5756. resetJunction(junction);
  5757. }
  5758. virtual void resetEOF()
  5759. {
  5760. CriticalBlock procedure(cs);
  5761. inputStream->resetEOF();
  5762. }
  5763. virtual const void *nextRow()
  5764. {
  5765. CriticalBlock procedure(cs);
  5766. return inputStream->nextRow();
  5767. }
  5768. virtual bool nextGroup(ConstPointerArray & group)
  5769. {
  5770. CriticalBlock procedure(cs);
  5771. return inputStream->nextGroup(group);
  5772. }
  5773. private:
  5774. CriticalSection cs;
  5775. Linked<IFinalRoxieInput> input;
  5776. Linked<IEngineRowStream> inputStream;
  5777. Owned<IStrandJunction> junction;
  5778. unsigned sourceIdx;
  5779. };
  5780. //=================================================================================
  5781. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5782. {
  5783. public:
  5784. IMPLEMENT_IINTERFACE;
  5785. CPseudoRoxieInput()
  5786. {
  5787. }
  5788. virtual unsigned __int64 queryTotalCycles() const
  5789. {
  5790. return 0;
  5791. }
  5792. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5793. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5794. virtual IRoxieServerActivity *queryActivity()
  5795. {
  5796. throwUnexpected();
  5797. }
  5798. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5799. {
  5800. throwUnexpected();
  5801. }
  5802. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5803. {
  5804. assertex(!idx);
  5805. streams.append(this);
  5806. return NULL;
  5807. }
  5808. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5809. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5810. virtual void stop() { }
  5811. virtual void reset() { }
  5812. virtual void checkAbort() { }
  5813. virtual void resetEOF() { }
  5814. };
  5815. class CIndirectRoxieInput : public CPseudoRoxieInput
  5816. {
  5817. public:
  5818. CIndirectRoxieInput() : input(NULL)
  5819. {
  5820. stream = NULL;
  5821. sourceIdx = 0;
  5822. }
  5823. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5824. {
  5825. input->start(parentExtractSize, parentExtract, paused);
  5826. startJunction(junction);
  5827. }
  5828. virtual void stop()
  5829. {
  5830. stream->stop();
  5831. }
  5832. virtual void reset()
  5833. {
  5834. input->reset();
  5835. resetJunction(junction);
  5836. }
  5837. virtual const void * nextRow()
  5838. {
  5839. return stream->nextRow();
  5840. }
  5841. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5842. {
  5843. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5844. }
  5845. virtual unsigned __int64 queryTotalCycles() const
  5846. {
  5847. return input ? input->queryTotalCycles() : 0;
  5848. }
  5849. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5850. {
  5851. return input->gatherConjunctions(collector);
  5852. }
  5853. virtual void resetEOF()
  5854. {
  5855. stream->resetEOF();
  5856. }
  5857. virtual unsigned numConcreteOutputs() const
  5858. {
  5859. return input->numConcreteOutputs();
  5860. }
  5861. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5862. {
  5863. return input->queryConcreteInput(idx);
  5864. }
  5865. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5866. {
  5867. return input->queryConcreteOutputStream(whichInput);
  5868. }
  5869. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5870. {
  5871. return input->queryConcreteOutputJunction(idx);
  5872. }
  5873. virtual IOutputMetaData * queryOutputMeta() const
  5874. {
  5875. return input->queryOutputMeta();
  5876. }
  5877. virtual IRoxieServerActivity *queryActivity()
  5878. {
  5879. return input->queryActivity();
  5880. }
  5881. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5882. {
  5883. input = _input;
  5884. sourceIdx = _sourceIdx;
  5885. }
  5886. inline void connectInputStreams(IRoxieAgentContext *ctx, bool consumerOrdered)
  5887. {
  5888. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5889. }
  5890. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5891. {
  5892. assertex(idx == 0);
  5893. connectInputStreams(ctx, consumerOrdered);
  5894. streams.append(this);
  5895. return NULL;
  5896. }
  5897. inline IFinalRoxieInput *queryInput() const
  5898. {
  5899. return input;
  5900. }
  5901. protected:
  5902. unsigned sourceIdx;
  5903. IFinalRoxieInput *input;
  5904. IEngineRowStream *stream;
  5905. Owned<IStrandJunction> junction;
  5906. };
  5907. class CExtractMapperInput : public CIndirectRoxieInput
  5908. {
  5909. unsigned savedParentExtractSize;
  5910. const byte * savedParentExtract;
  5911. public:
  5912. CExtractMapperInput()
  5913. {
  5914. savedParentExtractSize = 0;
  5915. savedParentExtract = NULL;
  5916. }
  5917. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5918. {
  5919. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5920. }
  5921. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5922. {
  5923. savedParentExtractSize = _savedParentExtractSize;
  5924. savedParentExtract = _savedParentExtract;
  5925. }
  5926. };
  5927. class CGraphResult : implements IGraphResult, public CInterface
  5928. {
  5929. CriticalSection cs;
  5930. const byte **rowset;
  5931. size32_t count;
  5932. bool complete;
  5933. void clear()
  5934. {
  5935. CriticalBlock func(cs);
  5936. rtlReleaseRowset(count, rowset);
  5937. rowset = NULL;
  5938. count = 0;
  5939. complete = false;
  5940. }
  5941. public:
  5942. IMPLEMENT_IINTERFACE
  5943. CGraphResult()
  5944. {
  5945. complete = false; // dummy result is not supposed to be used...
  5946. rowset = NULL;
  5947. count = 0;
  5948. }
  5949. CGraphResult(size32_t _count, const byte **_rowset)
  5950. : rowset(_rowset), count(_count)
  5951. {
  5952. complete = true;
  5953. }
  5954. ~CGraphResult()
  5955. {
  5956. clear();
  5957. }
  5958. // interface IGraphResult
  5959. virtual IEngineRowStream * createIterator()
  5960. {
  5961. if (!complete)
  5962. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5963. return new CGraphResultIterator(this);
  5964. }
  5965. virtual void getLinkedResult(unsigned & countResult, const byte * * & result) override
  5966. {
  5967. if (!complete)
  5968. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5969. result = rtlLinkRowset(rowset);
  5970. countResult = count;
  5971. }
  5972. virtual const void * getLinkedRowResult()
  5973. {
  5974. if (!complete)
  5975. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5976. if (count != 1)
  5977. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5978. const void * ret = rowset[0];
  5979. LinkRoxieRow(ret);
  5980. return ret;
  5981. }
  5982. //other
  5983. const void * getRow(unsigned i)
  5984. {
  5985. CriticalBlock func(cs);
  5986. if (i >= count)
  5987. return NULL;
  5988. const void * ret = rowset[i];
  5989. if (ret) LinkRoxieRow(ret);
  5990. return ret;
  5991. }
  5992. protected:
  5993. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5994. {
  5995. unsigned i;
  5996. Linked<CGraphResult> result;
  5997. public:
  5998. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5999. public:
  6000. virtual const void * nextRow()
  6001. {
  6002. return result->getRow(i++);
  6003. }
  6004. virtual void stop()
  6005. {
  6006. }
  6007. virtual void resetEOF()
  6008. {
  6009. throwUnexpected();
  6010. }
  6011. };
  6012. };
  6013. //=================================================================================
  6014. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  6015. {
  6016. IHThorLocalResultReadArg &helper;
  6017. CriticalSection iterCrit;
  6018. Owned<IEngineRowStream> iter;
  6019. ILocalGraphEx * graph;
  6020. unsigned graphId;
  6021. unsigned sequence;
  6022. public:
  6023. CRoxieServerLocalResultReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6024. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  6025. {
  6026. graph = NULL;
  6027. sequence = 0;
  6028. }
  6029. virtual void onCreate(IHThorArg *_colocalParent)
  6030. {
  6031. CRoxieServerActivity::onCreate(_colocalParent);
  6032. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6033. sequence = helper.querySequence();
  6034. }
  6035. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6036. {
  6037. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6038. iter.setown(graph->createResultIterator(sequence));
  6039. }
  6040. virtual void reset()
  6041. {
  6042. {
  6043. CriticalBlock b(iterCrit);
  6044. iter.clear();
  6045. }
  6046. CRoxieServerActivity::reset();
  6047. };
  6048. virtual const void *nextRow()
  6049. {
  6050. ActivityTimer t(activityStats, timeActivities);
  6051. Linked<IEngineRowStream> useIter;
  6052. {
  6053. CriticalBlock b(iterCrit);
  6054. if (!iter)
  6055. return NULL;
  6056. useIter.set(iter);
  6057. }
  6058. const void * next = useIter->nextRow();
  6059. if (next)
  6060. {
  6061. processed++;
  6062. rowsIn++;
  6063. }
  6064. return next;
  6065. }
  6066. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6067. {
  6068. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6069. }
  6070. };
  6071. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  6072. {
  6073. unsigned graphId;
  6074. public:
  6075. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6076. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6077. {
  6078. }
  6079. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6080. {
  6081. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  6082. }
  6083. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6084. {
  6085. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6086. }
  6087. };
  6088. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6089. {
  6090. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6091. }
  6092. //=================================================================================
  6093. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  6094. {
  6095. IHThorLocalResultReadArg &helper;
  6096. unsigned sequence;
  6097. public:
  6098. CRoxieServerLocalResultStreamReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6099. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  6100. {
  6101. sequence = 0;
  6102. }
  6103. virtual void onCreate(IHThorArg *_colocalParent)
  6104. {
  6105. CRoxieServerActivity::onCreate(_colocalParent);
  6106. sequence = helper.querySequence();
  6107. }
  6108. virtual const void *nextRow()
  6109. {
  6110. ActivityTimer t(activityStats, timeActivities);
  6111. const void * next = inputStream->nextRow();
  6112. if (next)
  6113. {
  6114. processed++;
  6115. rowsIn++;
  6116. }
  6117. return next;
  6118. }
  6119. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  6120. {
  6121. if (id == sequence)
  6122. {
  6123. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  6124. connectInputStreams(true);
  6125. return true;
  6126. }
  6127. return false;
  6128. }
  6129. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6130. {
  6131. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6132. }
  6133. };
  6134. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  6135. {
  6136. public:
  6137. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6138. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6139. {
  6140. }
  6141. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6142. {
  6143. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  6144. }
  6145. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6146. {
  6147. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6148. }
  6149. };
  6150. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6151. {
  6152. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6153. }
  6154. //=====================================================================================================
  6155. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  6156. {
  6157. IHThorLocalResultWriteArg &helper;
  6158. ILocalGraphEx * graph;
  6159. unsigned graphId;
  6160. public:
  6161. CRoxieServerLocalResultWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6162. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  6163. {
  6164. graph = NULL;
  6165. }
  6166. virtual bool needsAllocator() const { return true; }
  6167. virtual void onCreate(IHThorArg *_colocalParent)
  6168. {
  6169. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6170. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6171. }
  6172. virtual void onExecute()
  6173. {
  6174. RtlLinkedDatasetBuilder builder(rowAllocator);
  6175. inputStream->readAll(builder);
  6176. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6177. graph->setResult(helper.querySequence(), result);
  6178. }
  6179. virtual const void *nextRow()
  6180. {
  6181. return inputStream->nextRow(); // I can act as a passthrough input
  6182. }
  6183. IFinalRoxieInput * querySelectOutput(unsigned id)
  6184. {
  6185. if (id == helper.querySequence())
  6186. {
  6187. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6188. return LINK(this);
  6189. }
  6190. return NULL;
  6191. }
  6192. };
  6193. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6194. {
  6195. unsigned graphId;
  6196. public:
  6197. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6198. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6199. {
  6200. isInternal = true;
  6201. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6202. }
  6203. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6204. {
  6205. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6206. }
  6207. };
  6208. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6209. {
  6210. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6211. }
  6212. //=====================================================================================================
  6213. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6214. {
  6215. IHThorDictionaryResultWriteArg &helper;
  6216. ILocalGraphEx * graph;
  6217. unsigned graphId;
  6218. public:
  6219. CRoxieServerDictionaryResultWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6220. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6221. {
  6222. graph = NULL;
  6223. }
  6224. virtual bool needsAllocator() const { return true; }
  6225. virtual void onCreate(IHThorArg *_colocalParent)
  6226. {
  6227. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6228. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6229. }
  6230. virtual void onExecute()
  6231. {
  6232. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6233. for (;;)
  6234. {
  6235. const void *row = inputStream->ungroupedNextRow();
  6236. if (!row)
  6237. break;
  6238. builder.appendOwn(row);
  6239. processed++;
  6240. }
  6241. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6242. graph->setResult(helper.querySequence(), result);
  6243. }
  6244. virtual const void *nextRow()
  6245. {
  6246. return inputStream->nextRow(); // I can act as a passthrough input
  6247. }
  6248. IFinalRoxieInput * querySelectOutput(unsigned id)
  6249. {
  6250. if (id == helper.querySequence())
  6251. {
  6252. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6253. return LINK(this);
  6254. }
  6255. return NULL;
  6256. }
  6257. };
  6258. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6259. {
  6260. unsigned graphId;
  6261. public:
  6262. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6263. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6264. {
  6265. isInternal = true;
  6266. }
  6267. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6268. {
  6269. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6270. }
  6271. };
  6272. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6273. {
  6274. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6275. }
  6276. //=================================================================================
  6277. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6278. {
  6279. protected:
  6280. IHThorGraphLoopResultReadArg &helper;
  6281. CriticalSection iterCrit;
  6282. Owned<IFinalRoxieInput> iterInput;
  6283. Owned<IEngineRowStream> iterStream;
  6284. Owned<IStrandJunction> iterJunction;
  6285. ILocalGraphEx * graph;
  6286. unsigned graphId;
  6287. unsigned sequence;
  6288. public:
  6289. CRoxieServerGraphLoopResultReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6290. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6291. {
  6292. graph = NULL;
  6293. sequence = 0;
  6294. }
  6295. virtual void onCreate(IHThorArg *_colocalParent)
  6296. {
  6297. CRoxieServerActivity::onCreate(_colocalParent);
  6298. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6299. }
  6300. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6301. {
  6302. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6303. if (iterInput)
  6304. iterInput->start(parentExtractSize, parentExtract, paused);
  6305. else
  6306. {
  6307. sequence = helper.querySequence();
  6308. if ((int)sequence >= 0)
  6309. {
  6310. try
  6311. {
  6312. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6313. iterInput.clear();
  6314. }
  6315. catch (IException * E)
  6316. {
  6317. throw makeWrappedException(E);
  6318. }
  6319. }
  6320. }
  6321. startJunction(iterJunction);
  6322. }
  6323. virtual void stop()
  6324. {
  6325. if (iterStream)
  6326. iterStream->stop();
  6327. CRoxieServerActivity::stop();
  6328. }
  6329. virtual void reset()
  6330. {
  6331. {
  6332. CriticalBlock b(iterCrit);
  6333. if (iterInput)
  6334. iterInput->reset();
  6335. resetJunction(iterJunction);
  6336. iterInput.clear();
  6337. iterStream.clear();
  6338. iterJunction.clear();
  6339. }
  6340. CRoxieServerActivity::reset();
  6341. };
  6342. virtual const void *nextRow()
  6343. {
  6344. ActivityTimer t(activityStats, timeActivities);
  6345. Linked<IEngineRowStream> useStream;
  6346. {
  6347. CriticalBlock b(iterCrit);
  6348. if (!iterStream)
  6349. return NULL;
  6350. useStream.set(iterStream);
  6351. }
  6352. const void * next = useStream->nextRow();
  6353. if (next)
  6354. {
  6355. processed++;
  6356. rowsIn++;
  6357. }
  6358. return next;
  6359. }
  6360. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6361. {
  6362. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6363. }
  6364. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6365. {
  6366. ensureCreated();
  6367. basehelper.onStart(parentExtract, NULL);
  6368. processor.noteUseIteration(helper.querySequence());
  6369. }
  6370. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6371. {
  6372. //helper already initialised from the gatherIterationUsage() call.
  6373. CRoxieServerActivity::connectInputStreams(true);
  6374. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6375. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6376. }
  6377. virtual IInputSteppingMeta * querySteppingMeta()
  6378. {
  6379. assertex(iterInput);
  6380. return iterInput->querySteppingMeta();
  6381. }
  6382. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6383. {
  6384. assertex(iterStream);
  6385. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6386. }
  6387. };
  6388. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6389. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6390. {
  6391. public:
  6392. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6393. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6394. {
  6395. sequence = _sequence;
  6396. }
  6397. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6398. {
  6399. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6400. if ((int)sequence >= 0)
  6401. {
  6402. try
  6403. {
  6404. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6405. iterInput.clear();
  6406. }
  6407. catch (IException * E)
  6408. {
  6409. throw makeWrappedException(E);
  6410. }
  6411. }
  6412. }
  6413. };
  6414. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6415. {
  6416. unsigned graphId;
  6417. public:
  6418. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6419. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6420. {
  6421. }
  6422. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6423. {
  6424. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6425. }
  6426. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6427. {
  6428. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6429. }
  6430. };
  6431. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6432. {
  6433. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6434. }
  6435. //=====================================================================================================
  6436. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6437. {
  6438. ILocalGraphEx * graph;
  6439. unsigned graphId;
  6440. public:
  6441. CRoxieServerGraphLoopResultWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6442. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), graphId(_graphId)
  6443. {
  6444. graph = NULL;
  6445. }
  6446. virtual bool needsAllocator() const { return true; }
  6447. virtual void onCreate(IHThorArg *_colocalParent)
  6448. {
  6449. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6450. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6451. }
  6452. virtual void onExecute()
  6453. {
  6454. RtlLinkedDatasetBuilder builder(rowAllocator);
  6455. inputStream->readAll(builder);
  6456. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6457. graph->setGraphLoopResult(result);
  6458. }
  6459. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6460. {
  6461. if (idx==0)
  6462. return this;
  6463. else
  6464. return NULL;
  6465. }
  6466. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6467. {
  6468. return input->gatherConjunctions(collector);
  6469. }
  6470. virtual void resetEOF()
  6471. {
  6472. inputStream->resetEOF();
  6473. }
  6474. virtual const void *nextRow()
  6475. {
  6476. const void * next = inputStream->nextRow();
  6477. if (next)
  6478. processed++;
  6479. return next;
  6480. }
  6481. virtual bool isPassThrough()
  6482. {
  6483. return true;
  6484. }
  6485. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6486. {
  6487. ActivityTimer t(activityStats, timeActivities);
  6488. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6489. if (next)
  6490. processed++;
  6491. return next;
  6492. }
  6493. IInputSteppingMeta * querySteppingMeta()
  6494. {
  6495. return input->querySteppingMeta();
  6496. }
  6497. virtual IOutputMetaData * queryOutputMeta() const
  6498. {
  6499. return input->queryOutputMeta();
  6500. }
  6501. };
  6502. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6503. {
  6504. unsigned graphId;
  6505. public:
  6506. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6507. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6508. {
  6509. isInternal = true;
  6510. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6511. }
  6512. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6513. {
  6514. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6515. }
  6516. };
  6517. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6518. {
  6519. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6520. }
  6521. //=================================================================================
  6522. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6523. {
  6524. protected:
  6525. IHThorDedupArg &helper;
  6526. unsigned numKept;
  6527. unsigned numToKeep;
  6528. public:
  6529. CRoxieServerDedupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6530. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6531. {
  6532. numKept = 0;
  6533. numToKeep = 0;
  6534. }
  6535. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6536. {
  6537. numKept = 0;
  6538. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6539. numToKeep = helper.numToKeep();
  6540. }
  6541. };
  6542. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6543. {
  6544. IRangeCompare * stepCompare;
  6545. const void *prev;
  6546. public:
  6547. CRoxieServerDedupKeepLeftActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6548. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6549. {
  6550. prev = NULL;
  6551. stepCompare = NULL;
  6552. }
  6553. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6554. {
  6555. prev = NULL;
  6556. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6557. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6558. stepCompare = NULL;
  6559. if (stepMeta)
  6560. stepCompare = stepMeta->queryCompare();
  6561. }
  6562. virtual void reset()
  6563. {
  6564. ReleaseClearRoxieRow(prev);
  6565. CRoxieServerDedupActivity::reset();
  6566. }
  6567. virtual const void * nextRow()
  6568. {
  6569. ActivityTimer t(activityStats, timeActivities);
  6570. const void * next;
  6571. for (;;)
  6572. {
  6573. next = inputStream->nextRow();
  6574. if (!prev || !next || !helper.matches(prev,next))
  6575. {
  6576. numKept = 0;
  6577. break;
  6578. }
  6579. if (numKept < numToKeep-1)
  6580. {
  6581. numKept++;
  6582. break;
  6583. }
  6584. ReleaseRoxieRow(next);
  6585. }
  6586. ReleaseRoxieRow(prev);
  6587. prev = next;
  6588. if (next)
  6589. {
  6590. LinkRoxieRow(next);
  6591. processed++;
  6592. }
  6593. return next;
  6594. }
  6595. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6596. {
  6597. ActivityTimer t(activityStats, timeActivities);
  6598. const void * next;
  6599. for (;;)
  6600. {
  6601. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6602. //If the record was an in-exact match from the index then return it immediately
  6603. //and don't cause it to dedup following legal records.
  6604. if (!wasCompleteMatch)
  6605. {
  6606. assertex(stepExtra.returnMismatches());
  6607. return next;
  6608. }
  6609. if (!prev || !next || !helper.matches(prev,next))
  6610. {
  6611. numKept = 0;
  6612. break;
  6613. }
  6614. if (numKept < numToKeep-1)
  6615. {
  6616. numKept++;
  6617. break;
  6618. }
  6619. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6620. if (stepExtra.returnMismatches())
  6621. {
  6622. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6623. //condition to advance
  6624. if (stepCompare->docompare(next, seek, numFields) != 0)
  6625. {
  6626. wasCompleteMatch = false;
  6627. break;
  6628. }
  6629. }
  6630. ReleaseRoxieRow(next);
  6631. }
  6632. ReleaseRoxieRow(prev);
  6633. prev = next;
  6634. if (next)
  6635. {
  6636. LinkRoxieRow(next);
  6637. processed++;
  6638. }
  6639. return next;
  6640. }
  6641. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6642. {
  6643. return input->gatherConjunctions(collector);
  6644. }
  6645. virtual void resetEOF()
  6646. {
  6647. inputStream->resetEOF();
  6648. }
  6649. IInputSteppingMeta * querySteppingMeta()
  6650. {
  6651. return input->querySteppingMeta();
  6652. }
  6653. };
  6654. //=================================================================================
  6655. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6656. {
  6657. const void *kept;
  6658. bool first;
  6659. ICompare * compareBest;
  6660. public:
  6661. CRoxieServerDedupKeepRightActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6662. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager), compareBest(nullptr)
  6663. {
  6664. kept = nullptr;
  6665. first = true;
  6666. if (helper.keepBest())
  6667. compareBest = helper.queryCompareBest();
  6668. }
  6669. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6670. {
  6671. first = true;
  6672. kept = nullptr;
  6673. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6674. if (numToKeep>1)
  6675. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6676. }
  6677. virtual void reset()
  6678. {
  6679. ReleaseClearRoxieRow(kept);
  6680. CRoxieServerActivity::reset();
  6681. }
  6682. virtual const void * nextRow()
  6683. {
  6684. ActivityTimer t(activityStats, timeActivities);
  6685. if (first)
  6686. {
  6687. kept = inputStream->nextRow();
  6688. first = false;
  6689. }
  6690. const void * next;
  6691. for (;;)
  6692. {
  6693. next = inputStream->nextRow();
  6694. if (!kept || !next || !helper.matches(kept,next))
  6695. break;
  6696. if (compareBest && compareBest->docompare(kept,next) <= 0)
  6697. continue;
  6698. ReleaseRoxieRow(kept);
  6699. kept = next;
  6700. }
  6701. const void * ret = kept;
  6702. kept = next;
  6703. // CTXLOG("dedup returns %p", ret);
  6704. if (ret) processed++;
  6705. return ret;
  6706. }
  6707. };
  6708. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6709. {
  6710. IHThorDedupArg &helper;
  6711. unsigned survivorIndex;
  6712. ConstPointerArray survivors;
  6713. bool keepLeft;
  6714. bool eof;
  6715. bool first;
  6716. ICompare *primaryCompare;
  6717. public:
  6718. CRoxieServerDedupAllActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6719. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6720. {
  6721. keepLeft = _keepLeft;
  6722. primaryCompare = helper.queryComparePrimary();
  6723. eof = false;
  6724. first = true;
  6725. survivorIndex = 0;
  6726. }
  6727. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6728. {
  6729. eof = false;
  6730. first = true;
  6731. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6732. }
  6733. virtual void reset()
  6734. {
  6735. while (survivors.isItem(survivorIndex))
  6736. {
  6737. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6738. }
  6739. survivors.kill();
  6740. eof = false;
  6741. first = true;
  6742. CRoxieServerActivity::reset();
  6743. }
  6744. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6745. {
  6746. for (unsigned idxL = first; idxL < last; idxL++)
  6747. {
  6748. const void * left = group.item(idxL);
  6749. if (left)
  6750. {
  6751. for (unsigned idxR = first; idxR < last; idxR++)
  6752. {
  6753. const void * right = group.item(idxR);
  6754. if ((idxL != idxR) && right)
  6755. {
  6756. if (helper.matches(left, right))
  6757. {
  6758. if (keepLeft)
  6759. {
  6760. group.replace(NULL, idxR);
  6761. ReleaseRoxieRow(right);
  6762. }
  6763. else
  6764. {
  6765. group.replace(NULL, idxL);
  6766. ReleaseRoxieRow(left);
  6767. break;
  6768. }
  6769. }
  6770. }
  6771. }
  6772. }
  6773. }
  6774. }
  6775. void dedupRange(unsigned first, unsigned last, void ** rows)
  6776. {
  6777. for (unsigned idxL = first; idxL < last; idxL++)
  6778. {
  6779. void * left = rows[idxL];
  6780. if (left)
  6781. {
  6782. for (unsigned idxR = first; idxR < last; idxR++)
  6783. {
  6784. void * right = rows[idxR];
  6785. if ((idxL != idxR) && right)
  6786. {
  6787. if (helper.matches(left, right))
  6788. {
  6789. if (keepLeft)
  6790. {
  6791. rows[idxR] = NULL;
  6792. ReleaseRoxieRow(right);
  6793. }
  6794. else
  6795. {
  6796. rows[idxL] = NULL;
  6797. ReleaseRoxieRow(left);
  6798. break;
  6799. }
  6800. }
  6801. }
  6802. }
  6803. }
  6804. }
  6805. }
  6806. bool calcNextDedupAll()
  6807. {
  6808. survivors.kill();
  6809. survivorIndex = 0;
  6810. ConstPointerArray group;
  6811. if (eof || !inputStream->nextGroup(group))
  6812. {
  6813. eof = true;
  6814. return false;
  6815. }
  6816. unsigned max = group.ordinality();
  6817. if (primaryCompare)
  6818. {
  6819. //hard, if not impossible, to hit this code once optimisations in place
  6820. MemoryAttr indexbuff(max*sizeof(void *));
  6821. void ** temp = (void **)indexbuff.bufferBase();
  6822. void * *rows = const_cast<void * *>(group.getArray());
  6823. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6824. unsigned first = 0;
  6825. for (unsigned idx = 1; idx < max; idx++)
  6826. {
  6827. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6828. {
  6829. dedupRange(first, idx, rows);
  6830. first = idx;
  6831. }
  6832. }
  6833. dedupRange(first, max, rows);
  6834. for(unsigned idx2=0; idx2<max; ++idx2)
  6835. {
  6836. void * cur = rows[idx2];
  6837. if(cur)
  6838. survivors.append(cur);
  6839. }
  6840. }
  6841. else
  6842. {
  6843. dedupRange(0, max, group);
  6844. for(unsigned idx=0; idx<max; ++idx)
  6845. {
  6846. const void * cur = group.item(idx);
  6847. if(cur)
  6848. survivors.append(cur);
  6849. }
  6850. }
  6851. return true;
  6852. }
  6853. virtual const void *nextRow()
  6854. {
  6855. ActivityTimer t(activityStats, timeActivities);
  6856. if (first)
  6857. {
  6858. calcNextDedupAll();
  6859. first = false;
  6860. }
  6861. while (survivors.isItem(survivorIndex))
  6862. {
  6863. const void *ret = survivors.item(survivorIndex++);
  6864. if (ret)
  6865. {
  6866. processed++;
  6867. return ret;
  6868. }
  6869. }
  6870. calcNextDedupAll();
  6871. return NULL;
  6872. }
  6873. };
  6874. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6875. {
  6876. bool compareAll;
  6877. bool keepLeft;
  6878. bool keepBest;
  6879. public:
  6880. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6881. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6882. {
  6883. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6884. compareAll = helper->compareAll();
  6885. keepLeft = helper->keepLeft();
  6886. keepBest = helper->keepBest();
  6887. }
  6888. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  6889. {
  6890. if (compareAll)
  6891. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6892. else if (keepLeft && !keepBest)
  6893. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6894. else
  6895. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6896. }
  6897. };
  6898. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6899. {
  6900. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6901. }
  6902. //=================================================================================
  6903. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6904. {
  6905. bool eof;
  6906. IHThorHashDedupArg &helper;
  6907. class HashDedupElement
  6908. {
  6909. public:
  6910. HashDedupElement(unsigned _hash, const void *_keyRow)
  6911. : hash(_hash), keyRow(_keyRow)
  6912. {
  6913. }
  6914. ~HashDedupElement()
  6915. {
  6916. ReleaseRoxieRow(keyRow);
  6917. }
  6918. inline unsigned queryHash() const
  6919. {
  6920. return hash;
  6921. }
  6922. inline const void *queryRow() const
  6923. {
  6924. return keyRow;
  6925. }
  6926. inline const void *getRowClear()
  6927. {
  6928. const void * row = keyRow;
  6929. keyRow = nullptr;
  6930. return row;
  6931. }
  6932. private:
  6933. unsigned hash;
  6934. const void *keyRow;
  6935. };
  6936. static CClassMeta<HashDedupElement> hashDedupElementMeta;
  6937. class HashDedupTable : public SuperHashTable
  6938. {
  6939. public:
  6940. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6941. : helper(_helper),
  6942. keySize(helper.queryKeySize()),
  6943. activity(_activity)
  6944. {
  6945. bestCompare=helper.queryCompareBest();
  6946. }
  6947. virtual ~HashDedupTable()
  6948. {
  6949. //elementRowAllocator is a unique allocator, so all rows can be freed in a single call
  6950. elementRowAllocator->releaseAllRows();
  6951. tablecount = 0;
  6952. }
  6953. virtual unsigned getHashFromElement(const void *et) const
  6954. {
  6955. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6956. return element->queryHash();
  6957. }
  6958. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6959. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6960. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6961. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6962. {
  6963. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6964. if (fphash != element->queryHash())
  6965. return false;
  6966. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6967. }
  6968. virtual void onAdd(void *et) {}
  6969. virtual void onRemove(void *et)
  6970. {
  6971. ReleaseRoxieRow(et);
  6972. }
  6973. void onCreate(IRoxieAgentContext *ctx)
  6974. {
  6975. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6976. elementRowAllocator.setown(activity.createRowAllocatorEx(&hashDedupElementMeta, roxiemem::RHFunique|roxiemem::RHFscanning|roxiemem::RHFdelayrelease));
  6977. }
  6978. void reset()
  6979. {
  6980. kill();
  6981. }
  6982. bool insert(const void * row)
  6983. {
  6984. unsigned hash = helper.queryHash()->hash(row);
  6985. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6986. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6987. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6988. if (find(hash, keyRow.get()))
  6989. return false;
  6990. addNew(createElement(hash, keyRow.getClear()), hash);
  6991. return true;
  6992. }
  6993. bool insertBest(const void * nextrow)
  6994. {
  6995. unsigned hash = helper.queryHash()->hash(nextrow);
  6996. const void *et = find(hash, nextrow);
  6997. if (et)
  6998. {
  6999. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  7000. const void * row = element->queryRow();
  7001. if (bestCompare->docompare(row,nextrow) <= 0)
  7002. return false;
  7003. removeExact( const_cast<void *>(et));
  7004. // drop-through to add new row
  7005. }
  7006. addNew(createElement(hash, nextrow), hash);
  7007. return true;
  7008. }
  7009. void gatherStats(CRuntimeStatisticCollection & merged) const
  7010. {
  7011. if (keyRowAllocator)
  7012. keyRowAllocator->gatherStats(merged);
  7013. }
  7014. private:
  7015. inline void *createElement(unsigned hash, const void *row)
  7016. {
  7017. return elementRowAllocator->finalizeRow(sizeof(HashDedupElement), new (elementRowAllocator->createRow()) HashDedupElement(hash, row), sizeof(HashDedupElement));
  7018. }
  7019. IHThorHashDedupArg & helper;
  7020. CachedOutputMetaData keySize;
  7021. Owned<IEngineRowAllocator> keyRowAllocator;
  7022. Owned<IEngineRowAllocator> elementRowAllocator;
  7023. CRoxieServerHashDedupActivity & activity;
  7024. ICompare * bestCompare;
  7025. } table;
  7026. public:
  7027. CRoxieServerHashDedupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7028. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this), hashTableFilled(false), hashDedupTableIter(table)
  7029. {
  7030. eof = false;
  7031. keepBest = helper.keepBest();
  7032. }
  7033. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7034. {
  7035. eof = false;
  7036. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7037. }
  7038. virtual void onCreate(IHThorArg *_colocalParent)
  7039. {
  7040. CRoxieServerActivity::onCreate(colocalParent);
  7041. table.onCreate(ctx);
  7042. }
  7043. virtual void reset()
  7044. {
  7045. table.reset();
  7046. eof = false;
  7047. CRoxieServerActivity::reset();
  7048. hashTableFilled = false;
  7049. }
  7050. virtual const void *nextRow()
  7051. {
  7052. ActivityTimer t(activityStats, timeActivities);
  7053. if (keepBest)
  7054. {
  7055. if (eof)
  7056. return NULL;
  7057. // Populate hash table with best rows
  7058. if (!hashTableFilled)
  7059. {
  7060. const void * next = inputStream->nextRow();
  7061. while(next)
  7062. {
  7063. if (!table.insertBest(next))
  7064. ReleaseRoxieRow(next);
  7065. next = inputStream->nextRow();
  7066. }
  7067. if (table.count() == 0)
  7068. eof = true;
  7069. hashTableFilled = true;
  7070. hashDedupTableIter.first();
  7071. }
  7072. // Iterate throw hash table returning rows
  7073. if (hashDedupTableIter.isValid())
  7074. {
  7075. HashDedupElement &el = hashDedupTableIter.query();
  7076. const void * row = el.getRowClear();
  7077. hashDedupTableIter.next();
  7078. return row;
  7079. }
  7080. table.reset();
  7081. hashTableFilled = false;
  7082. return NULL;
  7083. }
  7084. else
  7085. {
  7086. while(!eof)
  7087. {
  7088. const void * next = inputStream->nextRow();
  7089. if(!next)
  7090. {
  7091. if (table.count() == 0)
  7092. eof = true;
  7093. table.reset();
  7094. return NULL;
  7095. }
  7096. if(table.insert(next))
  7097. return next;
  7098. else
  7099. ReleaseRoxieRow(next);
  7100. }
  7101. return NULL;
  7102. }
  7103. }
  7104. private:
  7105. bool keepBest;
  7106. bool hashTableFilled;
  7107. SuperHashIteratorOf<HashDedupElement> hashDedupTableIter;
  7108. };
  7109. CClassMeta<CRoxieServerHashDedupActivity::HashDedupElement> CRoxieServerHashDedupActivity::hashDedupElementMeta;
  7110. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  7111. {
  7112. public:
  7113. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7114. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7115. {
  7116. }
  7117. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7118. {
  7119. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  7120. }
  7121. };
  7122. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7123. {
  7124. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7125. }
  7126. //=================================================================================
  7127. class CRoxieServerRollupActivity : public CRoxieServerActivity
  7128. {
  7129. IHThorRollupArg &helper;
  7130. OwnedConstRoxieRow left;
  7131. OwnedConstRoxieRow prev;
  7132. OwnedConstRoxieRow right;
  7133. bool readFirstRow;
  7134. public:
  7135. CRoxieServerRollupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7136. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  7137. {
  7138. readFirstRow = false;
  7139. }
  7140. ~CRoxieServerRollupActivity()
  7141. {
  7142. }
  7143. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7144. {
  7145. readFirstRow = false;
  7146. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7147. }
  7148. virtual void reset()
  7149. {
  7150. left.clear();
  7151. prev.clear();
  7152. right.clear();
  7153. CRoxieServerActivity::reset();
  7154. }
  7155. virtual bool needsAllocator() const { return true; }
  7156. virtual const void * nextRow()
  7157. {
  7158. ActivityTimer t(activityStats, timeActivities);
  7159. if (!readFirstRow)
  7160. {
  7161. left.setown(inputStream->nextRow());
  7162. prev.set(left);
  7163. readFirstRow = true;
  7164. }
  7165. for (;;)
  7166. {
  7167. right.setown(inputStream->nextRow());
  7168. if(!prev || !right || !helper.matches(prev,right))
  7169. {
  7170. const void * ret = left.getClear();
  7171. if(ret)
  7172. processed++;
  7173. left.setown(right.getClear());
  7174. prev.set(left);
  7175. return ret;
  7176. }
  7177. try
  7178. {
  7179. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7180. unsigned outSize = helper.transform(rowBuilder, left, right);
  7181. if (outSize)
  7182. left.setown(rowBuilder.finalizeRowClear(outSize));
  7183. if (helper.getFlags() & RFrolledismatchleft)
  7184. prev.set(left);
  7185. else
  7186. prev.set(right);
  7187. }
  7188. catch(IException * E)
  7189. {
  7190. throw makeWrappedException(E);
  7191. }
  7192. }
  7193. }
  7194. };
  7195. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  7196. {
  7197. public:
  7198. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7199. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7200. {
  7201. }
  7202. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7203. {
  7204. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  7205. }
  7206. };
  7207. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7208. {
  7209. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7210. }
  7211. //=================================================================================
  7212. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  7213. {
  7214. IHThorNormalizeArg &helper;
  7215. unsigned numThisRow;
  7216. unsigned curRow;
  7217. const void *buffer;
  7218. unsigned numProcessedLastGroup;
  7219. public:
  7220. CRoxieServerNormalizeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7221. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  7222. {
  7223. buffer = NULL;
  7224. numThisRow = 0;
  7225. curRow = 0;
  7226. numProcessedLastGroup = 0;
  7227. }
  7228. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7229. {
  7230. numThisRow = 0;
  7231. curRow = 0;
  7232. numProcessedLastGroup = 0;
  7233. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7234. }
  7235. virtual void reset()
  7236. {
  7237. ReleaseClearRoxieRow(buffer);
  7238. CRoxieServerActivity::reset();
  7239. }
  7240. virtual bool needsAllocator() const { return true; }
  7241. virtual const void * nextRow()
  7242. {
  7243. ActivityTimer t(activityStats, timeActivities);
  7244. for (;;)
  7245. {
  7246. while (curRow == numThisRow)
  7247. {
  7248. if (buffer)
  7249. ReleaseClearRoxieRow(buffer);
  7250. buffer = inputStream->nextRow();
  7251. if (!buffer && (processed == numProcessedLastGroup))
  7252. buffer = inputStream->nextRow();
  7253. if (!buffer)
  7254. {
  7255. numProcessedLastGroup = processed;
  7256. return NULL;
  7257. }
  7258. curRow = 0;
  7259. numThisRow = helper.numExpandedRows(buffer);
  7260. }
  7261. try
  7262. {
  7263. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7264. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7265. if (actualSize != 0)
  7266. {
  7267. processed++;
  7268. return rowBuilder.finalizeRowClear(actualSize);
  7269. }
  7270. }
  7271. catch (IException *E)
  7272. {
  7273. throw makeWrappedException(E);
  7274. }
  7275. }
  7276. }
  7277. };
  7278. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7279. {
  7280. public:
  7281. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7282. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7283. {
  7284. }
  7285. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7286. {
  7287. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7288. }
  7289. };
  7290. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7291. {
  7292. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7293. }
  7294. //=================================================================================
  7295. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7296. {
  7297. IHThorNormalizeChildArg &helper;
  7298. unsigned numThisRow;
  7299. unsigned curRow;
  7300. const void *buffer;
  7301. unsigned numProcessedLastGroup;
  7302. INormalizeChildIterator * cursor;
  7303. const void * curChildRow;
  7304. bool advanceInput()
  7305. {
  7306. for (;;)
  7307. {
  7308. ReleaseClearRoxieRow(buffer);
  7309. buffer = inputStream->nextRow();
  7310. if (!buffer && (processed == numProcessedLastGroup))
  7311. buffer = inputStream->nextRow();
  7312. if (!buffer)
  7313. {
  7314. numProcessedLastGroup = processed;
  7315. return false;
  7316. }
  7317. curChildRow = cursor->first(buffer);
  7318. if (curChildRow)
  7319. {
  7320. curRow = 0;
  7321. return true;
  7322. }
  7323. }
  7324. }
  7325. public:
  7326. CRoxieServerNormalizeChildActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7327. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7328. {
  7329. buffer = NULL;
  7330. cursor = NULL;
  7331. numThisRow = 0;
  7332. curRow = 0;
  7333. numProcessedLastGroup = 0;
  7334. curChildRow = NULL;
  7335. }
  7336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7337. {
  7338. numThisRow = 0;
  7339. curRow = 0;
  7340. numProcessedLastGroup = 0;
  7341. curChildRow = NULL;
  7342. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7343. cursor = helper.queryIterator();
  7344. }
  7345. virtual void stop()
  7346. {
  7347. CRoxieServerActivity::stop();
  7348. }
  7349. virtual void reset()
  7350. {
  7351. cursor = NULL;
  7352. ReleaseClearRoxieRow(buffer);
  7353. CRoxieServerActivity::reset();
  7354. }
  7355. virtual bool needsAllocator() const { return true; }
  7356. const void *nextRow()
  7357. {
  7358. ActivityTimer t(activityStats, timeActivities);
  7359. for (;;)
  7360. {
  7361. if (!buffer)
  7362. {
  7363. if (!advanceInput())
  7364. return NULL;
  7365. }
  7366. try
  7367. {
  7368. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7369. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7370. curChildRow = cursor->next();
  7371. if (!curChildRow)
  7372. ReleaseClearRoxieRow(buffer);
  7373. if (outSize != 0)
  7374. {
  7375. processed++;
  7376. return rowBuilder.finalizeRowClear(outSize);
  7377. }
  7378. }
  7379. catch (IException *E)
  7380. {
  7381. throw makeWrappedException(E);
  7382. }
  7383. }
  7384. }
  7385. };
  7386. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7387. {
  7388. public:
  7389. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7390. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7391. {
  7392. }
  7393. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7394. {
  7395. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7396. }
  7397. };
  7398. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7399. {
  7400. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7401. }
  7402. //=================================================================================
  7403. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7404. {
  7405. IHThorNormalizeLinkedChildArg &helper;
  7406. OwnedConstRoxieRow curParent;
  7407. OwnedConstRoxieRow curChild;
  7408. unsigned numProcessedLastGroup;
  7409. bool advanceInput()
  7410. {
  7411. for (;;)
  7412. {
  7413. curParent.setown(inputStream->nextRow());
  7414. if (!curParent && (processed == numProcessedLastGroup))
  7415. curParent.setown(inputStream->nextRow());
  7416. if (!curParent)
  7417. {
  7418. numProcessedLastGroup = processed;
  7419. return false;
  7420. }
  7421. curChild.set(helper.first(curParent));
  7422. if (curChild)
  7423. return true;
  7424. }
  7425. }
  7426. public:
  7427. CRoxieServerNormalizeLinkedChildActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7428. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7429. {
  7430. numProcessedLastGroup = 0;
  7431. }
  7432. ~CRoxieServerNormalizeLinkedChildActivity()
  7433. {
  7434. }
  7435. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7436. {
  7437. numProcessedLastGroup = 0;
  7438. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7439. }
  7440. virtual void reset()
  7441. {
  7442. curParent.clear();
  7443. curChild.clear();
  7444. CRoxieServerActivity::reset();
  7445. }
  7446. const void *nextRow()
  7447. {
  7448. ActivityTimer t(activityStats, timeActivities);
  7449. for (;;)
  7450. {
  7451. if (!curParent)
  7452. {
  7453. if (!advanceInput())
  7454. return NULL;
  7455. }
  7456. try
  7457. {
  7458. const void *ret = curChild.getClear();
  7459. curChild.set(helper.next());
  7460. if (!curChild)
  7461. curParent.clear();
  7462. if (ret)
  7463. {
  7464. processed++;
  7465. return ret;
  7466. }
  7467. }
  7468. catch (IException *E)
  7469. {
  7470. throw makeWrappedException(E);
  7471. }
  7472. }
  7473. }
  7474. };
  7475. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7476. {
  7477. public:
  7478. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7479. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7480. {
  7481. }
  7482. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7483. {
  7484. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7485. }
  7486. };
  7487. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7488. {
  7489. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7490. }
  7491. //=================================================================================
  7492. class CRoxieServerSortActivity : public CRoxieServerActivity
  7493. {
  7494. protected:
  7495. IHThorSortArg &helper;
  7496. ICompare *compare;
  7497. Owned<ISortAlgorithm> sorter;
  7498. bool readInput;
  7499. RoxieSortAlgorithm sortAlgorithm;
  7500. unsigned sortFlags;
  7501. public:
  7502. CRoxieServerSortActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7503. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7504. {
  7505. compare = helper.queryCompare();
  7506. readInput = false;
  7507. }
  7508. virtual void onCreate(IHThorArg *_colocalParent)
  7509. {
  7510. CRoxieServerActivity::onCreate(_colocalParent);
  7511. if (sortAlgorithm==unknownSortAlgorithm)
  7512. sorter.clear();
  7513. else
  7514. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7515. }
  7516. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7517. {
  7518. assertex(!readInput);
  7519. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7520. }
  7521. virtual void reset()
  7522. {
  7523. if (sorter)
  7524. sorter->reset();
  7525. readInput = false;
  7526. CRoxieServerActivity::reset();
  7527. }
  7528. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7529. {
  7530. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7531. if (!algorithmName)
  7532. algorithmName = "";
  7533. if (stricmp(algorithmName, "quicksort")==0)
  7534. {
  7535. switch (sortFlags & (TAFstable|TAFspill))
  7536. {
  7537. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7538. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7539. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7540. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7541. }
  7542. }
  7543. else if (stricmp(algorithmName, "parquicksort")==0)
  7544. {
  7545. switch (sortFlags & TAFstable)
  7546. {
  7547. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7548. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7549. default: throwUnexpected();
  7550. }
  7551. }
  7552. else if (stricmp(algorithmName, "heapsort")==0)
  7553. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7554. else if (stricmp(algorithmName, "mergesort")==0)
  7555. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7556. else if (stricmp(algorithmName, "parmergesort")==0)
  7557. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7558. #ifdef _USE_TBB
  7559. else if (stricmp(algorithmName, "tbbqsort")==0)
  7560. sortAlgorithm = tbbQuickSortAlgorithm;
  7561. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7562. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7563. #endif
  7564. else
  7565. {
  7566. if (*algorithmName)
  7567. OWARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7568. if (sortFlags & TAFspill)
  7569. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7570. else if (sortFlags & TAFunstable)
  7571. sortAlgorithm = quickSortAlgorithm;
  7572. else
  7573. sortAlgorithm = heapSortAlgorithm;
  7574. }
  7575. return sortAlgorithm;
  7576. }
  7577. virtual const void * nextRow()
  7578. {
  7579. ActivityTimer t(activityStats, timeActivities);
  7580. if (!readInput)
  7581. {
  7582. if (sortAlgorithm == unknownSortAlgorithm)
  7583. {
  7584. sorter.clear();
  7585. OwnedRoxieString algorithmName(helper.getAlgorithm());
  7586. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7587. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7588. }
  7589. sorter->prepare(inputStream);
  7590. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7591. readInput = true;
  7592. }
  7593. const void *ret = sorter->next();
  7594. if (ret)
  7595. processed++;
  7596. else
  7597. {
  7598. sorter->reset();
  7599. readInput = false; // ready for next group
  7600. }
  7601. return ret;
  7602. }
  7603. };
  7604. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7605. {
  7606. RoxieSortAlgorithm sortAlgorithm;
  7607. unsigned sortFlags;
  7608. public:
  7609. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7610. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7611. {
  7612. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7613. const char *algorithmName = NULL;
  7614. sortFlags = sortHelper->getAlgorithmFlags();
  7615. if (sortFlags & TAFconstant)
  7616. algorithmName = sortHelper->getAlgorithm();
  7617. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7618. if (forceSpill)
  7619. sortFlags |= TAFspill;
  7620. if (!(sortFlags & TAFunstable))
  7621. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7622. if (sortFlags & TAFconstant)
  7623. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7624. else
  7625. sortAlgorithm = unknownSortAlgorithm;
  7626. }
  7627. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7628. {
  7629. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7630. }
  7631. virtual const StatisticsMapping &queryStatsMapping() const
  7632. {
  7633. return sortStatistics;
  7634. }
  7635. };
  7636. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7637. {
  7638. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7639. }
  7640. //=====================================================================================================
  7641. static int compareUint64(const void * _left, const void * _right)
  7642. {
  7643. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7644. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7645. if (left < right)
  7646. return -1;
  7647. if (left > right)
  7648. return -1;
  7649. return 0;
  7650. }
  7651. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7652. {
  7653. protected:
  7654. Owned<ISortAlgorithm> sorter;
  7655. IHThorQuantileArg &helper;
  7656. ConstPointerArray sorted;
  7657. ICompare *compare;
  7658. unsigned flags;
  7659. double skew;
  7660. unsigned __int64 numDivisions;
  7661. bool rangeIsAll;
  7662. size32_t rangeSize;
  7663. rtlDataAttr rangeValues;
  7664. bool calculated;
  7665. bool processedAny;
  7666. bool anyThisGroup;
  7667. bool eof;
  7668. unsigned curQuantile;
  7669. unsigned curIndex;
  7670. unsigned curIndexExtra;
  7671. unsigned skipSize;
  7672. unsigned skipExtra;
  7673. unsigned prevIndex;
  7674. public:
  7675. CRoxieServerQuantileActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7676. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7677. {
  7678. compare = helper.queryCompare();
  7679. skew = 0.0;
  7680. numDivisions = 0;
  7681. calculated = false;
  7682. processedAny = false;
  7683. anyThisGroup = false;
  7684. eof = false;
  7685. rangeIsAll = true;
  7686. rangeSize = 0;
  7687. curQuantile = 0;
  7688. prevIndex = 0;
  7689. curIndex = 0;
  7690. curIndexExtra = 0;
  7691. skipSize = 0;
  7692. skipExtra = 0;
  7693. if (flags & TQFunstable)
  7694. sorter.setown(createQuickSortAlgorithm(compare));
  7695. else
  7696. sorter.setown(createMergeSortAlgorithm(compare));
  7697. }
  7698. virtual void reset()
  7699. {
  7700. sorter->reset();
  7701. calculated = false;
  7702. processedAny = false;
  7703. anyThisGroup = false;
  7704. ReleaseRoxieRows(sorted);
  7705. CRoxieServerActivity::reset();
  7706. }
  7707. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7708. {
  7709. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7710. skew = helper.getSkew();
  7711. numDivisions = helper.getNumDivisions();
  7712. //Check for -ve integer values and treat as out of range
  7713. if ((__int64)numDivisions < 1)
  7714. numDivisions = 1;
  7715. if (flags & TQFhasrange)
  7716. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7717. else
  7718. {
  7719. rangeIsAll = true;
  7720. rangeSize = 0;
  7721. }
  7722. if (rangeSize)
  7723. {
  7724. //Sort the range items into order to allow quick comparison
  7725. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7726. }
  7727. calculated = false;
  7728. processedAny = false;
  7729. anyThisGroup = false;
  7730. eof = false;
  7731. curQuantile = 0;
  7732. prevIndex = 0;
  7733. curIndex = 0;
  7734. curIndexExtra = 0;
  7735. }
  7736. virtual bool needsAllocator() const { return true; }
  7737. virtual const void * nextRow()
  7738. {
  7739. ActivityTimer t(activityStats, timeActivities);
  7740. if (eof)
  7741. return NULL;
  7742. const void * ret = NULL;
  7743. for(;;)
  7744. {
  7745. if (!calculated)
  7746. {
  7747. if (flags & TQFlocalsorted)
  7748. {
  7749. for (;;)
  7750. {
  7751. const void * next = inputStream->nextRow();
  7752. if (!next)
  7753. break;
  7754. sorted.append(next);
  7755. }
  7756. }
  7757. else
  7758. {
  7759. sorter->prepare(inputStream);
  7760. sorter->getSortedGroup(sorted);
  7761. }
  7762. if (sorted.ordinality() == 0)
  7763. {
  7764. if (processedAny)
  7765. {
  7766. eof = true;
  7767. return NULL;
  7768. }
  7769. //Unusual case 0 rows - add a default row instead
  7770. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7771. size32_t thisSize = helper.createDefault(rowBuilder);
  7772. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7773. }
  7774. calculated = true;
  7775. processedAny = true;
  7776. anyThisGroup = false;
  7777. curQuantile = 0;
  7778. curIndex = 0;
  7779. curIndexExtra = (unsigned)((numDivisions-1) / 2); // to ensure correctly rounded up
  7780. prevIndex = curIndex-1; // Ensure it doesn't match
  7781. skipSize = (unsigned)(sorted.ordinality() / numDivisions);
  7782. skipExtra = (unsigned)(sorted.ordinality() % numDivisions);
  7783. }
  7784. if (isQuantileIncluded(curQuantile))
  7785. {
  7786. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7787. {
  7788. const void * lhs = sorted.item(curIndex);
  7789. if (flags & TQFneedtransform)
  7790. {
  7791. unsigned outSize;
  7792. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7793. try
  7794. {
  7795. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7796. }
  7797. catch (IException *E)
  7798. {
  7799. throw makeWrappedException(E);
  7800. }
  7801. if (outSize)
  7802. ret = rowBuilder.finalizeRowClear(outSize);
  7803. }
  7804. else
  7805. {
  7806. LinkRoxieRow(lhs);
  7807. ret = lhs;
  7808. }
  7809. prevIndex = curIndex; // even if output was skipped?
  7810. }
  7811. }
  7812. curIndex += skipSize;
  7813. curIndexExtra += skipExtra;
  7814. if (curIndexExtra >= numDivisions)
  7815. {
  7816. curIndex++;
  7817. curIndexExtra -= numDivisions;
  7818. }
  7819. //Ensure the current index always stays valid.
  7820. if (curIndex >= sorted.ordinality())
  7821. curIndex = sorted.ordinality()-1;
  7822. curQuantile++;
  7823. if (curQuantile > numDivisions)
  7824. {
  7825. ReleaseRoxieRows(sorted);
  7826. sorter->reset();
  7827. calculated = false; // ready for next group
  7828. }
  7829. if (ret)
  7830. {
  7831. anyThisGroup = true;
  7832. processed++;
  7833. return ret;
  7834. }
  7835. if (curQuantile > numDivisions)
  7836. {
  7837. if (anyThisGroup)
  7838. return NULL;
  7839. }
  7840. }
  7841. }
  7842. bool isQuantileIncluded(unsigned quantile) const
  7843. {
  7844. if (quantile == 0)
  7845. return (flags & TQFfirst) != 0;
  7846. if (quantile == numDivisions)
  7847. return (flags & TQFlast) != 0;
  7848. if (rangeIsAll)
  7849. return true;
  7850. //Compare against the list of ranges provided
  7851. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7852. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7853. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7854. for (unsigned i = 0; i < rangeNum; i++)
  7855. {
  7856. if (ranges[i] == quantile)
  7857. return true;
  7858. }
  7859. return false;
  7860. }
  7861. };
  7862. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7863. {
  7864. unsigned flags;
  7865. public:
  7866. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7867. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7868. {
  7869. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7870. flags = quantileHelper->getFlags();
  7871. }
  7872. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7873. {
  7874. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7875. }
  7876. };
  7877. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7878. {
  7879. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7880. }
  7881. //=====================================================================================================
  7882. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7883. {
  7884. IHThorSortedArg &helper;
  7885. ICompare * compare;
  7886. const void *prev;
  7887. IRangeCompare * stepCompare;
  7888. public:
  7889. CRoxieServerSortedActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7890. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7891. {
  7892. prev = NULL;
  7893. compare = helper.queryCompare();
  7894. stepCompare = NULL;
  7895. }
  7896. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7897. {
  7898. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7899. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7900. if (stepMeta)
  7901. stepCompare = stepMeta->queryCompare();
  7902. prev = NULL;
  7903. }
  7904. virtual void reset()
  7905. {
  7906. ReleaseClearRoxieRow(prev);
  7907. CRoxieServerActivity::reset();
  7908. }
  7909. virtual const void * nextRow()
  7910. {
  7911. ActivityTimer t(activityStats, timeActivities);
  7912. const void *ret = inputStream->nextRow();
  7913. if (ret && prev && compare->docompare(prev, ret) > 0)
  7914. {
  7915. // MORE - better to give mismatching rows that indexes?
  7916. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7917. }
  7918. ReleaseRoxieRow(prev);
  7919. prev = ret;
  7920. if (ret)
  7921. {
  7922. LinkRoxieRow(prev);
  7923. processed++;
  7924. }
  7925. return ret;
  7926. }
  7927. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7928. {
  7929. ActivityTimer t(activityStats, timeActivities);
  7930. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7931. if (ret && prev && compare->docompare(prev, ret) > 0)
  7932. {
  7933. // MORE - better to give mismatching rows that indexes?
  7934. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7935. }
  7936. ReleaseRoxieRow(prev);
  7937. prev = ret;
  7938. if (ret)
  7939. {
  7940. LinkRoxieRow(prev);
  7941. processed++;
  7942. }
  7943. return ret;
  7944. }
  7945. IInputSteppingMeta * querySteppingMeta()
  7946. {
  7947. return input->querySteppingMeta();
  7948. }
  7949. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7950. {
  7951. return input->gatherConjunctions(collector);
  7952. }
  7953. virtual void resetEOF()
  7954. {
  7955. inputStream->resetEOF();
  7956. }
  7957. };
  7958. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7959. {
  7960. public:
  7961. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7962. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7963. {
  7964. }
  7965. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  7966. {
  7967. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7968. }
  7969. };
  7970. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7971. {
  7972. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7973. }
  7974. //=====================================================================================================
  7975. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7976. {
  7977. /*
  7978. BE VERY CAREFUL - this code is tricky.
  7979. Note that starts and stops (and resets) can occur in strange orders
  7980. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7981. The last stop should call the upstream stop.
  7982. The first reset should call the upstream reset.
  7983. 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
  7984. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7985. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7986. ignored in the minIndex calculation
  7987. */
  7988. public:
  7989. IHThorArg &helper;
  7990. unsigned activeOutputs;
  7991. unsigned numOutputs;
  7992. unsigned numOriginalOutputs;
  7993. QueueOf<const void, true> buffer;
  7994. CriticalSection crit;
  7995. CriticalSection crit2;
  7996. unsigned tailIdx;
  7997. unsigned headIdx;
  7998. Owned<IException> readError;
  7999. Owned<IException> startError;
  8000. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  8001. {
  8002. bool eof, eofpending, stopped;
  8003. public:
  8004. CRoxieServerThroughSpillActivity *parent;
  8005. unsigned idx;
  8006. unsigned oid;
  8007. unsigned processed = 0;
  8008. unsigned numStarts = 0;
  8009. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  8010. public:
  8011. IMPLEMENT_IINTERFACE;
  8012. OutputAdaptor()
  8013. {
  8014. parent = NULL;
  8015. oid = 0;
  8016. idx = 0;
  8017. processed = 0;
  8018. totalCycles = 0;
  8019. eofpending = false;
  8020. eof = false;
  8021. stopped = false;
  8022. }
  8023. ~OutputAdaptor()
  8024. {
  8025. if (traceStartStop)
  8026. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  8027. }
  8028. void init()
  8029. {
  8030. if (traceStartStop)
  8031. DBGLOG("%p init Input adaptor %d", this, oid);
  8032. idx = 0;
  8033. eofpending = false;
  8034. eof = false;
  8035. stopped = false;
  8036. }
  8037. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  8038. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  8039. virtual IRoxieServerActivity *queryActivity()
  8040. {
  8041. return parent;
  8042. }
  8043. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  8044. {
  8045. return parent->queryIndexReadActivity();
  8046. }
  8047. virtual unsigned __int64 queryTotalCycles() const
  8048. {
  8049. return totalCycles;
  8050. }
  8051. virtual const void * nextRow()
  8052. {
  8053. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  8054. if (eof)
  8055. return NULL;
  8056. const void *ret = parent->readBuffered(idx, oid);
  8057. #ifdef TRACE_SPLIT
  8058. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  8059. #endif
  8060. if (ret)
  8061. {
  8062. processed++;
  8063. eofpending = false;
  8064. }
  8065. else if (eofpending)
  8066. eof = true;
  8067. else
  8068. eofpending = true;
  8069. return ret;
  8070. }
  8071. virtual IOutputMetaData * queryOutputMeta() const
  8072. {
  8073. return parent->queryOutputMeta();
  8074. }
  8075. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8076. {
  8077. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  8078. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  8079. // for minIndex to give the correct answers
  8080. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  8081. if (traceStartStop)
  8082. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  8083. parent->start(oid, parentExtractSize, parentExtract, paused);
  8084. numStarts++;
  8085. }
  8086. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  8087. {
  8088. parent->connectInputStreams(consumerOrdered);
  8089. streams.append(this);
  8090. return NULL;
  8091. }
  8092. virtual void stop()
  8093. {
  8094. if (traceStartStop)
  8095. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  8096. if (!stopped)
  8097. {
  8098. parent->stop(oid, idx); // NOTE - may call init()
  8099. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  8100. }
  8101. };
  8102. virtual void reset()
  8103. {
  8104. if (traceStartStop)
  8105. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  8106. parent->reset(oid);
  8107. idx = 0; // value should not be relevant really but this is the safest...
  8108. stopped = false;
  8109. };
  8110. virtual void resetEOF()
  8111. {
  8112. parent->resetEOF();
  8113. }
  8114. virtual void checkAbort()
  8115. {
  8116. parent->checkAbort();
  8117. }
  8118. } *adaptors;
  8119. bool *used;
  8120. unsigned minIndex(unsigned exceptOid)
  8121. {
  8122. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  8123. // this is trying to determine whether any of the adaptors will in the future read a given record
  8124. unsigned minIdx = (unsigned) -1;
  8125. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8126. {
  8127. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  8128. minIdx = adaptors[i].idx;
  8129. }
  8130. return minIdx;
  8131. }
  8132. inline bool isLastTailReader(unsigned exceptOid)
  8133. {
  8134. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8135. {
  8136. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  8137. return false;
  8138. }
  8139. return true;
  8140. }
  8141. void initOutputs()
  8142. {
  8143. activeOutputs = numOutputs;
  8144. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8145. if (used[i])
  8146. adaptors[i].init();
  8147. state = STATEstarting;
  8148. }
  8149. public:
  8150. CRoxieServerThroughSpillActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8151. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  8152. {
  8153. numOriginalOutputs = numOutputs;
  8154. adaptors = new OutputAdaptor[numOutputs];
  8155. used = new bool[numOutputs];
  8156. for (unsigned i = 0; i < numOutputs; i++)
  8157. {
  8158. adaptors[i].parent = this;
  8159. adaptors[i].oid = i;
  8160. used[i] = false;
  8161. }
  8162. tailIdx = 0;
  8163. headIdx = 0;
  8164. activeOutputs = numOutputs;
  8165. }
  8166. ~CRoxieServerThroughSpillActivity()
  8167. {
  8168. delete [] adaptors;
  8169. delete [] used;
  8170. }
  8171. const void *readBuffered(unsigned &idx, unsigned oid)
  8172. {
  8173. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  8174. const unsigned curIdx = idx;
  8175. if (curIdx == headIdx) // test once without getting the crit2 sec
  8176. {
  8177. CriticalBlock b2(crit2); // but only one puller gets to read the head
  8178. if (curIdx == headIdx) // test again now that we have it
  8179. {
  8180. ActivityTimer t(activityStats, 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
  8181. if (readError)
  8182. throw readError.getLink(); // Read exceptions are only throw if you try to read past the row where they happened
  8183. try
  8184. {
  8185. const void *row = inputStream->nextRow();
  8186. if (activeOutputs==1)
  8187. {
  8188. #ifdef TRACE_SPLIT
  8189. CTXLOG("spill %d optimised return of %p", activityId, row);
  8190. #endif
  8191. headIdx++;
  8192. idx++;
  8193. return row; // optimization for the case where only one output still active.
  8194. }
  8195. CriticalBlock b(crit);
  8196. headIdx++;
  8197. idx++;
  8198. if (activeOutputs==1)
  8199. return row; // optimization for the case where only one output still active.
  8200. buffer.enqueue(row);
  8201. if (row) LinkRoxieRow(row);
  8202. return row;
  8203. }
  8204. catch (IException *E)
  8205. {
  8206. #ifdef TRACE_SPLIT
  8207. CTXLOG("spill %d caught exception", activityId);
  8208. #endif
  8209. readError.set(E);
  8210. throw;
  8211. }
  8212. catch (...)
  8213. {
  8214. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  8215. readError.set(E);
  8216. throw E;
  8217. }
  8218. }
  8219. }
  8220. CriticalBlock b(crit);
  8221. ActivityTimer t(activityStats, 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
  8222. unsigned lidx = curIdx - tailIdx;
  8223. idx++;
  8224. if (!lidx)
  8225. {
  8226. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  8227. // 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
  8228. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  8229. {
  8230. tailIdx++;
  8231. const void *ret = buffer.dequeue(); // no need to link - last puller
  8232. #ifdef TRACE_SPLIT
  8233. CTXLOG("last puller return of %p", ret);
  8234. #endif
  8235. return ret;
  8236. }
  8237. }
  8238. const void *ret = buffer.item(lidx);
  8239. if (ret) LinkRoxieRow(ret);
  8240. #ifdef TRACE_SPLIT
  8241. CTXLOG("standard return of %p", ret);
  8242. #endif
  8243. return ret;
  8244. }
  8245. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8246. {
  8247. CriticalBlock b(crit);
  8248. if (startError)
  8249. throw startError.getLink();
  8250. if (collectFactoryStatistics)
  8251. factory->noteStarted(oid);
  8252. if (traceStartStop)
  8253. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8254. if (state != STATEstarted)
  8255. {
  8256. if (state != STATEstarting)
  8257. initOutputs();
  8258. tailIdx = 0;
  8259. headIdx = 0;
  8260. startError.clear();
  8261. readError.clear();
  8262. try
  8263. {
  8264. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8265. }
  8266. catch (IException *E)
  8267. {
  8268. #ifdef TRACE_SPLIT
  8269. CTXLOG("spill %d caught exception in start", activityId);
  8270. #endif
  8271. startError.set(E);
  8272. throw;
  8273. }
  8274. catch (...)
  8275. {
  8276. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8277. startError.set(E);
  8278. throw E;
  8279. }
  8280. }
  8281. }
  8282. void stop(unsigned oid, unsigned & idx)
  8283. {
  8284. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8285. CriticalBlock b(crit);
  8286. #ifdef TRACE_STARTSTOP
  8287. if (traceStartStop)
  8288. {
  8289. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8290. if (watchActivityId && watchActivityId==activityId)
  8291. {
  8292. CTXLOG("WATCH: stop %d", activityId);
  8293. }
  8294. }
  8295. #endif
  8296. if (state != STATEstarting && state != STATEstarted)
  8297. initOutputs();
  8298. if (activeOutputs > 1)
  8299. {
  8300. if (tailIdx==idx)
  8301. {
  8302. // Discard all buffered rows that are there purely for this adaptor to read them
  8303. unsigned min = minIndex(oid);
  8304. if (min != (unsigned) -1)
  8305. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8306. // Should never happen though if there are still some active.
  8307. // there may be a small window where adaptors are blocked on the semaphore...
  8308. {
  8309. #ifdef TRACE_SPLIT
  8310. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8311. #endif
  8312. while (tailIdx < min)
  8313. {
  8314. ReleaseRoxieRow(buffer.dequeue());
  8315. tailIdx++;
  8316. }
  8317. }
  8318. }
  8319. activeOutputs--;
  8320. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8321. return;
  8322. }
  8323. #ifdef TRACE_SPLIT
  8324. CTXLOG("%p: All outputs done", this);
  8325. #endif
  8326. activeOutputs = numOutputs;
  8327. CRoxieServerActivity::stop();
  8328. };
  8329. void reset(unsigned oid)
  8330. {
  8331. if (traceStartStop)
  8332. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8333. activeOutputs = numOutputs;
  8334. while (buffer.ordinality())
  8335. ReleaseRoxieRow(buffer.dequeue());
  8336. startError.clear();
  8337. readError.clear();
  8338. if (state != STATEreset) // make sure input is only reset once
  8339. CRoxieServerActivity::reset();
  8340. };
  8341. void connectInputStreams(bool consumerOrdered)
  8342. {
  8343. if (!inputStream)
  8344. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8345. }
  8346. virtual const void *nextRow()
  8347. {
  8348. throwUnexpected(); // Internal logic error - we are not anybody's input
  8349. }
  8350. virtual IOutputMetaData * queryOutputMeta() const
  8351. {
  8352. // if (outputMeta)
  8353. // return outputMeta;
  8354. // else
  8355. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8356. }
  8357. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8358. {
  8359. assertex(idx < numOriginalOutputs);
  8360. assertex(!used[idx]);
  8361. used[idx] = true;
  8362. return &adaptors[idx];
  8363. }
  8364. virtual void resetOutputsUsed()
  8365. {
  8366. numOutputs = 1;
  8367. activeOutputs = 1;
  8368. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8369. }
  8370. virtual void noteOutputUsed()
  8371. {
  8372. assertex(numOutputs < numOriginalOutputs);
  8373. numOutputs++;
  8374. activeOutputs = numOutputs;
  8375. }
  8376. virtual bool isPassThrough()
  8377. {
  8378. return numOutputs==1;
  8379. }
  8380. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  8381. {
  8382. for (unsigned i = 0; i < numOutputs; i++)
  8383. addEdgeStats(statsBuilder, i, adaptors[i].numStarts, adaptors[i].processed, 0);
  8384. }
  8385. };
  8386. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8387. {
  8388. public:
  8389. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8390. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8391. {
  8392. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8393. setNumOutputs(helper->getTempUsageCount() + 1);
  8394. }
  8395. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8396. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8397. {
  8398. setNumOutputs(_numOutputs);
  8399. }
  8400. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8401. {
  8402. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8403. }
  8404. };
  8405. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8406. {
  8407. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8408. }
  8409. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8410. {
  8411. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8412. }
  8413. //----------------------------------------------------------------------------------------------
  8414. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8415. {
  8416. public:
  8417. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8418. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8419. {
  8420. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8421. setNumOutputs(helper->numBranches());
  8422. }
  8423. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8424. {
  8425. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8426. }
  8427. };
  8428. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8429. {
  8430. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8431. }
  8432. //=====================================================================================================
  8433. #define PIPE_BUFSIZE 0x8000
  8434. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8435. {
  8436. StringBuffer msg;
  8437. if(pipe->hasError())
  8438. {
  8439. try
  8440. {
  8441. char error[512];
  8442. size32_t sz = pipe->readError(sizeof(error), error);
  8443. if(sz && sz!=(size32_t)-1)
  8444. msg.append(", stderr: '").append(sz, error).append("'");
  8445. }
  8446. catch (IException *e)
  8447. {
  8448. EXCLOG(e, "Error reading pipe stderr");
  8449. e->Release();
  8450. }
  8451. }
  8452. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8453. }
  8454. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8455. {
  8456. IHThorPipeReadArg &helper;
  8457. Owned<IPipeProcess> pipe;
  8458. StringAttr pipeCommand;
  8459. Owned<IOutputRowDeserializer> rowDeserializer;
  8460. Owned<IReadRowStream> readTransformer;
  8461. bool groupSignalled;
  8462. public:
  8463. CRoxieServerPipeReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8464. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8465. {
  8466. groupSignalled = true;
  8467. }
  8468. virtual bool needsAllocator() const { return true; }
  8469. virtual void onCreate(IHThorArg *_colocalParent)
  8470. {
  8471. CRoxieServerActivity::onCreate(_colocalParent);
  8472. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8473. }
  8474. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8475. {
  8476. groupSignalled = true; // i.e. don't start with a NULL row
  8477. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8478. if (!readTransformer)
  8479. {
  8480. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8481. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8482. }
  8483. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8484. openPipe(pipeProgram);
  8485. }
  8486. virtual void stop()
  8487. {
  8488. CRoxieServerActivity::stop();
  8489. pipe.clear();
  8490. readTransformer->setStream(NULL);
  8491. }
  8492. virtual const void *nextRow()
  8493. {
  8494. ActivityTimer t(activityStats, timeActivities);
  8495. while (!waitForPipe())
  8496. {
  8497. if (!pipe)
  8498. return NULL;
  8499. if (helper.getPipeFlags() & TPFgroupeachrow)
  8500. {
  8501. if (!groupSignalled)
  8502. {
  8503. groupSignalled = true;
  8504. return NULL;
  8505. }
  8506. }
  8507. }
  8508. const void *ret = readTransformer->next();
  8509. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8510. processed++;
  8511. groupSignalled = false;
  8512. return ret;
  8513. }
  8514. protected:
  8515. bool waitForPipe()
  8516. {
  8517. if (!pipe)
  8518. return false; // done
  8519. if (!readTransformer->eos())
  8520. return true;
  8521. verifyPipe();
  8522. return false;
  8523. }
  8524. void openPipe(char const * cmd)
  8525. {
  8526. pipeCommand.setown(cmd);
  8527. pipe.setown(createPipeProcess());
  8528. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8529. {
  8530. // NB: pipe->run can't rely on the child process failing fast enough to return false here, failure picked up later with stderr context.
  8531. WARNLOG(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8532. }
  8533. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8534. readTransformer->setStream(pipeReader.get());
  8535. }
  8536. void verifyPipe()
  8537. {
  8538. if (pipe)
  8539. {
  8540. unsigned err = pipe->wait();
  8541. if(err && !(helper.getPipeFlags() & TPFnofail))
  8542. {
  8543. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8544. }
  8545. pipe.clear();
  8546. }
  8547. }
  8548. };
  8549. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8550. {
  8551. IHThorPipeThroughArg &helper;
  8552. RecordPullerThread puller;
  8553. Owned<IPipeProcess> pipe;
  8554. StringAttr pipeCommand;
  8555. InterruptableSemaphore pipeVerified;
  8556. InterruptableSemaphore pipeOpened;
  8557. CachedOutputMetaData inputMeta;
  8558. Owned<IOutputRowSerializer> rowSerializer;
  8559. Owned<IOutputRowDeserializer> rowDeserializer;
  8560. Owned<IPipeWriteXformHelper> writeTransformer;
  8561. Owned<IReadRowStream> readTransformer;
  8562. bool firstRead;
  8563. bool recreate;
  8564. bool inputExhausted;
  8565. bool groupSignalled;
  8566. public:
  8567. CRoxieServerPipeThroughActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8568. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8569. {
  8570. recreate = helper.recreateEachRow();
  8571. groupSignalled = true;
  8572. firstRead = false;
  8573. inputExhausted = false;
  8574. }
  8575. virtual bool needsAllocator() const { return true; }
  8576. virtual void onCreate(IHThorArg *_colocalParent)
  8577. {
  8578. CRoxieServerActivity::onCreate(_colocalParent);
  8579. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8580. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8581. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8582. }
  8583. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8584. {
  8585. firstRead = true;
  8586. inputExhausted = false;
  8587. groupSignalled = true; // i.e. don't start with a NULL row
  8588. pipeVerified.reinit();
  8589. pipeOpened.reinit();
  8590. writeTransformer->ready();
  8591. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8592. if (!readTransformer)
  8593. {
  8594. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8595. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8596. }
  8597. if(!recreate)
  8598. {
  8599. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8600. openPipe(pipeProgram);
  8601. }
  8602. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8603. }
  8604. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8605. {
  8606. if (idx)
  8607. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8608. puller.setInput(this, _sourceIdx, _in);
  8609. inputMeta.set(_in->queryOutputMeta());
  8610. }
  8611. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8612. {
  8613. puller.connectInputStreams(ctx, consumerOrdered);
  8614. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8615. }
  8616. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8617. {
  8618. if (idx==0)
  8619. return puller.queryInput();
  8620. else
  8621. return NULL;
  8622. }
  8623. virtual void stop()
  8624. {
  8625. pipeVerified.interrupt(NULL);
  8626. pipeOpened.interrupt(NULL);
  8627. puller.stop();
  8628. CRoxieServerActivity::stop();
  8629. pipe.clear();
  8630. if (readTransformer)
  8631. readTransformer->setStream(NULL);
  8632. }
  8633. virtual void reset()
  8634. {
  8635. puller.reset();
  8636. CRoxieServerActivity::reset();
  8637. }
  8638. virtual const void *nextRow()
  8639. {
  8640. ActivityTimer t(activityStats, timeActivities);
  8641. while (!waitForPipe())
  8642. {
  8643. if (!pipe)
  8644. return NULL;
  8645. if (helper.getPipeFlags() & TPFgroupeachrow)
  8646. {
  8647. if (!groupSignalled)
  8648. {
  8649. groupSignalled = true;
  8650. return NULL;
  8651. }
  8652. }
  8653. }
  8654. const void *ret = readTransformer->next();
  8655. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8656. processed++;
  8657. groupSignalled = false;
  8658. return ret;
  8659. }
  8660. virtual void processRow(const void *row)
  8661. {
  8662. // called from puller thread
  8663. if(recreate)
  8664. openPipe(helper.getNameFromRow(row));
  8665. writeTransformer->writeTranslatedText(row, pipe);
  8666. ReleaseRoxieRow(row);
  8667. if(recreate)
  8668. {
  8669. closePipe();
  8670. pipeVerified.wait();
  8671. }
  8672. }
  8673. virtual void processDone()
  8674. {
  8675. // called from puller thread
  8676. if(recreate)
  8677. {
  8678. inputExhausted = true;
  8679. pipeOpened.signal();
  8680. }
  8681. else
  8682. {
  8683. closePipe();
  8684. pipeVerified.wait();
  8685. }
  8686. }
  8687. virtual void processEOG()
  8688. {
  8689. }
  8690. void processGroup(const ConstPointerArray &)
  8691. {
  8692. throwUnexpected();
  8693. }
  8694. virtual bool fireException(IException *e)
  8695. {
  8696. pipeOpened.interrupt(LINK(e));
  8697. pipeVerified.interrupt(e);
  8698. return true;
  8699. }
  8700. private:
  8701. bool waitForPipe()
  8702. {
  8703. Owned<IException> pipeException;
  8704. try
  8705. {
  8706. if (firstRead)
  8707. {
  8708. pipeOpened.wait();
  8709. firstRead = false;
  8710. }
  8711. if (!pipe)
  8712. return false; // done
  8713. if (!readTransformer->eos())
  8714. return true;
  8715. }
  8716. catch (IException *e)
  8717. {
  8718. // NB: the original exception is probably a IPipeProcessException, but because InterruptableSemaphore rethrows it, we must catch it as an IException
  8719. pipeException.setown(e);
  8720. }
  8721. verifyPipe();
  8722. if (pipeException) // NB: verifyPipe may throw error based on pipe prog. output 1st.
  8723. throw pipeException.getClear();
  8724. if (recreate && !inputExhausted)
  8725. pipeOpened.wait();
  8726. return false;
  8727. }
  8728. void openPipe(char const * cmd)
  8729. {
  8730. pipeCommand.setown(cmd);
  8731. pipe.setown(createPipeProcess());
  8732. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8733. {
  8734. // NB: pipe->run can't rely on the child process failing fast enough to return false here, failure picked up later with stderr context.
  8735. WARNLOG(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8736. }
  8737. writeTransformer->writeHeader(pipe);
  8738. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8739. readTransformer->setStream(pipeReader.get());
  8740. pipeOpened.signal();
  8741. }
  8742. void closePipe()
  8743. {
  8744. writeTransformer->writeFooter(pipe);
  8745. pipe->closeInput();
  8746. }
  8747. void verifyPipe()
  8748. {
  8749. if (pipe)
  8750. {
  8751. unsigned err = pipe->wait();
  8752. if(err && !(helper.getPipeFlags() & TPFnofail))
  8753. {
  8754. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8755. }
  8756. pipe.clear();
  8757. pipeVerified.signal();
  8758. }
  8759. }
  8760. };
  8761. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8762. {
  8763. IHThorPipeWriteArg &helper;
  8764. Owned<IPipeProcess> pipe;
  8765. StringAttr pipeCommand;
  8766. CachedOutputMetaData inputMeta;
  8767. Owned<IOutputRowSerializer> rowSerializer;
  8768. Owned<IPipeWriteXformHelper> writeTransformer;
  8769. bool firstRead;
  8770. bool recreate;
  8771. bool inputExhausted;
  8772. public:
  8773. CRoxieServerPipeWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8774. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8775. {
  8776. recreate = helper.recreateEachRow();
  8777. firstRead = false;
  8778. inputExhausted = false;
  8779. }
  8780. virtual bool needsAllocator() const { return true; }
  8781. virtual void onCreate(IHThorArg *_colocalParent)
  8782. {
  8783. CRoxieServerActivity::onCreate(_colocalParent);
  8784. inputMeta.set(input->queryOutputMeta());
  8785. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8786. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8787. }
  8788. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8789. {
  8790. firstRead = true;
  8791. inputExhausted = false;
  8792. writeTransformer->ready();
  8793. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8794. if(!recreate)
  8795. {
  8796. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8797. openPipe(pipeProgram);
  8798. }
  8799. }
  8800. virtual void stop()
  8801. {
  8802. if (!aborted && helper.getSequence() >= 0)
  8803. {
  8804. WorkunitUpdate wu = ctx->updateWorkUnit();
  8805. if (wu)
  8806. {
  8807. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8808. if (result)
  8809. {
  8810. result->setResultTotalRowCount(processed);
  8811. result->setResultStatus(ResultStatusCalculated);
  8812. }
  8813. }
  8814. }
  8815. CRoxieServerActivity::stop();
  8816. pipe.clear();
  8817. }
  8818. virtual void onExecute()
  8819. {
  8820. Owned<IException> pipeException;
  8821. try
  8822. {
  8823. for (;;)
  8824. {
  8825. OwnedConstRoxieRow row(inputStream->ungroupedNextRow());
  8826. if (!row)
  8827. break;
  8828. processed++;
  8829. if(recreate)
  8830. openPipe(helper.getNameFromRow(row));
  8831. writeTransformer->writeTranslatedText(row, pipe);
  8832. if (recreate)
  8833. {
  8834. closePipe();
  8835. verifyPipe();
  8836. }
  8837. }
  8838. if (!recreate)
  8839. closePipe();
  8840. }
  8841. catch (IException *e)
  8842. {
  8843. pipeException.setown(e);
  8844. }
  8845. verifyPipe();
  8846. if (pipeException) // NB: verifyPipe may throw error based on pipe prog. output 1st.
  8847. throw pipeException.getClear();
  8848. }
  8849. private:
  8850. void openPipe(char const * cmd)
  8851. {
  8852. pipeCommand.setown(cmd);
  8853. pipe.setown(createPipeProcess());
  8854. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8855. {
  8856. // NB: pipe->run can't rely on the child process failing fast enough to return false here, failure picked up later with stderr context.
  8857. WARNLOG(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8858. }
  8859. writeTransformer->writeHeader(pipe);
  8860. }
  8861. void closePipe()
  8862. {
  8863. writeTransformer->writeFooter(pipe);
  8864. pipe->closeInput();
  8865. }
  8866. void verifyPipe()
  8867. {
  8868. if (pipe)
  8869. {
  8870. unsigned err = pipe->wait();
  8871. if(err && !(helper.getPipeFlags() & TPFnofail))
  8872. {
  8873. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8874. }
  8875. pipe.clear();
  8876. }
  8877. }
  8878. };
  8879. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8880. {
  8881. public:
  8882. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8883. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8884. {
  8885. }
  8886. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8887. {
  8888. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8889. }
  8890. };
  8891. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8892. {
  8893. public:
  8894. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8895. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8896. {
  8897. }
  8898. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8899. {
  8900. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8901. }
  8902. };
  8903. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8904. {
  8905. public:
  8906. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8907. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8908. {
  8909. }
  8910. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8911. {
  8912. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8913. }
  8914. };
  8915. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8916. {
  8917. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8918. }
  8919. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8920. {
  8921. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8922. }
  8923. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8924. {
  8925. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8926. }
  8927. //=====================================================================================================
  8928. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8929. {
  8930. IHThorStreamedIteratorArg &helper;
  8931. Owned<IRowStream> rows;
  8932. public:
  8933. CRoxieServerStreamedIteratorActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8934. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8935. {
  8936. }
  8937. ~CRoxieServerStreamedIteratorActivity()
  8938. {
  8939. }
  8940. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8941. {
  8942. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8943. rows.setown(helper.createInput());
  8944. }
  8945. virtual void stop()
  8946. {
  8947. if (rows)
  8948. {
  8949. rows->stop();
  8950. rows.clear();
  8951. }
  8952. CRoxieServerActivity::stop();
  8953. }
  8954. virtual const void *nextRow()
  8955. {
  8956. ActivityTimer t(activityStats, timeActivities);
  8957. assertex(rows != NULL);
  8958. const void * next = rows->nextRow();
  8959. if (next)
  8960. processed++;
  8961. return next;
  8962. }
  8963. };
  8964. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8965. {
  8966. public:
  8967. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8968. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8969. {
  8970. }
  8971. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  8972. {
  8973. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8974. }
  8975. };
  8976. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8977. {
  8978. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8979. }
  8980. //=====================================================================================================
  8981. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8982. {
  8983. IHThorFilterArg &helper;
  8984. bool anyThisGroup;
  8985. IRangeCompare * stepCompare;
  8986. public:
  8987. CRoxieServerFilterActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8988. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8989. {
  8990. anyThisGroup = false;
  8991. stepCompare = NULL;
  8992. }
  8993. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8994. {
  8995. anyThisGroup = false;
  8996. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8997. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8998. stepCompare = NULL;
  8999. if (!eof)
  9000. {
  9001. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  9002. if (stepMeta)
  9003. stepCompare = stepMeta->queryCompare();
  9004. }
  9005. }
  9006. virtual const void * nextRow()
  9007. {
  9008. ActivityTimer t(activityStats, timeActivities);
  9009. if (eof)
  9010. return NULL;
  9011. for (;;)
  9012. {
  9013. OwnedConstRoxieRow ret(inputStream->nextRow());
  9014. if (!ret)
  9015. {
  9016. //stop returning two NULLs in a row.
  9017. if (anyThisGroup)
  9018. {
  9019. anyThisGroup = false;
  9020. return NULL;
  9021. }
  9022. ret.setown(inputStream->nextRow());
  9023. if (!ret)
  9024. {
  9025. eof = true;
  9026. return NULL; // eof...
  9027. }
  9028. }
  9029. if (helper.isValid(ret))
  9030. {
  9031. anyThisGroup = true;
  9032. processed++;
  9033. return ret.getClear();
  9034. }
  9035. }
  9036. }
  9037. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9038. {
  9039. //Could assert that this isn't grouped
  9040. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  9041. ActivityTimer t(activityStats, timeActivities);
  9042. if (eof)
  9043. return NULL;
  9044. for (;;)
  9045. {
  9046. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  9047. if (!ret)
  9048. {
  9049. eof = true;
  9050. return NULL;
  9051. }
  9052. if (!wasCompleteMatch)
  9053. {
  9054. anyThisGroup = false; // RKC->GH - is this right??
  9055. return ret.getClear();
  9056. }
  9057. if (helper.isValid(ret))
  9058. {
  9059. anyThisGroup = true;
  9060. processed++;
  9061. return ret.getClear();
  9062. }
  9063. if (!stepExtra.returnMismatches())
  9064. {
  9065. ret.clear();
  9066. return nextRow();
  9067. }
  9068. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  9069. //condition to advance
  9070. if (stepCompare->docompare(ret, seek, numFields) != 0)
  9071. {
  9072. wasCompleteMatch = false;
  9073. anyThisGroup = false; // WHY?
  9074. return ret.getClear();
  9075. }
  9076. }
  9077. }
  9078. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9079. {
  9080. return input->gatherConjunctions(collector);
  9081. }
  9082. virtual void resetEOF()
  9083. {
  9084. eof = prefiltered;
  9085. anyThisGroup = false;
  9086. inputStream->resetEOF();
  9087. }
  9088. IInputSteppingMeta * querySteppingMeta()
  9089. {
  9090. return input->querySteppingMeta();
  9091. }
  9092. };
  9093. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  9094. {
  9095. public:
  9096. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9097. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9098. {
  9099. optStableInput = false;
  9100. }
  9101. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9102. {
  9103. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  9104. }
  9105. };
  9106. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9107. {
  9108. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9109. }
  9110. //=====================================================================================================
  9111. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  9112. {
  9113. IHThorFilterGroupArg &helper;
  9114. unsigned curIndex;
  9115. ConstPointerArray gathered;
  9116. IRangeCompare * stepCompare;
  9117. public:
  9118. CRoxieServerFilterGroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9119. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  9120. {
  9121. curIndex = 0;
  9122. stepCompare = NULL;
  9123. }
  9124. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9125. {
  9126. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  9127. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  9128. assertex(eof == !helper.canMatchAny());
  9129. curIndex = 0;
  9130. stepCompare = NULL;
  9131. if (!eof)
  9132. {
  9133. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  9134. if (inputStepping)
  9135. stepCompare = inputStepping->queryCompare();
  9136. }
  9137. }
  9138. virtual void reset()
  9139. {
  9140. releaseGathered();
  9141. CRoxieServerLateStartActivity::reset();
  9142. }
  9143. inline void releaseGathered()
  9144. {
  9145. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9146. gathered.kill();
  9147. curIndex = 0;
  9148. }
  9149. virtual const void * nextRow()
  9150. {
  9151. ActivityTimer t(activityStats, timeActivities);
  9152. for (;;)
  9153. {
  9154. if (eof)
  9155. return NULL;
  9156. if (gathered.ordinality())
  9157. {
  9158. if (gathered.isItem(curIndex))
  9159. {
  9160. const void * ret = gathered.item(curIndex++);
  9161. processed++;
  9162. return ret;
  9163. }
  9164. curIndex = 0;
  9165. gathered.kill();
  9166. return NULL;
  9167. }
  9168. const void * ret = inputStream->nextRow();
  9169. while (ret)
  9170. {
  9171. gathered.append(ret);
  9172. ret = inputStream->nextRow();
  9173. }
  9174. unsigned num = gathered.ordinality();
  9175. if (num != 0)
  9176. {
  9177. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9178. ReleaseRoxieRows(gathered); // read next group
  9179. }
  9180. else
  9181. eof = true;
  9182. }
  9183. }
  9184. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9185. {
  9186. ActivityTimer t(activityStats, timeActivities);
  9187. if (eof)
  9188. return NULL;
  9189. if (gathered.ordinality())
  9190. {
  9191. while (gathered.isItem(curIndex))
  9192. {
  9193. const void * ret = gathered.item(curIndex++);
  9194. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  9195. {
  9196. processed++;
  9197. return ret;
  9198. }
  9199. ReleaseRoxieRow(ret);
  9200. }
  9201. curIndex = 0;
  9202. gathered.kill();
  9203. //nextRowGE never returns an end of group marker.
  9204. }
  9205. //Not completely sure about this - it could lead the the start of a group being skipped,
  9206. //so the group filter could potentially work on a different group. If so, we'd need to check the
  9207. //next fields were a subset of the grouping fields - more an issue for the group activity.
  9208. //MORE: What do we do with wasCompleteMatch? something like the following????
  9209. #if 0
  9210. for (;;)
  9211. {
  9212. const void * ret;
  9213. if (stepExtra.returnMismatches())
  9214. {
  9215. bool matchedCompletely = true;
  9216. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9217. if (!wasCompleteMatch)
  9218. return ret;
  9219. }
  9220. else
  9221. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9222. #endif
  9223. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9224. while (ret)
  9225. {
  9226. gathered.append(ret);
  9227. ret = inputStream->nextRow();
  9228. }
  9229. unsigned num = gathered.ordinality();
  9230. if (num != 0)
  9231. {
  9232. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9233. ReleaseRoxieRows(gathered); // read next group
  9234. }
  9235. else
  9236. eof = true;
  9237. return IEngineRowStream::ungroupedNextRow();
  9238. }
  9239. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9240. {
  9241. return input->gatherConjunctions(collector);
  9242. }
  9243. virtual void resetEOF()
  9244. {
  9245. eof = false;
  9246. releaseGathered();
  9247. inputStream->resetEOF();
  9248. }
  9249. IInputSteppingMeta * querySteppingMeta()
  9250. {
  9251. return input->querySteppingMeta();
  9252. }
  9253. };
  9254. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  9255. {
  9256. public:
  9257. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9258. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9259. {
  9260. }
  9261. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9262. {
  9263. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  9264. }
  9265. };
  9266. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9267. {
  9268. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9269. }
  9270. //=================================================================================
  9271. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  9272. {
  9273. IHThorSideEffectArg &helper;
  9274. CriticalSection ecrit;
  9275. Owned<IException> exception;
  9276. bool executed;
  9277. public:
  9278. CRoxieServerSideEffectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9279. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  9280. {
  9281. executed = false;
  9282. }
  9283. virtual const void * nextRow()
  9284. {
  9285. ActivityTimer t(activityStats, timeActivities);
  9286. CriticalBlock b(ecrit);
  9287. if (exception)
  9288. throw(exception.getLink());
  9289. if (!executed)
  9290. {
  9291. try
  9292. {
  9293. executed = true;
  9294. helper.action();
  9295. }
  9296. catch(IException *E)
  9297. {
  9298. exception.set(E);
  9299. throw;
  9300. }
  9301. }
  9302. return NULL;
  9303. }
  9304. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9305. {
  9306. CriticalBlock b(ecrit);
  9307. if (exception)
  9308. throw(exception.getLink());
  9309. if (!executed)
  9310. {
  9311. try
  9312. {
  9313. ActivityTimer t(activityStats, timeActivities);
  9314. executed = true;
  9315. start(parentExtractSize, parentExtract, false);
  9316. helper.action();
  9317. stop();
  9318. }
  9319. catch(IException *E)
  9320. {
  9321. ctx->notifyAbort(E);
  9322. abort();
  9323. exception.set(E);
  9324. throw;
  9325. }
  9326. }
  9327. }
  9328. virtual void reset()
  9329. {
  9330. executed = false;
  9331. exception.clear();
  9332. CRoxieServerActivity::reset();
  9333. }
  9334. };
  9335. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9336. {
  9337. bool isRoot;
  9338. public:
  9339. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9340. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9341. {
  9342. }
  9343. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9344. {
  9345. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9346. }
  9347. virtual bool isSink() const
  9348. {
  9349. return isRoot && !meta.queryOriginal();
  9350. }
  9351. };
  9352. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9353. {
  9354. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9355. }
  9356. //=================================================================================
  9357. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9358. {
  9359. IHThorActionArg &helper;
  9360. public:
  9361. CRoxieServerActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9362. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9363. {
  9364. }
  9365. virtual void onExecute()
  9366. {
  9367. helper.action();
  9368. }
  9369. };
  9370. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9371. {
  9372. public:
  9373. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9374. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9375. {
  9376. }
  9377. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9378. {
  9379. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9380. }
  9381. };
  9382. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9383. {
  9384. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9385. }
  9386. //=================================================================================
  9387. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9388. {
  9389. IHThorSampleArg &helper;
  9390. unsigned numSamples;
  9391. unsigned numToSkip;
  9392. unsigned whichSample;
  9393. bool anyThisGroup;
  9394. bool eof;
  9395. public:
  9396. CRoxieServerSampleActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9397. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9398. {
  9399. numSamples = 0;
  9400. numToSkip = 0;
  9401. whichSample = 0;
  9402. anyThisGroup = false;
  9403. eof = false;
  9404. }
  9405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9406. {
  9407. anyThisGroup = false;
  9408. eof = false;
  9409. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9410. numSamples = helper.getProportion();
  9411. whichSample = helper.getSampleNumber();
  9412. numToSkip = (whichSample ? whichSample-1 : 0);
  9413. }
  9414. virtual const void * nextRow()
  9415. {
  9416. ActivityTimer t(activityStats, timeActivities);
  9417. if (eof)
  9418. return NULL;
  9419. for (;;)
  9420. {
  9421. const void * ret = inputStream->nextRow();
  9422. if (!ret)
  9423. {
  9424. //this does work with groups - may or may not be useful...
  9425. //reset the sample for each group.... probably best.
  9426. numToSkip = (whichSample ? whichSample-1 : 0);
  9427. if (anyThisGroup)
  9428. {
  9429. anyThisGroup = false;
  9430. return NULL;
  9431. }
  9432. ret = inputStream->nextRow();
  9433. if (!ret)
  9434. {
  9435. eof = true;
  9436. return NULL; // eof...
  9437. }
  9438. }
  9439. if (numToSkip == 0)
  9440. {
  9441. anyThisGroup = true;
  9442. numToSkip = numSamples-1;
  9443. processed++;
  9444. return ret;
  9445. }
  9446. numToSkip--;
  9447. ReleaseRoxieRow(ret);
  9448. }
  9449. }
  9450. };
  9451. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9452. {
  9453. public:
  9454. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9455. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9456. {
  9457. }
  9458. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9459. {
  9460. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9461. }
  9462. };
  9463. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9464. {
  9465. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9466. }
  9467. //=================================================================================
  9468. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9469. {
  9470. IHThorChooseSetsArg &helper;
  9471. unsigned numSets;
  9472. unsigned * setCounts;
  9473. bool done;
  9474. public:
  9475. CRoxieServerChooseSetsActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9476. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9477. {
  9478. setCounts = NULL;
  9479. numSets = 0;
  9480. done = false;
  9481. }
  9482. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9483. {
  9484. done = false;
  9485. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9486. numSets = helper.getNumSets();
  9487. setCounts = new unsigned[numSets];
  9488. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9489. helper.setCounts(setCounts);
  9490. }
  9491. virtual void reset()
  9492. {
  9493. delete [] setCounts;
  9494. setCounts = NULL;
  9495. CRoxieServerActivity::reset();
  9496. }
  9497. virtual const void * nextRow()
  9498. {
  9499. ActivityTimer t(activityStats, timeActivities);
  9500. if (done)
  9501. return NULL;
  9502. for (;;)
  9503. {
  9504. const void * ret = inputStream->ungroupedNextRow();
  9505. if (!ret)
  9506. {
  9507. done = true;
  9508. return NULL;
  9509. }
  9510. processed++;
  9511. switch (helper.getRecordAction(ret))
  9512. {
  9513. case 2:
  9514. done = true;
  9515. return ret;
  9516. case 1:
  9517. return ret;
  9518. }
  9519. ReleaseRoxieRow(ret);
  9520. }
  9521. }
  9522. };
  9523. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9524. {
  9525. public:
  9526. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9527. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9528. {
  9529. }
  9530. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9531. {
  9532. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9533. }
  9534. };
  9535. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9536. {
  9537. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9538. }
  9539. //=================================================================================
  9540. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9541. {
  9542. protected:
  9543. IHThorChooseSetsExArg &helper;
  9544. unsigned numSets;
  9545. unsigned curIndex;
  9546. unsigned * setCounts;
  9547. count_t * limits;
  9548. bool done;
  9549. ConstPointerArray gathered;
  9550. virtual bool includeRow(const void * row) = 0;
  9551. virtual void calculateSelection() = 0;
  9552. public:
  9553. CRoxieServerChooseSetsExActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9554. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9555. {
  9556. setCounts = NULL;
  9557. limits = NULL;
  9558. done = false;
  9559. curIndex = 0;
  9560. numSets = 0;
  9561. }
  9562. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9563. {
  9564. done = false;
  9565. curIndex = 0;
  9566. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9567. numSets = helper.getNumSets();
  9568. setCounts = new unsigned[numSets];
  9569. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9570. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9571. helper.getLimits(limits);
  9572. }
  9573. virtual void reset()
  9574. {
  9575. delete [] setCounts;
  9576. setCounts = NULL;
  9577. free(limits);
  9578. limits = NULL;
  9579. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9580. gathered.kill();
  9581. curIndex = 0;
  9582. CRoxieServerActivity::reset();
  9583. }
  9584. virtual const void * nextRow()
  9585. {
  9586. ActivityTimer t(activityStats, timeActivities);
  9587. if (gathered.ordinality() == 0)
  9588. {
  9589. curIndex = 0;
  9590. if (!inputStream->nextGroup(gathered))
  9591. {
  9592. done = true;
  9593. return NULL;
  9594. }
  9595. ForEachItemIn(idx1, gathered)
  9596. {
  9597. unsigned category = helper.getCategory(gathered.item(idx1));
  9598. if (category)
  9599. setCounts[category-1]++;
  9600. }
  9601. calculateSelection();
  9602. }
  9603. while (gathered.isItem(curIndex))
  9604. {
  9605. const void * row = gathered.item(curIndex);
  9606. gathered.replace(NULL, curIndex);
  9607. curIndex++;
  9608. if (includeRow(row))
  9609. {
  9610. processed++;
  9611. return row;
  9612. }
  9613. ReleaseRoxieRow(row);
  9614. }
  9615. gathered.kill();
  9616. return NULL;
  9617. }
  9618. };
  9619. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9620. {
  9621. unsigned * numToSkip;
  9622. public:
  9623. CRoxieServerChooseSetsLastActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9624. {
  9625. numToSkip = NULL;
  9626. }
  9627. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9628. {
  9629. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9630. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9631. }
  9632. virtual void reset()
  9633. {
  9634. free(numToSkip);
  9635. numToSkip = NULL;
  9636. CRoxieServerChooseSetsExActivity::reset();
  9637. }
  9638. protected:
  9639. virtual void calculateSelection()
  9640. {
  9641. for (unsigned idx=0; idx < numSets; idx++)
  9642. {
  9643. if (setCounts[idx] < limits[idx])
  9644. numToSkip[idx] = 0;
  9645. else
  9646. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9647. }
  9648. }
  9649. virtual bool includeRow(const void * row)
  9650. {
  9651. unsigned category = helper.getCategory(row);
  9652. if (category)
  9653. {
  9654. if (numToSkip[category-1] == 0)
  9655. return true;
  9656. numToSkip[category-1]--;
  9657. }
  9658. return false;
  9659. }
  9660. };
  9661. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9662. {
  9663. count_t * counter;
  9664. public:
  9665. CRoxieServerChooseSetsEnthActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9666. {
  9667. counter = NULL;
  9668. }
  9669. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9670. {
  9671. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9672. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9673. }
  9674. virtual void reset()
  9675. {
  9676. free(counter);
  9677. counter = NULL;
  9678. CRoxieServerChooseSetsExActivity::reset();
  9679. }
  9680. protected:
  9681. virtual void calculateSelection()
  9682. {
  9683. }
  9684. virtual bool includeRow(const void * row)
  9685. {
  9686. unsigned category = helper.getCategory(row);
  9687. if (category)
  9688. {
  9689. assertex(category <= numSets);
  9690. counter[category-1] += limits[category-1];
  9691. if(counter[category-1] >= setCounts[category-1])
  9692. {
  9693. counter[category-1] -= setCounts[category-1];
  9694. return true;
  9695. }
  9696. }
  9697. return false;
  9698. }
  9699. };
  9700. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9701. {
  9702. public:
  9703. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9704. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9705. {
  9706. }
  9707. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9708. {
  9709. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9710. }
  9711. };
  9712. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9713. {
  9714. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9715. }
  9716. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9717. {
  9718. public:
  9719. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9720. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9721. {
  9722. }
  9723. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9724. {
  9725. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9726. }
  9727. };
  9728. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9729. {
  9730. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9731. }
  9732. //=================================================================================
  9733. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9734. {
  9735. IHThorEnthArg &helper;
  9736. unsigned __int64 numerator;
  9737. unsigned __int64 denominator;
  9738. unsigned __int64 counter;
  9739. bool eof;
  9740. public:
  9741. CRoxieServerEnthActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9742. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9743. {
  9744. eof = false;
  9745. numerator = denominator = counter = 0;
  9746. }
  9747. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9748. {
  9749. eof = false;
  9750. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9751. numerator = helper.getProportionNumerator();
  9752. denominator = helper.getProportionDenominator();
  9753. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9754. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9755. if (counter >= denominator)
  9756. counter %= denominator;
  9757. }
  9758. inline bool wanted()
  9759. {
  9760. counter += numerator;
  9761. if(counter >= denominator)
  9762. {
  9763. counter -= denominator;
  9764. return true;
  9765. }
  9766. return false;
  9767. }
  9768. virtual const void * nextRow()
  9769. {
  9770. ActivityTimer t(activityStats, timeActivities);
  9771. if (eof)
  9772. return NULL;
  9773. const void * ret;
  9774. for (;;)
  9775. {
  9776. ret = inputStream->ungroupedNextRow();
  9777. if (!ret) //eof
  9778. {
  9779. eof = true;
  9780. return ret;
  9781. }
  9782. if (wanted())
  9783. return ret;
  9784. ReleaseRoxieRow(ret);
  9785. }
  9786. }
  9787. };
  9788. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9789. {
  9790. public:
  9791. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9792. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9793. {
  9794. }
  9795. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  9796. {
  9797. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9798. }
  9799. };
  9800. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9801. {
  9802. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9803. }
  9804. //=================================================================================
  9805. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9806. {
  9807. IHThorAggregateArg &helper;
  9808. bool eof;
  9809. bool isInputGrouped;
  9810. bool abortEarly;
  9811. public:
  9812. CRoxieServerAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9813. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9814. {
  9815. eof = false;
  9816. isInputGrouped = false;
  9817. abortEarly = false;
  9818. }
  9819. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9820. {
  9821. eof = false;
  9822. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9823. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9824. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9825. }
  9826. virtual bool needsAllocator() const { return true; }
  9827. virtual const void * nextRow()
  9828. {
  9829. ActivityTimer t(activityStats, timeActivities);
  9830. if (eof)
  9831. return NULL;
  9832. const void * next = inputStream->nextRow();
  9833. if (!next && isInputGrouped)
  9834. {
  9835. eof = true;
  9836. return NULL;
  9837. }
  9838. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9839. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9840. if (next)
  9841. {
  9842. finalSize = helper.processFirst(rowBuilder, next);
  9843. ReleaseRoxieRow(next);
  9844. if (!abortEarly)
  9845. {
  9846. for (;;)
  9847. {
  9848. next = inputStream->nextRow();
  9849. if (!next)
  9850. break;
  9851. finalSize = helper.processNext(rowBuilder, next);
  9852. ReleaseRoxieRow(next);
  9853. }
  9854. }
  9855. }
  9856. if (!isInputGrouped) // either read all, or aborted early
  9857. eof = true;
  9858. processed++;
  9859. return rowBuilder.finalizeRowClear(finalSize);
  9860. }
  9861. };
  9862. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9863. {
  9864. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9865. {
  9866. protected:
  9867. IHThorAggregateArg &helper;
  9868. OwnedConstRoxieRow result;
  9869. bool eof = false;
  9870. bool isInputGrouped = false;
  9871. bool abortEarly = false;
  9872. public:
  9873. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9874. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9875. {
  9876. }
  9877. virtual const void * nextRow() override
  9878. {
  9879. ActivityTimer t(activityStats, timeActivities);
  9880. if (eof || isAborting())
  9881. return NULL;
  9882. const void * next = inputStream->nextRow();
  9883. if (!next && isInputGrouped)
  9884. {
  9885. eof = true;
  9886. return NULL;
  9887. }
  9888. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9889. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9890. if (next)
  9891. {
  9892. finalSize = helper.processFirst(rowBuilder, next);
  9893. ReleaseRoxieRow(next);
  9894. if (!abortEarly)
  9895. {
  9896. for (;;)
  9897. {
  9898. next = inputStream->nextRow();
  9899. if (!next)
  9900. break;
  9901. finalSize = helper.processNext(rowBuilder, next);
  9902. ReleaseRoxieRow(next);
  9903. if (isAborting())
  9904. break;
  9905. }
  9906. }
  9907. }
  9908. if (!isInputGrouped) // either read all, or aborted early
  9909. eof = true;
  9910. processed++;
  9911. return rowBuilder.finalizeRowClear(finalSize);
  9912. }
  9913. virtual void threadmain() override
  9914. {
  9915. isInputGrouped = true; // gather no row if there are no input rows.
  9916. result.setown(nextRow());
  9917. queryActivity().noteStrandFinished(inputStream);
  9918. }
  9919. virtual void reset() override
  9920. {
  9921. StrandProcessor::reset();
  9922. result.clear();
  9923. eof = false;
  9924. }
  9925. //interface IOutputOutputCallback
  9926. virtual bool noteEndOfInputChunk() { return true; }
  9927. virtual void noteEndOfInput() {}
  9928. virtual void stopStream()
  9929. {
  9930. inputStream->stop();
  9931. }
  9932. const void * queryResult() const { return result; }
  9933. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9934. };
  9935. //This class is only used when a single aggregate is being calculated.
  9936. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9937. {
  9938. public:
  9939. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9940. {
  9941. }
  9942. virtual const void *nextRow()
  9943. {
  9944. return parent.getCombinedAggregate();
  9945. }
  9946. virtual void stop()
  9947. {
  9948. parent.outputStopped();
  9949. }
  9950. virtual void resetEOF()
  9951. {
  9952. throwUnexpected();
  9953. }
  9954. protected:
  9955. CRoxieServerStrandedAggregateActivity & parent;
  9956. } combiner;
  9957. class NullCallback : implements IOrderedOutputCallback
  9958. {
  9959. public:
  9960. virtual bool noteEndOfInputChunk() { return true; }
  9961. virtual void noteEndOfInput() {}
  9962. } nullCallback;
  9963. public:
  9964. CRoxieServerStrandedAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9965. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), combiner(*this), helper((IHThorAggregateArg &)basehelper)
  9966. {
  9967. isInputGrouped = false;
  9968. abortEarly = false;
  9969. }
  9970. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9971. {
  9972. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9973. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9974. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9975. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9976. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9977. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9978. strandOptions.numStrands = 1;
  9979. else if (!isInputGrouped)
  9980. combineStreams = true;
  9981. }
  9982. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9983. {
  9984. PointerArrayOf<IEngineRowStream> localStreams;
  9985. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9986. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9987. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9988. if (localStreams.ordinality() == 1)
  9989. combineStreams = false; // Select a more efficient/simpler code path
  9990. if (combineStreams)
  9991. {
  9992. assertex(!outJunction); // this needs more thought!
  9993. streams.append(&combiner);
  9994. }
  9995. else
  9996. {
  9997. streams.swapWith(localStreams);
  9998. }
  9999. return outJunction.getClear();
  10000. }
  10001. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  10002. {
  10003. if (traceLevel > 4)
  10004. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  10005. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  10006. }
  10007. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  10008. virtual bool needsAllocator() const { return true; }
  10009. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  10010. {
  10011. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  10012. onStartStrands();
  10013. if (combineStreams)
  10014. {
  10015. barrier.setown(createStrandBarrier());
  10016. ForEachItemIn(i, strands)
  10017. barrier->startStrand(queryAggregate(i));
  10018. active.store(1);
  10019. }
  10020. else
  10021. active.store(0);
  10022. }
  10023. virtual void reset() override
  10024. {
  10025. CRoxieServerStrandedActivity::reset();
  10026. barrier.clear();
  10027. calculated = false;
  10028. }
  10029. //Helper functions for the single aggregate case
  10030. const void * getCombinedAggregate()
  10031. {
  10032. if (calculated)
  10033. return NULL;
  10034. calculated= true;
  10035. barrier->waitForStrands();
  10036. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10037. size32_t finalSize = helper.clearAggregate(rowBuilder);
  10038. bool isFirst = true;
  10039. for (unsigned i=0; i < numStrands(); i++)
  10040. {
  10041. const void * next = queryAggregate(i).queryResult();
  10042. if (next)
  10043. {
  10044. if (isFirst)
  10045. {
  10046. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  10047. isFirst = false;
  10048. }
  10049. else
  10050. finalSize = helper.mergeAggregate(rowBuilder, next);
  10051. }
  10052. }
  10053. return rowBuilder.finalizeRowClear(finalSize);
  10054. }
  10055. void outputStopped()
  10056. {
  10057. //only called if generating a single result.
  10058. assertex(combineStreams);
  10059. if (barrier)
  10060. {
  10061. requestAbort(); // if strands are still running, abort them
  10062. barrier->waitForStrands();
  10063. }
  10064. else
  10065. {
  10066. ForEachItemIn(i, strands)
  10067. queryAggregate(i).stopStream();
  10068. }
  10069. CRoxieServerStrandedActivity::stop();
  10070. }
  10071. void noteStrandFinished(IRowStream * stream)
  10072. {
  10073. barrier->noteStrandFinished(stream);
  10074. }
  10075. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  10076. {
  10077. //The non-ordered aggregate does not need to process the ordered call back information.
  10078. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  10079. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  10080. return &nullCallback;
  10081. }
  10082. inline AggregateProcessor & queryAggregate(unsigned i)
  10083. {
  10084. return static_cast<AggregateProcessor &>(strands.item(i));
  10085. }
  10086. protected:
  10087. IHThorAggregateArg &helper;
  10088. Owned<IStrandBarrier> barrier;
  10089. IEngineRowStream * combinedStream = nullptr;
  10090. bool isInputGrouped;
  10091. bool abortEarly;
  10092. bool combineStreams = false;
  10093. bool calculated = false;
  10094. };
  10095. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  10096. {
  10097. StrandOptions strandOptions;
  10098. public:
  10099. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10100. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  10101. {
  10102. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  10103. if (!(helper->getAggregateFlags() & TAForderedmerge))
  10104. optStableInput = false;
  10105. }
  10106. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  10107. {
  10108. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  10109. }
  10110. };
  10111. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10112. {
  10113. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10114. }
  10115. //=================================================================================
  10116. typedef unsigned t_hashPrefix;
  10117. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  10118. {
  10119. IHThorHashAggregateArg &helper;
  10120. RowAggregator aggregated;
  10121. bool eof;
  10122. bool gathered;
  10123. bool isGroupedAggregate;
  10124. public:
  10125. CRoxieServerHashAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  10126. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  10127. aggregated(helper, helper),
  10128. isGroupedAggregate(_isGroupedAggregate)
  10129. {
  10130. eof = false;
  10131. gathered = false;
  10132. }
  10133. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10134. {
  10135. eof = false;
  10136. gathered = false;
  10137. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10138. }
  10139. virtual void reset()
  10140. {
  10141. aggregated.reset();
  10142. CRoxieServerActivity::reset();
  10143. }
  10144. virtual bool needsAllocator() const { return true; }
  10145. virtual const void * nextRow()
  10146. {
  10147. ActivityTimer t(activityStats, timeActivities);
  10148. if (eof)
  10149. return NULL;
  10150. if (!gathered)
  10151. {
  10152. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  10153. bool eog = true;
  10154. for (;;)
  10155. {
  10156. const void * next = inputStream->nextRow();
  10157. if (!next)
  10158. {
  10159. if (isGroupedAggregate)
  10160. {
  10161. if (eog)
  10162. eof = true;
  10163. break;
  10164. }
  10165. next = inputStream->nextRow();
  10166. if (!next)
  10167. break;
  10168. }
  10169. eog = false;
  10170. aggregated.addRow(next);
  10171. ReleaseRoxieRow(next);
  10172. }
  10173. gathered = true;
  10174. }
  10175. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  10176. if (next)
  10177. {
  10178. processed++;
  10179. return next->finalizeRowClear();
  10180. }
  10181. if (!isGroupedAggregate)
  10182. eof = true;
  10183. aggregated.reset();
  10184. gathered = false;
  10185. return NULL;
  10186. }
  10187. };
  10188. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  10189. {
  10190. public:
  10191. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10192. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10193. {
  10194. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  10195. }
  10196. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  10197. {
  10198. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  10199. }
  10200. protected:
  10201. bool isGroupedAggregate;
  10202. };
  10203. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10204. {
  10205. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10206. }
  10207. //=================================================================================
  10208. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  10209. {
  10210. bool eof;
  10211. public:
  10212. CRoxieServerDegroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10213. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10214. {
  10215. eof = false;
  10216. }
  10217. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10218. {
  10219. eof = false;
  10220. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10221. }
  10222. virtual const void * nextRow()
  10223. {
  10224. ActivityTimer t(activityStats, timeActivities);
  10225. if (eof)
  10226. return NULL;
  10227. const void * ret = inputStream->ungroupedNextRow();
  10228. if (ret)
  10229. processed++;
  10230. else
  10231. eof = true;
  10232. return ret;
  10233. }
  10234. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  10235. {
  10236. ActivityTimer t(activityStats, timeActivities);
  10237. if (eof)
  10238. return NULL;
  10239. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  10240. if (ret)
  10241. processed++;
  10242. else
  10243. eof = true;
  10244. return ret;
  10245. }
  10246. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  10247. {
  10248. return input->gatherConjunctions(collector);
  10249. }
  10250. virtual void resetEOF()
  10251. {
  10252. eof = false;
  10253. inputStream->resetEOF();
  10254. }
  10255. IInputSteppingMeta * querySteppingMeta()
  10256. {
  10257. return input->querySteppingMeta();
  10258. }
  10259. };
  10260. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  10261. {
  10262. public:
  10263. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10264. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10265. {
  10266. }
  10267. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  10268. {
  10269. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  10270. }
  10271. };
  10272. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10273. {
  10274. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10275. }
  10276. //=================================================================================
  10277. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  10278. {
  10279. IHThorDiskReadArg &helper;
  10280. bool needTransform;
  10281. bool eof;
  10282. bool anyThisGroup;
  10283. unsigned __int64 rowLimit;
  10284. unsigned __int64 choosenLimit;
  10285. public:
  10286. CRoxieServerSpillReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10287. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  10288. {
  10289. needTransform = helper.needTransform();
  10290. rowLimit = (unsigned __int64) -1;
  10291. choosenLimit = 0;
  10292. eof = false;
  10293. anyThisGroup = false;
  10294. }
  10295. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10296. {
  10297. anyThisGroup = false;
  10298. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10299. if (helper.canMatchAny())
  10300. eof = false;
  10301. else
  10302. eof = true;
  10303. choosenLimit = helper.getChooseNLimit();
  10304. rowLimit = helper.getRowLimit();
  10305. helper.setCallback(NULL); // members should not be called - change if they are
  10306. }
  10307. virtual bool needsAllocator() const { return true; }
  10308. virtual const void * nextRow()
  10309. {
  10310. ActivityTimer t(activityStats, timeActivities);
  10311. if (eof)
  10312. return NULL;
  10313. if (processed==choosenLimit)
  10314. {
  10315. eof = true;
  10316. return NULL;
  10317. }
  10318. if (needTransform)
  10319. {
  10320. for (;;)
  10321. {
  10322. OwnedConstRoxieRow in = inputStream->nextRow();
  10323. if (!in)
  10324. {
  10325. if (anyThisGroup)
  10326. {
  10327. anyThisGroup = false;
  10328. return NULL;
  10329. }
  10330. in.setown(inputStream->nextRow());
  10331. if (!in)
  10332. {
  10333. eof = true;
  10334. return NULL; // eof...
  10335. }
  10336. }
  10337. if (likely(helper.canMatch(in)))
  10338. {
  10339. unsigned outSize;
  10340. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10341. try
  10342. {
  10343. outSize = helper.transform(rowBuilder, in);
  10344. }
  10345. catch (IException *E)
  10346. {
  10347. throw makeWrappedException(E);
  10348. }
  10349. if (outSize)
  10350. {
  10351. anyThisGroup = true;
  10352. processed++;
  10353. if (processed==rowLimit)
  10354. {
  10355. if (traceLevel > 4)
  10356. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10357. helper.onLimitExceeded();
  10358. }
  10359. return rowBuilder.finalizeRowClear(outSize);
  10360. }
  10361. }
  10362. }
  10363. }
  10364. else
  10365. {
  10366. const void *ret = inputStream->nextRow();
  10367. if (ret)
  10368. {
  10369. processed++;
  10370. if (processed==rowLimit)
  10371. {
  10372. if (traceLevel > 4)
  10373. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10374. ReleaseClearRoxieRow(ret);
  10375. helper.onLimitExceeded(); // should not return
  10376. throwUnexpected();
  10377. }
  10378. }
  10379. return ret;
  10380. }
  10381. }
  10382. };
  10383. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10384. {
  10385. public:
  10386. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10387. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10388. {
  10389. }
  10390. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  10391. {
  10392. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10393. }
  10394. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10395. {
  10396. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite || sourceKind==TAKspillwrite) // Bit of a hack - codegen probably should differentiate
  10397. setInput(0, source, sourceIdx);
  10398. else
  10399. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10400. }
  10401. };
  10402. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10403. {
  10404. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10405. }
  10406. //=================================================================================
  10407. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10408. {
  10409. public:
  10410. CRoxieServerSpillWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10411. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10412. {
  10413. }
  10414. ~CRoxieServerSpillWriteActivity()
  10415. {
  10416. }
  10417. virtual const void *nextRow()
  10418. {
  10419. ActivityTimer t(activityStats, timeActivities);
  10420. return inputStream->nextRow();
  10421. }
  10422. };
  10423. //==================================================================================
  10424. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10425. {
  10426. protected:
  10427. Owned<IExtRowWriter> outSeq;
  10428. Owned<IOutputRowSerializer> rowSerializer;
  10429. Linked<IFileIOStream> diskout;
  10430. bool blockcompressed;
  10431. bool extend;
  10432. bool overwrite;
  10433. bool encrypted;
  10434. bool grouped;
  10435. IHThorDiskWriteArg &helper;
  10436. Owned<IRecordSize> diskmeta;
  10437. Owned<IRoxieWriteHandler> writer;
  10438. bool tallycrc;
  10439. unsigned __int64 uncompressedBytesWritten;
  10440. CRC32 crc;
  10441. void updateWorkUnitResult(unsigned __int64 reccount)
  10442. {
  10443. assertex(writer);
  10444. // MORE - a lot of this is common with hthor
  10445. WorkunitUpdate wu = ctx->updateWorkUnit();
  10446. if (wu)
  10447. {
  10448. OwnedRoxieString rawLogicalName = helper.getFileName();
  10449. StringBuffer lfn; // logical filename
  10450. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10451. if (lfn.length())
  10452. {
  10453. unsigned flags = helper.getFlags();
  10454. WUFileKind fileKind;
  10455. if (TDXtemporary & flags)
  10456. fileKind = WUFileTemporary;
  10457. else if(TDXjobtemp & flags)
  10458. fileKind = WUFileJobOwned;
  10459. else if(TDWowned & flags)
  10460. fileKind = WUFileOwned;
  10461. else
  10462. fileKind = WUFileStandard;
  10463. StringArray clusters;
  10464. writer->getClusters(clusters);
  10465. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10466. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10467. {
  10468. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10469. if (result)
  10470. {
  10471. result->setResultTotalRowCount(reccount);
  10472. result->setResultStatus(ResultStatusCalculated);
  10473. if (helper.getFlags() & TDWresult)
  10474. result->setResultFilename(lfn.str());
  10475. else
  10476. result->setResultLogicalName(lfn.str());
  10477. }
  10478. }
  10479. }
  10480. }
  10481. }
  10482. void resolve()
  10483. {
  10484. OwnedRoxieString rawLogicalName = helper.getFileName();
  10485. assertex(rawLogicalName);
  10486. assertex((helper.getFlags() & TDXtemporary) == 0);
  10487. StringArray clusters;
  10488. unsigned clusterIdx = 0;
  10489. while(true)
  10490. {
  10491. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10492. if(!cluster)
  10493. break;
  10494. if (isContainerized())
  10495. throw makeStringException(0, "Output clusters not supported in cloud environment");
  10496. clusters.append(cluster);
  10497. clusterIdx++;
  10498. }
  10499. if (clusters.length())
  10500. {
  10501. if (extend)
  10502. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10503. }
  10504. else
  10505. {
  10506. if (isContainerized() && fileNameServiceDali)
  10507. {
  10508. StringBuffer nasGroupName;
  10509. queryNamedGroupStore().getNasGroupName(nasGroupName, 1);
  10510. clusters.append(nasGroupName);
  10511. }
  10512. else if (roxieName.length())
  10513. clusters.append(roxieName.str());
  10514. else
  10515. clusters.append(".");
  10516. }
  10517. // Using defaultPrivilegedUser as restricted files applies to limits reading of file (not writing of files)
  10518. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters, defaultPrivilegedUser));
  10519. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10520. }
  10521. public:
  10522. CRoxieServerDiskWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10523. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10524. {
  10525. extend = ((helper.getFlags() & TDWextend) != 0);
  10526. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10527. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10528. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10529. if (grouped)
  10530. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10531. size32_t fixedSize = diskmeta->getFixedSize();
  10532. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && ((0 == fixedSize) || (fixedSize >= MIN_ROWCOMPRESS_RECSIZE)))); //always use new compression
  10533. encrypted = false; // set later
  10534. tallycrc = true;
  10535. uncompressedBytesWritten = 0;
  10536. }
  10537. ~CRoxieServerDiskWriteActivity()
  10538. {
  10539. }
  10540. virtual bool needsAllocator() const
  10541. {
  10542. return true;
  10543. }
  10544. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10545. {
  10546. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10547. resolve();
  10548. Owned<IFileIO> io;
  10549. void *ekey;
  10550. size32_t ekeylen;
  10551. helper.getEncryptKey(ekeylen, ekey);
  10552. Owned<ICompressor> ecomp;
  10553. if (ekeylen!=0)
  10554. {
  10555. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10556. memset(ekey,0,ekeylen);
  10557. rtlFree(ekey);
  10558. encrypted = true;
  10559. blockcompressed = true;
  10560. }
  10561. if (blockcompressed)
  10562. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp, COMPRESS_METHOD_LZW));
  10563. else
  10564. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10565. if (!io)
  10566. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10567. diskout.setown(createBufferedIOStream(io));
  10568. if (extend)
  10569. diskout->seek(0, IFSend);
  10570. tallycrc = !blockcompressed; // MORE: Should this be controlled by an activity hint/flag?
  10571. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10572. rowSerializer.set(rowIf->queryRowSerializer());
  10573. unsigned rwFlags = rw_autoflush;
  10574. if(grouped)
  10575. rwFlags |= rw_grouped;
  10576. if(tallycrc)
  10577. rwFlags |= rw_crc;
  10578. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10579. }
  10580. virtual void stop()
  10581. {
  10582. if (aborted)
  10583. {
  10584. if (writer)
  10585. writer->finish(false, this);
  10586. }
  10587. else
  10588. {
  10589. if (outSeq)
  10590. outSeq->flush(&crc);
  10591. if (outSeq)
  10592. uncompressedBytesWritten = outSeq->getPosition();
  10593. outSeq.clear();
  10594. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10595. if (writer)
  10596. {
  10597. updateWorkUnitResult(processed);
  10598. writer->finish(true, this);
  10599. }
  10600. }
  10601. writer.clear();
  10602. CRoxieServerActivity::stop();
  10603. }
  10604. virtual void reset()
  10605. {
  10606. CRoxieServerInternalSinkActivity::reset();
  10607. diskout.clear();
  10608. outSeq.clear();
  10609. writer.clear();
  10610. uncompressedBytesWritten = 0;
  10611. crc.reset();
  10612. }
  10613. virtual void onExecute()
  10614. {
  10615. for (;;)
  10616. {
  10617. const void *row = inputStream->nextRow();
  10618. if (!row)
  10619. {
  10620. row = inputStream->nextRow();
  10621. if (!row)
  10622. break;
  10623. if (grouped)
  10624. outSeq->putRow(NULL);
  10625. }
  10626. processed++;
  10627. outSeq->putRow(row);
  10628. }
  10629. }
  10630. virtual void setFileProperties(IFileDescriptor *desc) const
  10631. {
  10632. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10633. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10634. if (blockcompressed)
  10635. {
  10636. // caller has already set @size from file size...
  10637. fileProps.setPropBool("@blockCompressed", true);
  10638. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10639. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10640. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10641. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10642. }
  10643. else if (tallycrc && crc.get())
  10644. partProps.setPropInt64("@fileCrc", crc.get());
  10645. if (encrypted)
  10646. fileProps.setPropBool("@encrypted", true);
  10647. fileProps.setPropInt64("@recordCount", processed);
  10648. partProps.setPropInt64("@recordCount", processed);
  10649. unsigned flags = helper.getFlags();
  10650. if (flags & TDWpersist)
  10651. fileProps.setPropBool("@persistent", true);
  10652. if (grouped)
  10653. fileProps.setPropBool("@grouped", true);
  10654. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10655. fileProps.setPropBool("@owned", true);
  10656. if (flags & TDWresult)
  10657. fileProps.setPropBool("@result", true);
  10658. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10659. if (workUnit)
  10660. {
  10661. fileProps.setProp("@owner", workUnit->queryUser());
  10662. fileProps.setProp("@workunit", workUnit->queryWuid());
  10663. fileProps.setProp("@job", workUnit->queryJobName());
  10664. }
  10665. if (flags & TDWexpires)
  10666. setExpiryTime(fileProps, helper.getExpiryDays());
  10667. if (flags & TDWupdate)
  10668. {
  10669. unsigned eclCRC;
  10670. unsigned __int64 totalCRC;
  10671. helper.getUpdateCRCs(eclCRC, totalCRC);
  10672. fileProps.setPropInt("@eclCRC", eclCRC);
  10673. fileProps.setPropInt64("@totalCRC", totalCRC);
  10674. }
  10675. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10676. if (flags & TDWrestricted)
  10677. fileProps.setPropBool("restricted", true);
  10678. IRecordSize * inputMeta = input->queryOutputMeta();
  10679. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10680. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10681. const char *recordECL = helper.queryRecordECL();
  10682. if (recordECL && *recordECL)
  10683. fileProps.setProp("ECL", recordECL);
  10684. setRtlFormat(fileProps, helper.queryDiskRecordSize());
  10685. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10686. }
  10687. virtual IUserDescriptor *queryUserDescriptor() const
  10688. {
  10689. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10690. if (workUnit)
  10691. return workUnit->queryUserDescriptor();//ad-hoc mode
  10692. else
  10693. {
  10694. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10695. if (daliHelper)
  10696. return daliHelper->queryUserDescriptor();//predeployed query mode
  10697. }
  10698. return NULL;
  10699. }
  10700. virtual bool isOutputTransformed() const { return false; }
  10701. };
  10702. //=================================================================================
  10703. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10704. {
  10705. IHThorCsvWriteArg &csvHelper;
  10706. CSVOutputStream csvOutput;
  10707. public:
  10708. CRoxieServerCsvWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10709. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10710. {
  10711. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10712. }
  10713. virtual void onExecute()
  10714. {
  10715. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10716. if (header)
  10717. {
  10718. csvOutput.beginLine();
  10719. csvOutput.writeHeaderLn(strlen(header), header);
  10720. diskout->write(csvOutput.length(), csvOutput.str());
  10721. }
  10722. for (;;)
  10723. {
  10724. const void *nextrec = inputStream->ungroupedNextRow();
  10725. if (!nextrec)
  10726. break;
  10727. processed++;
  10728. csvOutput.beginLine();
  10729. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10730. csvOutput.endLine();
  10731. diskout->write(csvOutput.length(), csvOutput.str());
  10732. ReleaseRoxieRow(nextrec);
  10733. }
  10734. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10735. if (footer)
  10736. {
  10737. csvOutput.beginLine();
  10738. csvOutput.writeHeaderLn(strlen(footer), footer);
  10739. diskout->write(csvOutput.length(), csvOutput.str());
  10740. }
  10741. }
  10742. virtual void setFileProperties(IFileDescriptor *desc) const
  10743. {
  10744. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10745. IPropertyTree &props = desc->queryProperties();
  10746. props.setProp("@format","utf8n");
  10747. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10748. StringBuffer separator;
  10749. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10750. const char *s = rs;
  10751. while (s && *s)
  10752. {
  10753. if (',' == *s)
  10754. separator.append("\\,");
  10755. else
  10756. separator.append(*s);
  10757. ++s;
  10758. }
  10759. props.setProp("@csvSeparate", separator.str());
  10760. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10761. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10762. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10763. props.setProp("@kind", "csv");
  10764. }
  10765. virtual bool isOutputTransformed() const { return true; }
  10766. };
  10767. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10768. {
  10769. IHThorXmlWriteArg &xmlHelper;
  10770. StringAttr rowTag;
  10771. ThorActivityKind kind;
  10772. unsigned headerLength;
  10773. unsigned footerLength;
  10774. public:
  10775. CRoxieServerXmlWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10776. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10777. {
  10778. }
  10779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10780. {
  10781. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10782. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10783. if (!xmlpath)
  10784. rowTag.set(DEFAULTXMLROWTAG);
  10785. else
  10786. {
  10787. const char *path = xmlpath;
  10788. if (*path == '/') path++;
  10789. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10790. rowTag.set(path);
  10791. }
  10792. }
  10793. virtual void onExecute()
  10794. {
  10795. StringBuffer header;
  10796. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10797. if (kind==TAKjsonwrite)
  10798. buildJsonHeader(header, suppliedHeader, rowTag);
  10799. else if (suppliedHeader)
  10800. header.set(suppliedHeader);
  10801. else
  10802. header.append(DEFAULTXMLHEADER).newline();
  10803. headerLength = header.length();
  10804. diskout->write(header.length(), header.str());
  10805. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSONRootless : WTStandard);
  10806. writer->outputBeginArray(rowTag); //need to set this
  10807. writer->clear(); //but not output it
  10808. for (;;)
  10809. {
  10810. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10811. if (!nextrec)
  10812. break;
  10813. processed++;
  10814. writer->clear().outputBeginNested(rowTag, false);
  10815. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10816. writer->outputEndNested(rowTag);
  10817. diskout->write(writer->length(), writer->str());
  10818. }
  10819. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10820. StringBuffer footer;
  10821. if (kind==TAKjsonwrite)
  10822. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10823. else if (suppliedFooter)
  10824. footer.append(suppliedFooter);
  10825. else
  10826. footer.append(DEFAULTXMLFOOTER);
  10827. footerLength=footer.length();
  10828. diskout->write(footer.length(), footer);
  10829. }
  10830. virtual void reset()
  10831. {
  10832. CRoxieServerDiskWriteActivity::reset();
  10833. rowTag.clear();
  10834. }
  10835. virtual void setFileProperties(IFileDescriptor *desc) const
  10836. {
  10837. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10838. desc->queryProperties().setProp("@format","utf8n");
  10839. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10840. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10841. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10842. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10843. }
  10844. virtual bool isOutputTransformed() const { return true; }
  10845. };
  10846. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10847. {
  10848. bool isTemp;
  10849. public:
  10850. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10851. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10852. {
  10853. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10854. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10855. setNumOutputs(helper->getTempUsageCount());
  10856. if (_kind != TAKspillwrite)
  10857. assertex(numOutputs == 0);
  10858. }
  10859. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  10860. {
  10861. switch (numOutputs)
  10862. {
  10863. case 0:
  10864. switch (kind)
  10865. {
  10866. case TAKdiskwrite:
  10867. return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10868. case TAKcsvwrite:
  10869. return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10870. case TAKxmlwrite:
  10871. case TAKjsonwrite:
  10872. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10873. case TAKspillwrite:
  10874. return new CRoxieServerNullSinkActivity(_ctx, this, _probeManager);
  10875. };
  10876. throwUnexpected();
  10877. case 1:
  10878. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10879. default:
  10880. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10881. }
  10882. }
  10883. virtual bool isSink() const
  10884. {
  10885. return numOutputs == 0 && (kind==TAKspillwrite || !isTemp); // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10886. }
  10887. };
  10888. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10889. {
  10890. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10891. }
  10892. //=================================================================================
  10893. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10894. {
  10895. IHThorIndexWriteArg &helper;
  10896. bool overwrite;
  10897. Owned<ClusterWriteHandler> clusterHandler;
  10898. Owned<IRoxieWriteHandler> writer;
  10899. unsigned __int64 reccount;
  10900. unsigned int fileCrc;
  10901. StringBuffer filename;
  10902. unsigned __int64 duplicateKeyCount = 0;
  10903. unsigned __int64 cummulativeDuplicateKeyCount = 0;
  10904. void updateWorkUnitResult()
  10905. {
  10906. // MORE - a lot of this is common with hthor
  10907. WorkunitUpdate wu = ctx->updateWorkUnit();
  10908. if (wu)
  10909. {
  10910. OwnedRoxieString rawLogicalName = helper.getFileName();
  10911. StringBuffer lfn; // logical filename
  10912. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10913. if (lfn.length())
  10914. {
  10915. if (helper.getSequence() >= 0)
  10916. {
  10917. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10918. if (result)
  10919. {
  10920. result->setResultTotalRowCount(reccount);
  10921. result->setResultStatus(ResultStatusCalculated);
  10922. result->setResultLogicalName(lfn.str());
  10923. }
  10924. }
  10925. if(clusterHandler)
  10926. clusterHandler->finish(writer->queryFile());
  10927. CTXLOG("Created roxie index file %s", lfn.str());
  10928. }
  10929. }
  10930. }
  10931. virtual void resolve()
  10932. {
  10933. StringArray clusters;
  10934. unsigned clusterIdx = 0;
  10935. while(true)
  10936. {
  10937. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10938. if(!cluster)
  10939. break;
  10940. if (isContainerized())
  10941. throw makeStringException(0, "Output clusters not supported in cloud environment");
  10942. clusters.append(cluster);
  10943. clusterIdx++;
  10944. }
  10945. if (!clusters.length())
  10946. {
  10947. if (isContainerized() && fileNameServiceDali)
  10948. {
  10949. StringBuffer nasGroupName;
  10950. queryNamedGroupStore().getNasGroupName(nasGroupName, 1);
  10951. clusters.append(nasGroupName);
  10952. }
  10953. else if (roxieName.length())
  10954. clusters.append(roxieName.str());
  10955. else
  10956. clusters.append(".");
  10957. }
  10958. OwnedRoxieString fname(helper.getFileName());
  10959. writer.setown(ctx->createLFN(fname, overwrite, false, clusters, defaultPrivilegedUser)); // MORE - if there's a workunit, use if for scope.
  10960. filename.set(writer->queryFile()->queryFilename());
  10961. if (writer->queryFile()->exists())
  10962. {
  10963. if (overwrite)
  10964. {
  10965. CTXLOG("Removing existing %s from DFS",filename.str());
  10966. writer->queryFile()->remove();
  10967. }
  10968. else
  10969. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10970. }
  10971. }
  10972. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10973. {
  10974. size32_t nameLen;
  10975. char * nameBuff;
  10976. size32_t valueLen;
  10977. char * valueBuff;
  10978. unsigned idx = 0;
  10979. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10980. {
  10981. StringBuffer name(nameLen, nameBuff);
  10982. StringBuffer value(valueLen, valueBuff);
  10983. rtlFree(nameBuff);
  10984. rtlFree(valueBuff);
  10985. if(*name == '_' && !checkReservedMetadataName(name))
  10986. {
  10987. OwnedRoxieString fname(helper.getFileName());
  10988. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10989. }
  10990. if(!validateXMLTag(name.str()))
  10991. {
  10992. OwnedRoxieString fname(helper.getFileName());
  10993. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10994. }
  10995. if(!metadata)
  10996. metadata.setown(createPTree("metadata", ipt_fast));
  10997. metadata->setProp(name.str(), value.str());
  10998. }
  10999. }
  11000. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  11001. {
  11002. if(!metadata)
  11003. metadata.setown(createPTree("metadata", ipt_fast));
  11004. metadata->setProp("_record_ECL", helper.queryRecordECL());
  11005. setRtlFormat(*metadata, helper.queryDiskRecordSize());
  11006. }
  11007. public:
  11008. CRoxieServerIndexWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11009. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  11010. {
  11011. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  11012. reccount = 0;
  11013. fileCrc = 0;
  11014. }
  11015. ~CRoxieServerIndexWriteActivity()
  11016. {
  11017. }
  11018. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11019. {
  11020. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11021. resolve();
  11022. }
  11023. virtual void onExecute()
  11024. {
  11025. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  11026. size32_t fileposSize = hasTrailingFileposition(helper.queryDiskRecordSize()->queryTypeInfo()) ? sizeof(offset_t) : 0;
  11027. size32_t maxDiskRecordSize;
  11028. if (isVariable)
  11029. {
  11030. if (helper.getFlags() & TIWmaxlength)
  11031. maxDiskRecordSize = helper.getMaxKeySize();
  11032. else
  11033. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  11034. }
  11035. else
  11036. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize()-fileposSize;
  11037. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  11038. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  11039. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  11040. fileCrc = -1;
  11041. {
  11042. Owned<IFileIO> io;
  11043. try
  11044. {
  11045. io.setown(writer->queryFile()->open(IFOcreate));
  11046. }
  11047. catch(IException * e)
  11048. {
  11049. e->Release();
  11050. clearKeyStoreCache(false);
  11051. io.setown(writer->queryFile()->open(IFOcreate));
  11052. }
  11053. if(!io)
  11054. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  11055. bool needsSeek = true;
  11056. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  11057. if (helper.getFlags() & TIWrowcompress)
  11058. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  11059. else if (!(helper.getFlags() & TIWnolzwcompress))
  11060. flags |= HTREE_COMPRESSED_KEY;
  11061. if (isVariable)
  11062. flags |= HTREE_VARSIZE;
  11063. Owned<IPropertyTree> metadata;
  11064. buildUserMetadata(metadata);
  11065. buildLayoutMetadata(metadata);
  11066. unsigned nodeSize = metadata->getPropInt("_nodeSize", NODESIZE);
  11067. if (metadata->getPropBool("_noSeek", ctx->queryOptions().noSeekBuildIndex))
  11068. {
  11069. flags |= TRAILING_HEADER_ONLY;
  11070. needsSeek = false;
  11071. }
  11072. if (metadata->getPropBool("_useTrailingHeader", true))
  11073. flags |= USE_TRAILING_HEADER;
  11074. Owned<IFileIOStream> out = createBufferedIOStream(io, 0x100000);
  11075. if (!needsSeek)
  11076. out.setown(createNoSeekIOStream(out));
  11077. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0, &helper, true, false);
  11078. class BcWrapper : implements IBlobCreator
  11079. {
  11080. IKeyBuilder *builder;
  11081. public:
  11082. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  11083. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  11084. {
  11085. return builder->createBlob(size, (const char *) ptr);
  11086. }
  11087. } bc(builder);
  11088. // Loop thru the results
  11089. for (;;)
  11090. {
  11091. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  11092. if (!nextrec)
  11093. break;
  11094. try
  11095. {
  11096. unsigned __int64 fpos=0;
  11097. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  11098. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  11099. builder->processKeyData(rowBuffer, fpos, thisSize);
  11100. }
  11101. catch(IException * e)
  11102. {
  11103. throw makeWrappedException(e);
  11104. }
  11105. reccount++;
  11106. }
  11107. duplicateKeyCount = builder->getDuplicateCount();
  11108. cummulativeDuplicateKeyCount += duplicateKeyCount;
  11109. builder->finish(metadata, &fileCrc);
  11110. clearKeyStoreCache(false);
  11111. }
  11112. }
  11113. virtual void stop()
  11114. {
  11115. if (writer)
  11116. {
  11117. if (!aborted)
  11118. updateWorkUnitResult();
  11119. writer->finish(!aborted, this);
  11120. writer.clear();
  11121. }
  11122. CRoxieServerActivity::stop();
  11123. }
  11124. virtual void reset()
  11125. {
  11126. noteStatistic(StNumDuplicateKeys, cummulativeDuplicateKeyCount);
  11127. CRoxieServerActivity::reset();
  11128. writer.clear();
  11129. }
  11130. //interface IRoxiePublishCallback
  11131. virtual void setFileProperties(IFileDescriptor *desc) const
  11132. {
  11133. // Now publish to name services
  11134. StringBuffer dir,base;
  11135. offset_t indexFileSize = writer->queryFile()->size();
  11136. if(clusterHandler)
  11137. clusterHandler->splitPhysicalFilename(dir, base);
  11138. else
  11139. {
  11140. // Check filename is URL and get localpath, only actually necessary if force remote reads are are on
  11141. RemoteFilename rfn;
  11142. rfn.setRemotePath(filename);
  11143. StringBuffer localPath;
  11144. rfn.getLocalPath(localPath);
  11145. splitFilename(localPath, &dir, &dir, &base, &base);
  11146. }
  11147. desc->setDefaultDir(dir.str());
  11148. //properties of the first file part.
  11149. Owned<IPropertyTree> attrs;
  11150. if(clusterHandler)
  11151. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  11152. else
  11153. {
  11154. // add cluster
  11155. StringBuffer mygroupname;
  11156. desc->setNumParts(1);
  11157. desc->setPartMask(base.str());
  11158. attrs.set(&desc->queryPart(0)->queryProperties());
  11159. }
  11160. attrs->setPropInt64("@size", indexFileSize);
  11161. attrs->setPropInt64("@recordCount", reccount);
  11162. CDateTime createTime, modifiedTime, accessedTime;
  11163. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  11164. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  11165. unsigned hour, min, sec, nanosec;
  11166. modifiedTime.getTime(hour, min, sec, nanosec);
  11167. modifiedTime.setTime(hour, min, sec, 0);
  11168. StringBuffer timestr;
  11169. modifiedTime.getString(timestr);
  11170. if(timestr.length())
  11171. attrs->setProp("@modified", timestr.str());
  11172. if(clusterHandler)
  11173. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  11174. // properties of the logical file
  11175. IPropertyTree & properties = desc->queryProperties();
  11176. properties.setProp("@kind", "key");
  11177. properties.setPropInt64("@size", indexFileSize);
  11178. properties.setPropInt64("@recordCount", reccount);
  11179. properties.setPropInt64("@duplicateKeyCount", duplicateKeyCount);
  11180. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  11181. if (workUnit)
  11182. {
  11183. properties.setProp("@owner", workUnit->queryUser());
  11184. properties.setProp("@workunit", workUnit->queryWuid());
  11185. properties.setProp("@job", workUnit->queryJobName());
  11186. }
  11187. char const * rececl = helper.queryRecordECL();
  11188. if(rececl && *rececl)
  11189. properties.setProp("ECL", rececl);
  11190. if (helper.getFlags() & TIWexpires)
  11191. setExpiryTime(properties, helper.getExpiryDays());
  11192. if (helper.getFlags() & TIWupdate)
  11193. {
  11194. unsigned eclCRC;
  11195. unsigned __int64 totalCRC;
  11196. helper.getUpdateCRCs(eclCRC, totalCRC);
  11197. properties.setPropInt("@eclCRC", eclCRC);
  11198. properties.setPropInt64("@totalCRC", totalCRC);
  11199. }
  11200. properties.setPropInt("@fileCrc", fileCrc);
  11201. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  11202. // Legacy record layout info
  11203. void * layoutMetaBuff;
  11204. size32_t layoutMetaSize;
  11205. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  11206. {
  11207. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  11208. rtlFree(layoutMetaBuff);
  11209. }
  11210. if (helper.getFlags() & TIWrestricted)
  11211. properties.setPropBool("restricted", true);
  11212. // New record layout info
  11213. setRtlFormat(properties, helper.queryDiskRecordSize());
  11214. // Bloom info
  11215. const IBloomBuilderInfo * const *bloomFilters = helper.queryBloomInfo();
  11216. while (bloomFilters && *bloomFilters)
  11217. {
  11218. const IBloomBuilderInfo *info = *bloomFilters++;
  11219. IPropertyTree *bloom = properties.addPropTree("Bloom");
  11220. bloom->setPropInt64("@bloomFieldMask", info->getBloomFields());
  11221. bloom->setPropInt64("@bloomLimit", info->getBloomLimit()); // MORE - if we didn't actually build because of the limit that might be interesting. Though that's going to vary by part.
  11222. VStringBuffer pval("%f", info->getBloomProbability());
  11223. bloom->setProp("@bloomProbability", pval.str());
  11224. }
  11225. }
  11226. IUserDescriptor *queryUserDescriptor() const
  11227. {
  11228. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  11229. if (workUnit)
  11230. return workUnit->queryUserDescriptor();//ad-hoc mode
  11231. else
  11232. {
  11233. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  11234. if (daliHelper)
  11235. return daliHelper->queryUserDescriptor();//predeployed query mode
  11236. }
  11237. return NULL;
  11238. }
  11239. };
  11240. //=================================================================================
  11241. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  11242. {
  11243. public:
  11244. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11245. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11246. {
  11247. setNumOutputs(0);
  11248. }
  11249. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  11250. {
  11251. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  11252. }
  11253. virtual bool isSink() const
  11254. {
  11255. return true;
  11256. }
  11257. virtual const StatisticsMapping &queryStatsMapping() const
  11258. {
  11259. return indexWriteStatistics; // Overridden by anyone that needs more
  11260. }
  11261. };
  11262. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11263. {
  11264. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  11265. }
  11266. //=================================================================================
  11267. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  11268. {
  11269. if((flags & JFmatchAbortLimitSkips) != 0)
  11270. {
  11271. limitFail = false;
  11272. limitOnFail = false;
  11273. }
  11274. else
  11275. {
  11276. limitOnFail = ((flags & JFonfail) != 0);
  11277. limitFail = !limitOnFail;
  11278. }
  11279. }
  11280. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  11281. {
  11282. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  11283. IHThorJoinArg &helper;
  11284. ICompare * collate;
  11285. ICompare * collateupper;
  11286. ThorActivityKind activityKind;
  11287. bool leftOuterJoin;
  11288. bool rightOuterJoin;
  11289. bool exclude;
  11290. bool limitFail;
  11291. bool limitOnFail;
  11292. bool forceSpill;
  11293. unsigned keepLimit;
  11294. unsigned joinLimit;
  11295. unsigned atmostLimit;
  11296. unsigned abortLimit;
  11297. unsigned atmostsTriggered;
  11298. bool betweenjoin;
  11299. OwnedRowArray right;
  11300. const void * left;
  11301. const void * pendingRight;
  11302. unsigned rightIndex;
  11303. unsigned joinCounter;
  11304. BoolArray matchedRight;
  11305. bool matchedLeft;
  11306. Owned<IException> failingLimit;
  11307. ConstPointerArray filteredRight;
  11308. Owned<IRHLimitedCompareHelper> limitedhelper;
  11309. OwnedConstRoxieRow defaultLeft;
  11310. OwnedConstRoxieRow defaultRight;
  11311. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11312. Owned<IEngineRowAllocator> defaultRightAllocator;
  11313. Owned<IGroupedInput> sortedLeft;
  11314. Owned<IGroupedInput> groupedSortedRight;
  11315. bool cloneLeft;
  11316. void createDefaultLeft()
  11317. {
  11318. if (!defaultLeft)
  11319. {
  11320. if (!defaultLeftAllocator)
  11321. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11322. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11323. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11324. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11325. }
  11326. }
  11327. void createDefaultRight()
  11328. {
  11329. if (!defaultRight)
  11330. {
  11331. if (!defaultRightAllocator)
  11332. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11333. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11334. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11335. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11336. }
  11337. }
  11338. public:
  11339. CRoxieServerJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11340. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11341. {
  11342. // MORE - some of this should be done in factory
  11343. unsigned joinFlags = helper.getJoinFlags();
  11344. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11345. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11346. exclude = (joinFlags & JFexclude) != 0;
  11347. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11348. getLimitType(joinFlags, limitFail, limitOnFail);
  11349. if (joinFlags & JFslidingmatch)
  11350. {
  11351. betweenjoin = true;
  11352. collate = helper.queryCompareLeftRightLower();
  11353. collateupper = helper.queryCompareLeftRightUpper();
  11354. }
  11355. else
  11356. {
  11357. betweenjoin = false;
  11358. collate = collateupper = helper.queryCompareLeftRight();
  11359. }
  11360. rightIndex = 0;
  11361. joinCounter = 0;
  11362. state = JSfill;
  11363. matchedLeft = false;
  11364. joinLimit = 0;
  11365. keepLimit = 0; // wait until ctx available
  11366. atmostLimit = 0; // wait until ctx available
  11367. abortLimit = 0; // wait until ctx available
  11368. atmostsTriggered = 0;
  11369. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11370. left = NULL;
  11371. pendingRight = NULL;
  11372. activityKind = _factory->getKind();
  11373. }
  11374. virtual bool needsAllocator() const { return true; }
  11375. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11376. {
  11377. left = NULL;
  11378. rightIndex = 0;
  11379. joinCounter = 0;
  11380. state = JSfill;
  11381. matchedLeft = false;
  11382. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11383. keepLimit = helper.getKeepLimit();
  11384. if (keepLimit == 0)
  11385. keepLimit = (unsigned)-1;
  11386. atmostsTriggered = 0;
  11387. atmostLimit = helper.getJoinLimit();
  11388. if(atmostLimit == 0)
  11389. atmostLimit = (unsigned)-1;
  11390. else
  11391. assertex(!rightOuterJoin && !betweenjoin);
  11392. abortLimit = helper.getMatchAbortLimit();
  11393. if (abortLimit == 0)
  11394. abortLimit = (unsigned)-1;
  11395. if (rightOuterJoin)
  11396. createDefaultLeft();
  11397. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11398. createDefaultRight();
  11399. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11400. RoxieSortAlgorithm sortAlgorithm;
  11401. if (forceSpill)
  11402. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11403. else
  11404. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11405. if (helper.isLeftAlreadySorted())
  11406. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11407. else
  11408. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11409. ICompare *compareRight = helper.queryCompareRight();
  11410. if (helper.isRightAlreadySorted())
  11411. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11412. else
  11413. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11414. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11415. { //limited match join (s[1..n])
  11416. limitedhelper.setown(createRHLimitedCompareHelper());
  11417. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11418. }
  11419. }
  11420. virtual void reset()
  11421. {
  11422. if (atmostsTriggered)
  11423. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11424. right.clear();
  11425. ReleaseClearRoxieRow(left);
  11426. ReleaseClearRoxieRow(pendingRight);
  11427. defaultRight.clear();
  11428. defaultLeft.clear();
  11429. sortedLeft.clear();
  11430. groupedSortedRight.clear();
  11431. CRoxieServerTwoInputActivity::reset();
  11432. }
  11433. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11434. {
  11435. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11436. {
  11437. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11438. puller->setInput(0, _sourceIdx, _in);
  11439. _in = puller;
  11440. _sourceIdx = 0;
  11441. }
  11442. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11443. }
  11444. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11445. {
  11446. if (idx==(unsigned)-1)
  11447. idx = 0;
  11448. return idx ? NULL : this;
  11449. }
  11450. void fillLeft()
  11451. {
  11452. matchedLeft = false;
  11453. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11454. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11455. fillRight();
  11456. if (limitedhelper && 0==rightIndex)
  11457. {
  11458. rightIndex = 0;
  11459. joinCounter = 0;
  11460. right.clear();
  11461. matchedRight.kill();
  11462. if (left)
  11463. {
  11464. limitedhelper->getGroup(right,left);
  11465. ForEachItemIn(idx, right)
  11466. matchedRight.append(false);
  11467. }
  11468. }
  11469. }
  11470. void fillRight()
  11471. {
  11472. if (limitedhelper)
  11473. return;
  11474. failingLimit.clear();
  11475. if(betweenjoin && left)
  11476. {
  11477. aindex_t start = 0;
  11478. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11479. start++;
  11480. if(start>0)
  11481. right.clearPart(0, start);
  11482. }
  11483. else
  11484. right.clear();
  11485. rightIndex = 0;
  11486. joinCounter = 0;
  11487. unsigned groupCount = 0;
  11488. const void * next;
  11489. while(true)
  11490. {
  11491. if(pendingRight)
  11492. {
  11493. next = pendingRight;
  11494. pendingRight = NULL;
  11495. }
  11496. else
  11497. {
  11498. next = groupedSortedRight->nextRow();
  11499. }
  11500. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11501. {
  11502. while(next)
  11503. {
  11504. ReleaseClearRoxieRow(next);
  11505. next = groupedSortedRight->nextRow();
  11506. }
  11507. continue;
  11508. }
  11509. while(next)
  11510. {
  11511. if(groupCount==abortLimit)
  11512. {
  11513. if(limitFail)
  11514. failLimit();
  11515. if (ctx->queryDebugContext())
  11516. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11517. if(limitOnFail)
  11518. {
  11519. assertex(!failingLimit);
  11520. try
  11521. {
  11522. failLimit();
  11523. }
  11524. catch(IException * except)
  11525. {
  11526. failingLimit.setown(except);
  11527. }
  11528. assertex(failingLimit != NULL);
  11529. }
  11530. right.append(next);
  11531. do
  11532. {
  11533. next = groupedSortedRight->nextRow();
  11534. ReleaseRoxieRow(next);
  11535. } while(next);
  11536. break;
  11537. }
  11538. else if(groupCount==atmostLimit)
  11539. {
  11540. atmostsTriggered++;
  11541. right.clear();
  11542. groupCount = 0;
  11543. while(next)
  11544. {
  11545. ReleaseRoxieRow(next);
  11546. next = groupedSortedRight->nextRow();
  11547. }
  11548. }
  11549. else
  11550. {
  11551. right.append(next);
  11552. groupCount++;
  11553. }
  11554. next = groupedSortedRight->nextRow();
  11555. }
  11556. // 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
  11557. if(betweenjoin && left)
  11558. {
  11559. pendingRight = groupedSortedRight->nextRow();
  11560. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11561. break;
  11562. }
  11563. else
  11564. break;
  11565. }
  11566. matchedRight.kill();
  11567. ForEachItemIn(idx, right)
  11568. matchedRight.append(false);
  11569. }
  11570. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter, unsigned flags)
  11571. {
  11572. if (cloneLeft)
  11573. {
  11574. LinkRoxieRow(curLeft);
  11575. return curLeft;
  11576. }
  11577. try
  11578. {
  11579. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11580. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  11581. if (thisSize)
  11582. return rowBuilder.finalizeRowClear(thisSize);
  11583. else
  11584. return NULL;
  11585. }
  11586. catch (IException *E)
  11587. {
  11588. throw makeWrappedException(E);
  11589. }
  11590. }
  11591. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  11592. {
  11593. try
  11594. {
  11595. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11596. unsigned numRows = rows.ordinality();
  11597. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11598. if (numRows>0)
  11599. flags |= JTFmatchedright;
  11600. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray(), flags);
  11601. if (thisSize)
  11602. return rowBuilder.finalizeRowClear(thisSize);
  11603. else
  11604. return NULL;
  11605. }
  11606. catch (IException *E)
  11607. {
  11608. throw makeWrappedException(E);
  11609. }
  11610. }
  11611. const void * joinException(const void * curLeft, IException * except)
  11612. {
  11613. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11614. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except, JTFmatchedleft);
  11615. return rowBuilder.finalizeRowClear(thisSize);
  11616. }
  11617. void failLimit()
  11618. {
  11619. helper.onMatchAbortLimitExceeded();
  11620. CommonXmlWriter xmlwrite(0);
  11621. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11622. {
  11623. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11624. }
  11625. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11626. }
  11627. virtual const void * nextRow()
  11628. {
  11629. ActivityTimer t(activityStats, timeActivities);
  11630. for (;;)
  11631. {
  11632. switch (state)
  11633. {
  11634. case JSfill:
  11635. fillLeft();
  11636. state = JSfillright;
  11637. break;
  11638. case JSfillright:
  11639. fillRight();
  11640. state = JScollate;
  11641. break;
  11642. case JSfillleft:
  11643. fillLeft();
  11644. state = JScollate;
  11645. break;
  11646. case JScollate:
  11647. if (right.ordinality() == 0)
  11648. {
  11649. if (left == NULL)
  11650. return NULL;
  11651. state = JSleftonly;
  11652. }
  11653. else
  11654. {
  11655. if (!left)
  11656. state = JSrightonly;
  11657. else
  11658. {
  11659. int diff;
  11660. if(betweenjoin)
  11661. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11662. else
  11663. diff = collate->docompare(left, right.item(0));
  11664. bool limitExceeded = right.ordinality()>abortLimit;
  11665. if (diff == 0)
  11666. {
  11667. if (limitExceeded)
  11668. {
  11669. const void * ret = NULL;
  11670. if(failingLimit)
  11671. ret = joinException(left, failingLimit);
  11672. ReleaseRoxieRow(left);
  11673. left = NULL;
  11674. state = JSfillleft;
  11675. ForEachItemIn(idx, right)
  11676. matchedRight.replace(true, idx);
  11677. if(ret)
  11678. {
  11679. processed++;
  11680. return ret;
  11681. }
  11682. }
  11683. else
  11684. {
  11685. state = JScompare;
  11686. joinLimit = keepLimit;
  11687. }
  11688. }
  11689. else if (diff < 0)
  11690. state = JSleftonly;
  11691. else if (limitExceeded)
  11692. {
  11693. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11694. state = JSfillright;
  11695. }
  11696. else
  11697. state = JSrightonly;
  11698. }
  11699. }
  11700. break;
  11701. case JSrightonly:
  11702. if (rightOuterJoin)
  11703. {
  11704. switch (activityKind)
  11705. {
  11706. case TAKjoin:
  11707. {
  11708. while (right.isItem(rightIndex))
  11709. {
  11710. if (!matchedRight.item(rightIndex))
  11711. {
  11712. const void * rhs = right.item(rightIndex++);
  11713. const void *ret = joinRecords(defaultLeft, rhs, 0, JTFmatchedright);
  11714. if (ret)
  11715. {
  11716. processed++;
  11717. return ret;
  11718. }
  11719. }
  11720. else
  11721. rightIndex++;
  11722. }
  11723. break;
  11724. }
  11725. //Probably excessive to implement the following, but possibly useful
  11726. case TAKdenormalize:
  11727. {
  11728. OwnedConstRoxieRow newLeft;
  11729. newLeft.set(defaultLeft);
  11730. unsigned rowSize = 0;
  11731. unsigned leftCount = 0;
  11732. while (right.isItem(rightIndex))
  11733. {
  11734. if (!matchedRight.item(rightIndex))
  11735. {
  11736. const void * rhs = right.item(rightIndex);
  11737. try
  11738. {
  11739. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11740. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedright);
  11741. if (thisSize)
  11742. {
  11743. rowSize = thisSize;
  11744. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11745. }
  11746. }
  11747. catch (IException *E)
  11748. {
  11749. throw makeWrappedException(E);
  11750. }
  11751. }
  11752. rightIndex++;
  11753. }
  11754. state = JSfillright;
  11755. if (rowSize)
  11756. {
  11757. processed++;
  11758. return newLeft.getClear();
  11759. }
  11760. break;
  11761. }
  11762. case TAKdenormalizegroup:
  11763. {
  11764. filteredRight.kill();
  11765. while (right.isItem(rightIndex))
  11766. {
  11767. if (!matchedRight.item(rightIndex))
  11768. filteredRight.append(right.item(rightIndex));
  11769. rightIndex++;
  11770. }
  11771. state = JSfillright;
  11772. if (filteredRight.ordinality())
  11773. {
  11774. const void * ret = denormalizeRecords(defaultLeft, filteredRight, 0);
  11775. filteredRight.kill();
  11776. if (ret)
  11777. {
  11778. processed++;
  11779. return ret;
  11780. }
  11781. }
  11782. break;
  11783. }
  11784. }
  11785. }
  11786. state = JSfillright;
  11787. break;
  11788. case JSleftonly:
  11789. {
  11790. const void * ret = NULL;
  11791. if (!matchedLeft && leftOuterJoin)
  11792. {
  11793. switch (activityKind)
  11794. {
  11795. case TAKjoin:
  11796. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  11797. break;
  11798. case TAKdenormalize:
  11799. ret = left;
  11800. left = NULL;
  11801. break;
  11802. case TAKdenormalizegroup:
  11803. filteredRight.kill();
  11804. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11805. break;
  11806. }
  11807. }
  11808. ReleaseRoxieRow(left);
  11809. left = NULL;
  11810. state = JSfillleft;
  11811. if (ret)
  11812. {
  11813. processed++;
  11814. return ret;
  11815. }
  11816. break;
  11817. }
  11818. case JScompare:
  11819. if (joinLimit != 0)
  11820. {
  11821. switch (activityKind)
  11822. {
  11823. case TAKjoin:
  11824. {
  11825. while (right.isItem(rightIndex))
  11826. {
  11827. const void * rhs = right.item(rightIndex++);
  11828. if (helper.match(left, rhs))
  11829. {
  11830. matchedRight.replace(true, rightIndex-1);
  11831. matchedLeft = true;
  11832. if (!exclude)
  11833. {
  11834. const void *ret = joinRecords(left, rhs, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  11835. if (ret)
  11836. {
  11837. processed++;
  11838. joinLimit--;
  11839. return ret;
  11840. }
  11841. }
  11842. }
  11843. }
  11844. break;
  11845. }
  11846. case TAKdenormalize:
  11847. {
  11848. OwnedConstRoxieRow newLeft;
  11849. newLeft.set(left);
  11850. unsigned rowSize = 0;
  11851. unsigned leftCount = 0;
  11852. while (right.isItem(rightIndex) && joinLimit)
  11853. {
  11854. try
  11855. {
  11856. const void * rhs = right.item(rightIndex++);
  11857. if (helper.match(left, rhs))
  11858. {
  11859. matchedRight.replace(true, rightIndex-1);
  11860. matchedLeft = true;
  11861. if (!exclude)
  11862. {
  11863. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11864. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedleft|JTFmatchedright);
  11865. if (thisSize)
  11866. {
  11867. rowSize = thisSize;
  11868. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11869. joinLimit--;
  11870. }
  11871. }
  11872. }
  11873. }
  11874. catch (IException *E)
  11875. {
  11876. throw makeWrappedException(E);
  11877. }
  11878. }
  11879. state = JSleftonly;
  11880. rightIndex = 0;
  11881. if (rowSize)
  11882. {
  11883. processed++;
  11884. return newLeft.getClear();
  11885. }
  11886. break;
  11887. }
  11888. case TAKdenormalizegroup:
  11889. {
  11890. filteredRight.kill();
  11891. while (right.isItem(rightIndex))
  11892. {
  11893. const void * rhs = right.item(rightIndex++);
  11894. if (helper.match(left, rhs))
  11895. {
  11896. matchedRight.replace(true, rightIndex-1);
  11897. filteredRight.append(rhs);
  11898. matchedLeft = true;
  11899. if (filteredRight.ordinality()==joinLimit)
  11900. break;
  11901. }
  11902. }
  11903. state = JSleftonly;
  11904. rightIndex = 0;
  11905. if (!exclude && filteredRight.ordinality())
  11906. {
  11907. const void * ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11908. filteredRight.kill();
  11909. if (ret)
  11910. {
  11911. processed++;
  11912. return ret;
  11913. }
  11914. }
  11915. break;
  11916. }
  11917. }
  11918. }
  11919. state = JSleftonly;
  11920. rightIndex = 0;
  11921. joinCounter = 0;
  11922. break;
  11923. }
  11924. }
  11925. }
  11926. };
  11927. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11928. {
  11929. unsigned input2;
  11930. unsigned input2idx;
  11931. bool forceSpill;
  11932. public:
  11933. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11934. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11935. {
  11936. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11937. input2 = 0;
  11938. input2idx = 0;
  11939. }
  11940. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  11941. {
  11942. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11943. }
  11944. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11945. {
  11946. if (idx==1)
  11947. {
  11948. input2 = source;
  11949. input2idx = sourceidx;
  11950. }
  11951. else
  11952. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11953. }
  11954. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11955. {
  11956. switch (idx)
  11957. {
  11958. case 1:
  11959. sourceidx = input2idx;
  11960. return input2;
  11961. case 0:
  11962. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11963. default:
  11964. return (unsigned) -1;
  11965. }
  11966. }
  11967. virtual unsigned numInputs() const { return 2; }
  11968. virtual const StatisticsMapping &queryStatsMapping() const
  11969. {
  11970. return joinStatistics;
  11971. }
  11972. };
  11973. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11974. {
  11975. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11976. }
  11977. //=================================================================================
  11978. #define CONCAT_READAHEAD 1000
  11979. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11980. {
  11981. public:
  11982. IMPLEMENT_IINTERFACE;
  11983. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11984. : puller(false), ready(_ready), atEog(true), eof(false), grouped(_grouped)
  11985. {
  11986. }
  11987. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieAgentContext *ctx)
  11988. {
  11989. space.reinit(CONCAT_READAHEAD);
  11990. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11991. }
  11992. void stop()
  11993. {
  11994. space.interrupt();
  11995. puller.stop();
  11996. }
  11997. IFinalRoxieInput *queryInput() const
  11998. {
  11999. return puller.queryInput();
  12000. }
  12001. void reset()
  12002. {
  12003. puller.reset();
  12004. ForEachItemIn(idx, buffer)
  12005. ReleaseRoxieRow(buffer.item(idx));
  12006. buffer.clear();
  12007. eof = false;
  12008. atEog = true;
  12009. }
  12010. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  12011. {
  12012. puller.setInput(this, _sourceIdx, _in);
  12013. }
  12014. void connectInputStreams(IRoxieAgentContext *ctx, bool consumerOrdered)
  12015. {
  12016. puller.connectInputStreams(ctx, consumerOrdered);
  12017. }
  12018. virtual void processRow(const void *row)
  12019. {
  12020. buffer.enqueue(row);
  12021. ready.signal();
  12022. space.wait();
  12023. }
  12024. virtual void processGroup(const ConstPointerArray &rows)
  12025. {
  12026. // We use record-by-record input mode of the puller thread even in grouped mode.
  12027. throwUnexpected();
  12028. }
  12029. virtual void processEOG()
  12030. {
  12031. if (grouped)
  12032. processRow(NULL);
  12033. }
  12034. virtual void processDone()
  12035. {
  12036. processRow(NULL);
  12037. }
  12038. virtual bool fireException(IException *e)
  12039. {
  12040. // called from puller thread on failure
  12041. ready.interrupt(LINK(e));
  12042. space.interrupt(e);
  12043. return true;
  12044. }
  12045. bool peek(const void * &row, bool &anyActive)
  12046. {
  12047. if (!eof)
  12048. {
  12049. if (buffer.ordinality())
  12050. {
  12051. space.signal();
  12052. row = buffer.dequeue();
  12053. if (row==NULL)
  12054. {
  12055. if (atEog)
  12056. {
  12057. eof = true;
  12058. return false;
  12059. }
  12060. else
  12061. atEog = true;
  12062. }
  12063. else if (grouped)
  12064. atEog = false;
  12065. return true;
  12066. }
  12067. anyActive = true;
  12068. }
  12069. return false;
  12070. }
  12071. protected:
  12072. RecordPullerThread puller;
  12073. InterruptableSemaphore space;
  12074. InterruptableSemaphore &ready;
  12075. SafeQueueOf<const void, true> buffer;
  12076. bool atEog;
  12077. bool eof;
  12078. bool grouped;
  12079. };
  12080. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  12081. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  12082. {
  12083. InterruptableSemaphore ready;
  12084. ReaderArray pullers;
  12085. unsigned numInputs;
  12086. unsigned nextPuller; // for round robin
  12087. unsigned readyPending;
  12088. bool eof;
  12089. bool inGroup;
  12090. bool grouped;
  12091. public:
  12092. CRoxieServerThreadedConcatActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12093. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  12094. {
  12095. numInputs = _numInputs;
  12096. eof = (numInputs==0);
  12097. inGroup = false;
  12098. nextPuller = 0;
  12099. readyPending = 0;
  12100. for (unsigned i = 0; i < numInputs; i++)
  12101. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  12102. }
  12103. ~CRoxieServerThreadedConcatActivity()
  12104. {
  12105. ForEachItemIn(idx, pullers)
  12106. delete &pullers.item(idx);
  12107. }
  12108. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12109. {
  12110. eof = (numInputs==0);
  12111. inGroup = false;
  12112. nextPuller = 0;
  12113. readyPending = 0;
  12114. ready.reinit();
  12115. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12116. ForEachItemIn(idx, pullers)
  12117. {
  12118. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  12119. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  12120. // in the part of the subgraph that the thread uses has been started.
  12121. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  12122. }
  12123. }
  12124. virtual void stop()
  12125. {
  12126. ready.interrupt();
  12127. ForEachItemIn(idx, pullers)
  12128. pullers.item(idx).stop();
  12129. CRoxieServerActivity::stop();
  12130. }
  12131. virtual unsigned __int64 queryLocalCycles() const
  12132. {
  12133. return 0;
  12134. }
  12135. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12136. {
  12137. if (pullers.isItem(idx))
  12138. return pullers.item(idx).queryInput();
  12139. else
  12140. return NULL;
  12141. }
  12142. virtual void reset()
  12143. {
  12144. CRoxieServerActivity::reset();
  12145. ForEachItemIn(idx, pullers)
  12146. pullers.item(idx).reset();
  12147. eof = false;
  12148. inGroup = false;
  12149. nextPuller = 0;
  12150. readyPending = 0;
  12151. }
  12152. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12153. {
  12154. if (pullers.isItem(idx))
  12155. pullers.item(idx).setInput(_sourceIdx, _in);
  12156. else
  12157. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12158. }
  12159. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12160. {
  12161. ForEachItemIn(i, pullers)
  12162. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  12163. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  12164. }
  12165. virtual const void * nextRow()
  12166. {
  12167. ActivityTimer t(activityStats, timeActivities);
  12168. if (eof)
  12169. return NULL;
  12170. for (;;)
  12171. {
  12172. if (readyPending && !inGroup)
  12173. {
  12174. if (readyPending > 1)
  12175. ready.signal(readyPending-1);
  12176. readyPending = 0;
  12177. }
  12178. else
  12179. ready.wait();
  12180. bool anyActive = false;
  12181. ForEachItemIn(unused_index, pullers)
  12182. {
  12183. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  12184. const void *ret;
  12185. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  12186. if (fetched)
  12187. {
  12188. inGroup = (ret != NULL);
  12189. return ret;
  12190. }
  12191. if (inGroup && grouped)
  12192. {
  12193. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  12194. readyPending++;
  12195. anyActive = true;
  12196. break;
  12197. }
  12198. nextPuller++;
  12199. if (nextPuller==pullers.ordinality())
  12200. nextPuller = 0;
  12201. }
  12202. if (!anyActive)
  12203. break;
  12204. // A ready signal without anything being ready means someone reached end-of-file.
  12205. }
  12206. eof = true;
  12207. return NULL;
  12208. }
  12209. };
  12210. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  12211. {
  12212. IEngineRowStream *curStream;
  12213. bool eogSeen;
  12214. bool anyThisGroup;
  12215. bool grouped;
  12216. unsigned streamIdx;
  12217. public:
  12218. CRoxieServerOrderedConcatActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12219. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12220. {
  12221. eogSeen = false;
  12222. anyThisGroup = false;
  12223. grouped = _grouped;
  12224. streamIdx = 0;
  12225. curStream = NULL;
  12226. }
  12227. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12228. {
  12229. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12230. streamIdx = 0;
  12231. curStream = streamArray[streamIdx];
  12232. eogSeen = false;
  12233. anyThisGroup = false;
  12234. }
  12235. virtual const void * nextRow()
  12236. {
  12237. ActivityTimer t(activityStats, timeActivities);
  12238. if (!curStream)
  12239. return NULL; // eof
  12240. const void * next = curStream->nextRow();
  12241. if (next)
  12242. {
  12243. anyThisGroup = true;
  12244. eogSeen = false;
  12245. processed++;
  12246. return next;
  12247. }
  12248. else if (!eogSeen)
  12249. {
  12250. eogSeen = true;
  12251. if (grouped)
  12252. {
  12253. if (anyThisGroup)
  12254. {
  12255. anyThisGroup = false;
  12256. return NULL;
  12257. }
  12258. else
  12259. return nextRow();
  12260. }
  12261. else
  12262. return nextRow();
  12263. }
  12264. else if (streamIdx < numStreams-1)
  12265. {
  12266. streamIdx++;
  12267. curStream = streamArray[streamIdx];
  12268. eogSeen = false;
  12269. return nextRow();
  12270. }
  12271. else
  12272. {
  12273. curStream = NULL;
  12274. return NULL;
  12275. }
  12276. }
  12277. };
  12278. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  12279. {
  12280. bool ordered;
  12281. bool grouped;
  12282. public:
  12283. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12284. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12285. {
  12286. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  12287. ordered = helper->isOrdered();
  12288. grouped = helper->queryOutputMeta()->isGrouped();
  12289. }
  12290. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12291. {
  12292. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  12293. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12294. else
  12295. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12296. }
  12297. };
  12298. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12299. {
  12300. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12301. }
  12302. //=================================================================================
  12303. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12304. {
  12305. IEngineRowStream* selectedStream;
  12306. unsigned savedParentExtractSize;
  12307. const byte * savedParentExtract;
  12308. bool foundInput;
  12309. bool unusedStopped;
  12310. public:
  12311. CRoxieServerNonEmptyActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12312. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12313. {
  12314. foundInput = false;
  12315. unusedStopped = false;
  12316. selectedStream = NULL;
  12317. savedParentExtractSize = 0;;
  12318. savedParentExtract = NULL;
  12319. }
  12320. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12321. {
  12322. //Don't start the inputs yet so we can short-circuit...
  12323. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12324. savedParentExtractSize = parentExtractSize;
  12325. savedParentExtract = parentExtract;
  12326. }
  12327. virtual void stop()
  12328. {
  12329. if (unusedStopped)
  12330. {
  12331. if (selectedStream)
  12332. selectedStream->stop();
  12333. }
  12334. else
  12335. {
  12336. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12337. for (unsigned i = 0; i < numStreams; i++)
  12338. streamArray[i]->stop();
  12339. }
  12340. CRoxieServerMultiInputBaseActivity::stop();
  12341. }
  12342. virtual void reset()
  12343. {
  12344. CRoxieServerMultiInputBaseActivity::reset();
  12345. foundInput = false;
  12346. unusedStopped = false;
  12347. selectedStream = NULL;
  12348. }
  12349. virtual unsigned __int64 queryLocalCycles() const
  12350. {
  12351. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12352. }
  12353. virtual const void * nextRow()
  12354. {
  12355. ActivityTimer t(activityStats, timeActivities);
  12356. if (!foundInput)
  12357. {
  12358. foundInput = true;
  12359. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12360. //If we get an exception in this loop then stop() will stop any started inputs
  12361. for (unsigned i=0; i < numStreams; i++)
  12362. {
  12363. selectedStream = streamArray[i];
  12364. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12365. startJunction(junctionArray[i]);
  12366. const void * next = selectedStream->nextRow();
  12367. if (next)
  12368. {
  12369. //Found a row so stop remaining
  12370. for (unsigned j=i+1; j < numInputs; j++)
  12371. streamArray[j]->stop();
  12372. unusedStopped = true;
  12373. processed++;
  12374. return next;
  12375. }
  12376. selectedStream->stop();
  12377. }
  12378. unusedStopped = true;
  12379. selectedStream = NULL;
  12380. return NULL;
  12381. }
  12382. if (!selectedStream)
  12383. return NULL;
  12384. const void * next = selectedStream->nextRow();
  12385. if (next)
  12386. processed++;
  12387. return next;
  12388. }
  12389. };
  12390. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12391. {
  12392. public:
  12393. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12394. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12395. {
  12396. }
  12397. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12398. {
  12399. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12400. }
  12401. };
  12402. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12403. {
  12404. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12405. }
  12406. //=================================================================================
  12407. class SingleNodeActivityContext : public IThorActivityContext
  12408. {
  12409. public:
  12410. SingleNodeActivityContext(unsigned _numStrands, unsigned _curStrand) : strands(_numStrands), curStrand(_curStrand) { assertex(curStrand < strands); }
  12411. virtual bool isLocal() const override { return false; }
  12412. virtual unsigned numSlaves() const override { return 1; }
  12413. virtual unsigned numStrands() const override { return strands; }
  12414. virtual unsigned querySlave() const override { return 0; }
  12415. virtual unsigned queryStrand() const override { return curStrand; }
  12416. protected:
  12417. unsigned strands;
  12418. unsigned curStrand;
  12419. };
  12420. class CRoxieServerExternalActivity : public CRoxieServerMultiInputActivity
  12421. {
  12422. Owned<IRowStream> rows;
  12423. SingleNodeActivityContext activityContext;
  12424. public:
  12425. CRoxieServerExternalActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12426. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), activityContext(1, 0)
  12427. {
  12428. }
  12429. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  12430. {
  12431. Owned<IStrandJunction> junction = CRoxieServerMultiInputActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12432. associateInputsWithHelper();
  12433. return junction.getClear();
  12434. }
  12435. virtual void connectInputStreams(bool consumerOrdered)
  12436. {
  12437. CRoxieServerMultiInputActivity::connectInputStreams(consumerOrdered);
  12438. associateInputsWithHelper();
  12439. }
  12440. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12441. {
  12442. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12443. if (factory->getKind() != TAKexternalsink)
  12444. {
  12445. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12446. rows.setown(helper.createOutput(&activityContext));
  12447. }
  12448. }
  12449. virtual void stop()
  12450. {
  12451. if (rows)
  12452. {
  12453. rows->stop();
  12454. rows.clear();
  12455. }
  12456. CRoxieServerMultiInputActivity::stop();
  12457. }
  12458. virtual void reset()
  12459. {
  12460. rows.clear();
  12461. CRoxieServerMultiInputActivity::reset();
  12462. }
  12463. virtual const void * nextRow()
  12464. {
  12465. ActivityTimer t(activityStats, timeActivities);
  12466. assertex(rows);
  12467. const void * next = rows->nextRow();
  12468. if (next)
  12469. processed++;
  12470. return next;
  12471. }
  12472. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  12473. {
  12474. try
  12475. {
  12476. start(parentExtractSize, parentExtract, false);
  12477. assertex(!rows);
  12478. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12479. helper.execute(&activityContext);
  12480. stop();
  12481. }
  12482. catch (IException * E)
  12483. {
  12484. ctx->notifyAbort(E);
  12485. abort();
  12486. throw;
  12487. }
  12488. }
  12489. protected:
  12490. void associateInputsWithHelper()
  12491. {
  12492. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12493. for (unsigned i = 0; i < numInputs; i++)
  12494. helper.setInput(i, streamArray[i]);
  12495. }
  12496. };
  12497. class CRoxieServerExternalActivityFactory : public CRoxieServerMultiInputFactory
  12498. {
  12499. bool isRoot;
  12500. public:
  12501. CRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12502. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  12503. {
  12504. }
  12505. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12506. {
  12507. return new CRoxieServerExternalActivity(_ctx, this, _probeManager, numInputs());
  12508. }
  12509. virtual bool isSink() const
  12510. {
  12511. return (kind == TAKexternalsink) && isRoot;
  12512. }
  12513. };
  12514. IRoxieServerActivityFactory *createRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12515. {
  12516. return new CRoxieServerExternalActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  12517. }
  12518. //=================================================================================
  12519. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12520. {
  12521. IHThorMergeArg &helper;
  12522. unsigned *mergeheap;
  12523. unsigned activeInputs;
  12524. const void **pending;
  12525. bool first;
  12526. ICompare *compare;
  12527. bool dedup;
  12528. void permute()
  12529. {
  12530. assertex(activeInputs == 0);
  12531. for(unsigned i = 0; i < numStreams; i++)
  12532. if(pullInput(i))
  12533. mergeheap[activeInputs++] = i;
  12534. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12535. // the heap property: no element should be smaller than its parent
  12536. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12537. // 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
  12538. if (activeInputs >= 2)
  12539. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12540. siftDown(p);
  12541. if(dedup)
  12542. siftDownDedupTop();
  12543. else
  12544. siftDown(0);
  12545. }
  12546. void readNext()
  12547. {
  12548. if(!pullInput(mergeheap[0]))
  12549. if(!promote(0))
  12550. return;
  12551. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12552. if(dedup)
  12553. siftDownDedupTop();
  12554. else
  12555. siftDown(0);
  12556. }
  12557. bool pullInput(unsigned i)
  12558. {
  12559. const void *next = streamArray[i]->ungroupedNextRow();
  12560. pending[i] = next;
  12561. return (next != NULL);
  12562. }
  12563. bool promote(unsigned p)
  12564. {
  12565. activeInputs--;
  12566. if(activeInputs == p)
  12567. return false;
  12568. mergeheap[p] = mergeheap[activeInputs];
  12569. return true;
  12570. }
  12571. bool siftDown(unsigned p)
  12572. {
  12573. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12574. bool nochange = true;
  12575. while(1)
  12576. {
  12577. unsigned c = p*2 + 1;
  12578. if(c >= activeInputs)
  12579. return nochange;
  12580. if(c+1 < activeInputs)
  12581. {
  12582. int childcmp = BuffCompare(c+1, c);
  12583. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12584. ++c;
  12585. }
  12586. int cmp = BuffCompare(c, p);
  12587. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12588. return nochange;
  12589. nochange = false;
  12590. unsigned r = mergeheap[c];
  12591. mergeheap[c] = mergeheap[p];
  12592. mergeheap[p] = r;
  12593. p = c;
  12594. }
  12595. }
  12596. void siftDownDedupTop()
  12597. {
  12598. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12599. if(activeInputs < 2)
  12600. return;
  12601. unsigned c = 1;
  12602. int childcmp = 1;
  12603. if(activeInputs >= 3)
  12604. {
  12605. childcmp = BuffCompare(2, 1);
  12606. if(childcmp < 0)
  12607. c = 2;
  12608. }
  12609. int cmp = BuffCompare(c, 0);
  12610. if(cmp > 0)
  12611. return;
  12612. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12613. while(cmp <= 0)
  12614. {
  12615. if(cmp == 0)
  12616. {
  12617. if(mergeheap[c] < mergeheap[0])
  12618. {
  12619. unsigned r = mergeheap[c];
  12620. mergeheap[c] = mergeheap[0];
  12621. mergeheap[0] = r;
  12622. }
  12623. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12624. if(!pullInput(mergeheap[c]))
  12625. if(!promote(c))
  12626. break;
  12627. siftDown(c);
  12628. }
  12629. else
  12630. {
  12631. unsigned r = mergeheap[c];
  12632. mergeheap[c] = mergeheap[0];
  12633. mergeheap[0] = r;
  12634. if(siftDown(c))
  12635. break;
  12636. }
  12637. cmp = BuffCompare(c, 0);
  12638. }
  12639. // the following loop ensures the uniqueness property holds on the other branch too
  12640. c = 3-c;
  12641. if(activeInputs <= c)
  12642. return;
  12643. while(childcmp == 0)
  12644. {
  12645. if(mergeheap[c] < mergeheap[0])
  12646. {
  12647. unsigned r = mergeheap[c];
  12648. mergeheap[c] = mergeheap[0];
  12649. mergeheap[0] = r;
  12650. }
  12651. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12652. if(!pullInput(mergeheap[c]))
  12653. if(!promote(c))
  12654. break;
  12655. siftDown(c);
  12656. childcmp = BuffCompare(c, 0);
  12657. }
  12658. }
  12659. inline int BuffCompare(unsigned a, unsigned b)
  12660. {
  12661. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12662. }
  12663. public:
  12664. CRoxieServerMergeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12665. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12666. {
  12667. activeInputs = 0;
  12668. first = true;
  12669. mergeheap = new unsigned[numInputs];
  12670. pending = new const void *[numStreams];
  12671. compare = helper.queryCompare();
  12672. dedup = helper.dedup();
  12673. for (unsigned i = 0; i < numStreams; i++)
  12674. pending[i] = NULL;
  12675. }
  12676. ~CRoxieServerMergeActivity()
  12677. {
  12678. delete [] mergeheap;
  12679. delete [] pending;
  12680. }
  12681. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12682. {
  12683. activeInputs = 0;
  12684. first = true;
  12685. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12686. }
  12687. virtual void reset()
  12688. {
  12689. for (unsigned i = 0; i < numStreams; i++)
  12690. ReleaseClearRoxieRow(pending[i]);
  12691. CRoxieServerMultiInputActivity::reset();
  12692. }
  12693. virtual const void * nextRow()
  12694. {
  12695. ActivityTimer t(activityStats, timeActivities);
  12696. if (first)
  12697. {
  12698. permute();
  12699. first = false;
  12700. }
  12701. if (activeInputs)
  12702. {
  12703. const void *next = pending[mergeheap[0]];
  12704. readNext();
  12705. if (next)
  12706. processed++;
  12707. return next;
  12708. }
  12709. else
  12710. return NULL;
  12711. }
  12712. };
  12713. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12714. {
  12715. public:
  12716. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12717. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12718. {
  12719. }
  12720. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12721. {
  12722. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12723. }
  12724. };
  12725. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12726. {
  12727. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12728. }
  12729. //=================================================================================
  12730. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12731. {
  12732. unsigned streamIndex;
  12733. bool eof;
  12734. unsigned __int64 numProcessedLastGroup;
  12735. public:
  12736. CRoxieServerRegroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12737. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12738. {
  12739. streamIndex = 0;
  12740. eof = false;
  12741. numProcessedLastGroup = 0;
  12742. }
  12743. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12744. {
  12745. streamIndex = 0;
  12746. eof = false;
  12747. numProcessedLastGroup = processed;
  12748. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12749. }
  12750. const void * nextFromInputs()
  12751. {
  12752. unsigned initialStream = streamIndex;
  12753. while (streamIndex < numStreams)
  12754. {
  12755. const void * next = streamArray[streamIndex]->nextRow();
  12756. if (next)
  12757. {
  12758. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12759. {
  12760. ReleaseRoxieRow(next);
  12761. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12762. }
  12763. return next;
  12764. }
  12765. streamIndex++;
  12766. }
  12767. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12768. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12769. streamIndex = 0;
  12770. return NULL;
  12771. }
  12772. virtual const void * nextRow()
  12773. {
  12774. ActivityTimer t(activityStats, timeActivities);
  12775. if (eof)
  12776. return NULL;
  12777. const void * ret = nextFromInputs();
  12778. if (ret)
  12779. {
  12780. processed++;
  12781. return ret;
  12782. }
  12783. if (numProcessedLastGroup != processed)
  12784. {
  12785. numProcessedLastGroup = processed;
  12786. return NULL;
  12787. }
  12788. eof = true;
  12789. return NULL;
  12790. }
  12791. };
  12792. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12793. {
  12794. public:
  12795. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12796. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12797. {
  12798. }
  12799. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12800. {
  12801. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12802. }
  12803. };
  12804. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12805. {
  12806. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12807. }
  12808. //=================================================================================
  12809. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12810. {
  12811. IHThorCombineArg &helper;
  12812. unsigned __int64 numProcessedLastGroup;
  12813. public:
  12814. CRoxieServerCombineActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12815. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12816. {
  12817. numProcessedLastGroup = 0;
  12818. }
  12819. ~CRoxieServerCombineActivity()
  12820. {
  12821. }
  12822. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12823. {
  12824. numProcessedLastGroup = processed;
  12825. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12826. }
  12827. void nextInputs(ConstPointerArray & out)
  12828. {
  12829. for (unsigned i=0; i < numStreams; i++)
  12830. {
  12831. const void * next = streamArray[i]->nextRow();
  12832. if (next)
  12833. out.append(next);
  12834. }
  12835. }
  12836. virtual bool needsAllocator() const { return true; }
  12837. virtual const void * nextRow()
  12838. {
  12839. ActivityTimer t(activityStats, timeActivities);
  12840. for (;;)
  12841. {
  12842. ConstPointerArray group;
  12843. nextInputs(group);
  12844. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12845. nextInputs(group);
  12846. if (group.ordinality() == 0)
  12847. {
  12848. numProcessedLastGroup = processed;
  12849. return NULL;
  12850. }
  12851. else if (group.ordinality() != numInputs)
  12852. {
  12853. ReleaseRoxieRows(group);
  12854. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12855. }
  12856. try
  12857. {
  12858. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12859. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12860. ReleaseRoxieRows(group);
  12861. if (outSize)
  12862. {
  12863. processed++;
  12864. return rowBuilder.finalizeRowClear(outSize);
  12865. }
  12866. }
  12867. catch (IException *E)
  12868. {
  12869. ReleaseRoxieRows(group);
  12870. throw makeWrappedException(E);
  12871. }
  12872. }
  12873. }
  12874. };
  12875. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12876. {
  12877. public:
  12878. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12879. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12880. {
  12881. }
  12882. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12883. {
  12884. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12885. }
  12886. };
  12887. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12888. {
  12889. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12890. }
  12891. //=================================================================================
  12892. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12893. {
  12894. IHThorCombineGroupArg &helper;
  12895. unsigned __int64 numProcessedLastGroup;
  12896. public:
  12897. CRoxieServerCombineGroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12898. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12899. {
  12900. numProcessedLastGroup = 0;
  12901. }
  12902. ~CRoxieServerCombineGroupActivity()
  12903. {
  12904. }
  12905. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12906. {
  12907. numProcessedLastGroup = processed;
  12908. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12909. }
  12910. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12911. {
  12912. if (idx==(unsigned)-1)
  12913. idx = 0;
  12914. return idx ? NULL : this;
  12915. }
  12916. virtual bool needsAllocator() const { return true; }
  12917. virtual const void * nextRow()
  12918. {
  12919. ActivityTimer t(activityStats, timeActivities);
  12920. for (;;)
  12921. {
  12922. const void * left = inputStream->nextRow();
  12923. if (!left && (numProcessedLastGroup == processed))
  12924. left = inputStream->nextRow();
  12925. if (!left)
  12926. {
  12927. if (numProcessedLastGroup == processed)
  12928. {
  12929. const void * nextRight = inputStream1->nextRow();
  12930. if (nextRight)
  12931. {
  12932. ReleaseRoxieRow(nextRight);
  12933. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12934. }
  12935. }
  12936. else
  12937. numProcessedLastGroup = processed;
  12938. return NULL;
  12939. }
  12940. ConstPointerArray group;
  12941. for (;;)
  12942. {
  12943. const void * in = inputStream1->nextRow();
  12944. if (!in)
  12945. break;
  12946. group.append(in);
  12947. }
  12948. if (group.ordinality() == 0)
  12949. {
  12950. ReleaseRoxieRow(left);
  12951. ReleaseRoxieRows(group);
  12952. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12953. }
  12954. try
  12955. {
  12956. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12957. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12958. ReleaseRoxieRow(left);
  12959. ReleaseRoxieRows(group);
  12960. if (outSize)
  12961. {
  12962. processed++;
  12963. return rowBuilder.finalizeRowClear(outSize);
  12964. }
  12965. }
  12966. catch (IException *E)
  12967. {
  12968. ReleaseRoxieRow(left);
  12969. ReleaseRoxieRows(group);
  12970. throw makeWrappedException(E);
  12971. }
  12972. }
  12973. }
  12974. };
  12975. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12976. {
  12977. unsigned input2;
  12978. unsigned input2idx;
  12979. public:
  12980. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12981. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12982. {
  12983. input2 = 0;
  12984. input2idx = 0;
  12985. }
  12986. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  12987. {
  12988. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12989. }
  12990. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12991. {
  12992. if (idx==1)
  12993. {
  12994. input2 = source;
  12995. input2idx = sourceidx;
  12996. }
  12997. else
  12998. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12999. }
  13000. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13001. {
  13002. switch (idx)
  13003. {
  13004. case 1:
  13005. sourceidx = input2idx;
  13006. return input2;
  13007. case 0:
  13008. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  13009. default:
  13010. return (unsigned) -1;
  13011. }
  13012. }
  13013. virtual unsigned numInputs() const { return 2; }
  13014. };
  13015. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13016. {
  13017. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13018. }
  13019. //=================================================================================
  13020. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  13021. {
  13022. IHThorRollupGroupArg &helper;
  13023. bool eof;
  13024. public:
  13025. CRoxieServerRollupGroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  13026. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13027. helper((IHThorRollupGroupArg &)basehelper)
  13028. {
  13029. eof = false;
  13030. }
  13031. ~CRoxieServerRollupGroupActivity()
  13032. {
  13033. }
  13034. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13035. {
  13036. eof = false;
  13037. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13038. }
  13039. virtual bool needsAllocator() const { return true; }
  13040. virtual const void * nextRow()
  13041. {
  13042. ActivityTimer t(activityStats, timeActivities);
  13043. if (eof)
  13044. return NULL;
  13045. for (;;)
  13046. {
  13047. ConstPointerArray group;
  13048. for (;;)
  13049. {
  13050. const void * in = inputStream->nextRow();
  13051. if (!in)
  13052. break;
  13053. group.append(in);
  13054. }
  13055. if (group.ordinality() == 0)
  13056. {
  13057. eof = true;
  13058. return NULL;
  13059. }
  13060. try
  13061. {
  13062. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13063. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  13064. ReleaseRoxieRows(group);
  13065. if (outSize)
  13066. {
  13067. processed++;
  13068. return rowBuilder.finalizeRowClear(outSize);
  13069. }
  13070. }
  13071. catch (IException * E)
  13072. {
  13073. ReleaseRoxieRows(group);
  13074. throw makeWrappedException(E);
  13075. }
  13076. }
  13077. }
  13078. };
  13079. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  13080. {
  13081. public:
  13082. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13083. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13084. {
  13085. }
  13086. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  13087. {
  13088. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  13089. }
  13090. };
  13091. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13092. {
  13093. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13094. }
  13095. //=================================================================================
  13096. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  13097. {
  13098. IHThorFilterProjectArg &helper;
  13099. unsigned numProcessedLastGroup;
  13100. unsigned __int64 recordCount;
  13101. public:
  13102. CRoxieServerFilterProjectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  13103. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  13104. {
  13105. numProcessedLastGroup = 0;
  13106. recordCount = 0;
  13107. }
  13108. ~CRoxieServerFilterProjectActivity()
  13109. {
  13110. }
  13111. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13112. {
  13113. numProcessedLastGroup = 0;
  13114. recordCount = 0;
  13115. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  13116. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  13117. }
  13118. virtual bool needsAllocator() const { return true; }
  13119. virtual const void * nextRow()
  13120. {
  13121. ActivityTimer t(activityStats, timeActivities);
  13122. if (eof)
  13123. return NULL;
  13124. for (;;)
  13125. {
  13126. const void * in = inputStream->nextRow();
  13127. if (!in)
  13128. {
  13129. recordCount = 0;
  13130. if (numProcessedLastGroup == processed)
  13131. in = inputStream->nextRow();
  13132. if (!in)
  13133. {
  13134. numProcessedLastGroup = processed;
  13135. return NULL;
  13136. }
  13137. }
  13138. try
  13139. {
  13140. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13141. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  13142. ReleaseRoxieRow(in);
  13143. if (outSize)
  13144. {
  13145. processed++;
  13146. return rowBuilder.finalizeRowClear(outSize);
  13147. }
  13148. }
  13149. catch (IException *E)
  13150. {
  13151. throw makeWrappedException(E);
  13152. }
  13153. }
  13154. }
  13155. };
  13156. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  13157. {
  13158. public:
  13159. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13160. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13161. {
  13162. //MORE: Code generator needs to indicate if the count is used.
  13163. //optStableInput = false;
  13164. }
  13165. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  13166. {
  13167. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  13168. }
  13169. };
  13170. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13171. {
  13172. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13173. }
  13174. //=====================================================
  13175. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  13176. {
  13177. class ProjectProcessor : public StrandProcessor
  13178. {
  13179. protected:
  13180. IHThorProjectArg &helper;
  13181. public:
  13182. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  13183. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  13184. {
  13185. }
  13186. virtual const void * nextRow()
  13187. {
  13188. ActivityTimer t(activityStats, timeActivities);
  13189. for (;;)
  13190. {
  13191. OwnedConstRoxieRow in = inputStream->nextRow();
  13192. if (!in)
  13193. {
  13194. if (numProcessedLastGroup == processed)
  13195. in.setown(inputStream->nextRow());
  13196. if (!in)
  13197. {
  13198. numProcessedLastGroup = processed;
  13199. return NULL;
  13200. }
  13201. }
  13202. try
  13203. {
  13204. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13205. size32_t outSize;
  13206. outSize = helper.transform(rowBuilder, in);
  13207. if (outSize)
  13208. {
  13209. processed++;
  13210. return rowBuilder.finalizeRowClear(outSize);
  13211. }
  13212. }
  13213. catch (IException *E)
  13214. {
  13215. throw parent.makeWrappedException(E);
  13216. }
  13217. }
  13218. }
  13219. };
  13220. public:
  13221. CRoxieServerStrandedProjectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  13222. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  13223. {
  13224. }
  13225. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13226. {
  13227. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  13228. onStartStrands();
  13229. }
  13230. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  13231. {
  13232. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  13233. }
  13234. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  13235. };
  13236. class CRoxieServerProjectActivity : public CRoxieServerActivity
  13237. {
  13238. unsigned numProcessedLastGroup;
  13239. unsigned __int64 recordCount;
  13240. bool count;
  13241. public:
  13242. CRoxieServerProjectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13243. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13244. count(_count)
  13245. {
  13246. numProcessedLastGroup = 0;
  13247. recordCount = 0;
  13248. }
  13249. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13250. {
  13251. numProcessedLastGroup = 0;
  13252. recordCount = 0;
  13253. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13254. }
  13255. virtual bool needsAllocator() const { return true; }
  13256. virtual const void * nextRow()
  13257. {
  13258. ActivityTimer t(activityStats, timeActivities);
  13259. for (;;)
  13260. {
  13261. OwnedConstRoxieRow in = inputStream->nextRow();
  13262. if (!in)
  13263. {
  13264. recordCount = 0;
  13265. if (numProcessedLastGroup == processed)
  13266. in.setown(inputStream->nextRow());
  13267. if (!in)
  13268. {
  13269. numProcessedLastGroup = processed;
  13270. return NULL;
  13271. }
  13272. }
  13273. try
  13274. {
  13275. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13276. size32_t outSize;
  13277. if (count)
  13278. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  13279. else
  13280. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  13281. if (outSize)
  13282. {
  13283. processed++;
  13284. return rowBuilder.finalizeRowClear(outSize);
  13285. }
  13286. }
  13287. catch (IException *E)
  13288. {
  13289. throw makeWrappedException(E);
  13290. }
  13291. }
  13292. }
  13293. };
  13294. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  13295. {
  13296. protected:
  13297. StrandOptions strandOptions;
  13298. bool count;
  13299. public:
  13300. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13301. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  13302. {
  13303. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  13304. optStableInput = count;
  13305. }
  13306. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  13307. {
  13308. // NOTE - if they explicitly requested numStrands = 1 via hint, we could use either of the below. For now use the stranded version to ensure it is tested.
  13309. if (kind == TAKproject) // Not supported on prefetch or count projects
  13310. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  13311. else
  13312. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  13313. }
  13314. };
  13315. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13316. {
  13317. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13318. }
  13319. //=================================================================================
  13320. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  13321. {
  13322. unsigned numProcessedLastGroup;
  13323. bool eof;
  13324. bool allPulled;
  13325. bool isThreaded;
  13326. unsigned preload;
  13327. unsigned __int64 recordCount;
  13328. IHThorPrefetchProjectArg &helper;
  13329. RecordPullerThread puller;
  13330. InterruptableSemaphore ready;
  13331. InterruptableSemaphore space;
  13332. class PrefetchInfo : public CInterface
  13333. {
  13334. public:
  13335. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  13336. {
  13337. if (helper.preTransform(extract, _in, _recordCount))
  13338. {
  13339. in.setown(_in);
  13340. recordCount = _recordCount;
  13341. }
  13342. else
  13343. {
  13344. ReleaseRoxieRow(_in);
  13345. recordCount = 0;
  13346. }
  13347. }
  13348. OwnedConstRoxieRow in;
  13349. unsigned __int64 recordCount;
  13350. rtlRowBuilder extract;
  13351. };
  13352. QueueOf<PrefetchInfo, true> pulled;
  13353. CriticalSection pulledCrit;
  13354. public:
  13355. CRoxieServerPrefetchProjectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  13356. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13357. helper((IHThorPrefetchProjectArg &) basehelper),
  13358. puller(false)
  13359. {
  13360. numProcessedLastGroup = 0;
  13361. recordCount = 0;
  13362. eof = false;
  13363. allPulled = false;
  13364. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  13365. preload = 0;
  13366. }
  13367. ~CRoxieServerPrefetchProjectActivity()
  13368. {
  13369. while (pulled.ordinality())
  13370. ::Release(pulled.dequeue());
  13371. }
  13372. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13373. {
  13374. if (idx)
  13375. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13376. puller.setInput(this, _sourceIdx, _in);
  13377. }
  13378. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13379. {
  13380. puller.connectInputStreams(ctx, consumerOrdered);
  13381. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  13382. }
  13383. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13384. {
  13385. if (idx==0)
  13386. return puller.queryInput();
  13387. else
  13388. return NULL;
  13389. }
  13390. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13391. {
  13392. numProcessedLastGroup = 0;
  13393. recordCount = 0;
  13394. eof = false;
  13395. allPulled = false;
  13396. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13397. preload = helper.getLookahead();
  13398. if (!preload)
  13399. preload = ctx->queryOptions().prefetchProjectPreload;
  13400. space.reinit(preload);
  13401. ready.reinit();
  13402. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  13403. }
  13404. virtual void stop()
  13405. {
  13406. space.interrupt();
  13407. ready.interrupt();
  13408. CRoxieServerActivity::stop();
  13409. puller.stop();
  13410. }
  13411. virtual void reset()
  13412. {
  13413. CRoxieServerActivity::reset();
  13414. puller.reset();
  13415. allPulled = false;
  13416. while (pulled.ordinality())
  13417. ::Release(pulled.dequeue());
  13418. }
  13419. virtual PrefetchInfo *readNextRecord()
  13420. {
  13421. if (!isThreaded)
  13422. {
  13423. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13424. puller.pullRecords(1);
  13425. }
  13426. else
  13427. ready.wait();
  13428. CriticalBlock b(pulledCrit);
  13429. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13430. space.signal();
  13431. return ret;
  13432. }
  13433. virtual bool needsAllocator() const { return true; }
  13434. virtual const void * nextRow()
  13435. {
  13436. ActivityTimer t(activityStats, timeActivities);
  13437. if (eof)
  13438. return NULL;
  13439. for (;;)
  13440. {
  13441. Owned<PrefetchInfo> in = readNextRecord();
  13442. if (!in)
  13443. {
  13444. recordCount = 0;
  13445. if (numProcessedLastGroup == processed)
  13446. in.setown(readNextRecord());
  13447. if (!in)
  13448. {
  13449. numProcessedLastGroup = processed;
  13450. eof = true;
  13451. return NULL;
  13452. }
  13453. }
  13454. try
  13455. {
  13456. if (in->in)
  13457. {
  13458. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13459. size32_t outSize;
  13460. IThorChildGraph *child = helper.queryChild();
  13461. Owned<IEclGraphResults> results;
  13462. if (child)
  13463. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13464. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13465. if (outSize)
  13466. {
  13467. processed++;
  13468. return rowBuilder.finalizeRowClear(outSize);
  13469. }
  13470. }
  13471. }
  13472. catch (IException *E)
  13473. {
  13474. throw makeWrappedException(E);
  13475. }
  13476. }
  13477. }
  13478. // interface IExceptionHandler
  13479. virtual bool fireException(IException *e)
  13480. {
  13481. // called from puller thread on failure
  13482. ready.interrupt(LINK(e));
  13483. space.interrupt(e);
  13484. return true;
  13485. }
  13486. // interface IRecordPullerCallback
  13487. virtual void processRow(const void *row)
  13488. {
  13489. {
  13490. CriticalBlock b(pulledCrit);
  13491. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13492. }
  13493. if (isThreaded)
  13494. {
  13495. ready.signal();
  13496. space.wait();
  13497. }
  13498. }
  13499. virtual void processEOG()
  13500. {
  13501. {
  13502. CriticalBlock b(pulledCrit);
  13503. pulled.enqueue(NULL);
  13504. }
  13505. if (isThreaded)
  13506. {
  13507. ready.signal();
  13508. space.wait();
  13509. }
  13510. }
  13511. virtual void processGroup(const ConstPointerArray &rows)
  13512. {
  13513. throwUnexpected();
  13514. }
  13515. virtual void processDone()
  13516. {
  13517. CriticalBlock b(pulledCrit);
  13518. allPulled = true;
  13519. if (isThreaded)
  13520. ready.signal();
  13521. }
  13522. };
  13523. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13524. {
  13525. public:
  13526. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13527. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13528. {
  13529. }
  13530. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  13531. {
  13532. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager);
  13533. }
  13534. };
  13535. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13536. {
  13537. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13538. }
  13539. //=================================================================================
  13540. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13541. {
  13542. public:
  13543. CPointerArrayRoxieInput()
  13544. {
  13545. rowset = NULL;
  13546. rowcount = 0;
  13547. curRow = 0;
  13548. }
  13549. void init(size32_t _rowcount, const byte **_rowset)
  13550. {
  13551. rowset = _rowset;
  13552. rowcount = _rowcount;
  13553. curRow = 0;
  13554. }
  13555. virtual const void * nextRow()
  13556. {
  13557. if (curRow < rowcount)
  13558. {
  13559. const void * ret = rowset[curRow];
  13560. if (ret)
  13561. LinkRoxieRow(ret);
  13562. curRow++;
  13563. return ret;
  13564. }
  13565. return NULL;
  13566. }
  13567. protected:
  13568. const byte **rowset;
  13569. size32_t rowcount;
  13570. size32_t curRow;
  13571. };
  13572. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13573. {
  13574. protected:
  13575. IHThorLoopArg &helper;
  13576. ThorActivityKind activityKind;
  13577. unsigned maxIterations;
  13578. bool finishedLooping;
  13579. unsigned flags;
  13580. bool eof;
  13581. rtlRowBuilder loopExtractBuilder;
  13582. unsigned loopGraphId;
  13583. Linked<IOutputMetaData> counterMeta;
  13584. public:
  13585. CRoxieServerLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13586. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13587. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13588. {
  13589. eof = false;
  13590. finishedLooping = false;
  13591. activityKind = factory->getKind();
  13592. flags = helper.getFlags();
  13593. maxIterations = 0;
  13594. }
  13595. virtual bool needsAllocator() const { return true; }
  13596. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13597. {
  13598. eof = false;
  13599. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13600. int iterations = (int) helper.numIterations();
  13601. maxIterations = (iterations >= 0) ? iterations : 0;
  13602. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13603. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13604. finishedLooping = true;
  13605. loopExtractBuilder.clear();
  13606. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13607. }
  13608. virtual void stop()
  13609. {
  13610. CRoxieServerActivity::stop();
  13611. loopExtractBuilder.clear();
  13612. }
  13613. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13614. {
  13615. if (flags & IHThorLoopArg::LFcounter)
  13616. {
  13617. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13618. *((thor_loop_counter_t *)counterRow) = counter;
  13619. RtlLinkedDatasetBuilder builder(rowAllocator);
  13620. builder.appendOwn(counterRow);
  13621. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13622. graph->setInputResult(2, counterResult);
  13623. }
  13624. }
  13625. };
  13626. //=================================================================================
  13627. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13628. {
  13629. Owned<IActivityGraph> loopQuery;
  13630. Owned<IRoxieServerChildGraph> loopGraph;
  13631. IEngineRowStream * curStream;
  13632. RtlLinkedDatasetBuilder *loopInputBuilder;
  13633. CPointerArrayRoxieInput arrayInput;
  13634. Linked<IEngineRowStream> resultStream;
  13635. unsigned loopCounter;
  13636. public:
  13637. CRoxieServerSequentialLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13638. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13639. {
  13640. curStream = NULL;
  13641. loopCounter = 0;
  13642. loopInputBuilder = NULL;
  13643. }
  13644. virtual bool needsAllocator() const { return true; }
  13645. virtual void onCreate(IHThorArg *_colocalParent)
  13646. {
  13647. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13648. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13649. }
  13650. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13651. {
  13652. curStream = inputStream;
  13653. loopCounter = 1;
  13654. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13655. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13656. loopGraph.set(loopQuery->queryLoopGraph());
  13657. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13658. }
  13659. virtual void stop()
  13660. {
  13661. delete loopInputBuilder;
  13662. loopInputBuilder = NULL;
  13663. CRoxieServerLoopActivity::stop();
  13664. }
  13665. virtual const void * nextRow()
  13666. {
  13667. ActivityTimer t(activityStats, timeActivities);
  13668. if (eof)
  13669. return NULL;
  13670. unsigned emptyIterations = 0;
  13671. for (;;)
  13672. {
  13673. for (;;)
  13674. {
  13675. const void * ret = curStream->nextRow();
  13676. if (!ret)
  13677. {
  13678. ret = curStream->nextRow(); // more cope with groups somehow....
  13679. if (!ret)
  13680. {
  13681. if (finishedLooping)
  13682. {
  13683. eof = true;
  13684. return NULL;
  13685. }
  13686. break;
  13687. }
  13688. }
  13689. if (finishedLooping ||
  13690. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13691. {
  13692. processed++;
  13693. return ret;
  13694. }
  13695. loopInputBuilder->appendOwn(ret);
  13696. }
  13697. switch (activityKind)
  13698. {
  13699. case TAKloopdataset:
  13700. {
  13701. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13702. {
  13703. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13704. {
  13705. if (loopInputBuilder->getcount() == 0)
  13706. {
  13707. eof = true;
  13708. return NULL;
  13709. }
  13710. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13711. // MORE - should builder be cleared here?
  13712. curStream = &arrayInput;
  13713. finishedLooping = true;
  13714. continue; // back to the input loop again
  13715. }
  13716. }
  13717. break;
  13718. }
  13719. case TAKlooprow:
  13720. if (!loopInputBuilder->getcount())
  13721. {
  13722. finishedLooping = true;
  13723. eof = true;
  13724. return NULL;
  13725. }
  13726. break;
  13727. }
  13728. if (loopInputBuilder->getcount())
  13729. emptyIterations = 0;
  13730. else
  13731. {
  13732. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13733. emptyIterations++;
  13734. if (emptyIterations > maxEmptyLoopIterations)
  13735. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13736. if (emptyIterations % 32 == 0)
  13737. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13738. }
  13739. checkAbort();
  13740. try
  13741. {
  13742. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13743. resultStream.setown(results->createIterator(0));
  13744. if (flags & IHThorLoopArg::LFnewloopagain)
  13745. {
  13746. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13747. OwnedConstRoxieRow row = againResult->nextRow();
  13748. assertex(row);
  13749. //Result is a row which contains a single boolean field.
  13750. if (!((const bool *)row.get())[0])
  13751. finishedLooping = true;
  13752. }
  13753. }
  13754. catch (IException *E)
  13755. {
  13756. throw makeWrappedException(E);
  13757. }
  13758. curStream = resultStream.get();
  13759. loopCounter++;
  13760. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13761. finishedLooping = true;
  13762. }
  13763. }
  13764. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13765. {
  13766. try
  13767. {
  13768. loopGraph->beforeExecute();
  13769. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13770. loopInputBuilder->clear();
  13771. loopGraph->setInputResult(1, inputRowsResult);
  13772. createCounterResult(loopGraph, counter);
  13773. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13774. loopGraph->afterExecute();
  13775. return ret.getClear();
  13776. }
  13777. catch (...)
  13778. {
  13779. CTXLOG("Exception thrown in loop body - cleaning up");
  13780. loopGraph->afterExecute();
  13781. throw;
  13782. }
  13783. }
  13784. };
  13785. //=================================================================================
  13786. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13787. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13788. {
  13789. public:
  13790. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13791. : input(_input), meta(_meta)
  13792. {
  13793. eof = false;
  13794. }
  13795. virtual const void * nextRow()
  13796. {
  13797. if (eof)
  13798. return NULL;
  13799. const void * ret = input.dequeue();
  13800. if (!ret)
  13801. eof = true;
  13802. return ret;
  13803. }
  13804. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13805. protected:
  13806. SafeRowQueue & input;
  13807. IOutputMetaData * meta;
  13808. bool eof;
  13809. };
  13810. class CRoxieServerParallelLoopActivity;
  13811. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13812. {
  13813. public:
  13814. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13815. activity(_activity), counter(_counter)
  13816. {
  13817. }
  13818. virtual const void * nextRow();
  13819. protected:
  13820. CRoxieServerParallelLoopActivity * activity;
  13821. unsigned counter;
  13822. };
  13823. class LoopExecutorThread : public RestartableThread
  13824. {
  13825. protected:
  13826. Owned<CSafeRoxieInput> safeInput;
  13827. CRoxieServerParallelLoopActivity * activity;
  13828. bool eof;
  13829. CriticalSection crit;
  13830. unsigned flags;
  13831. SafeRowQueue tempResults[2];
  13832. unsigned savedParentExtractSize;
  13833. const byte * savedParentExtract;
  13834. IArrayOf<IActivityGraph> cachedGraphs;
  13835. IRoxieAgentContext *ctx;
  13836. public:
  13837. LoopExecutorThread()
  13838. : RestartableThread("LoopExecutorThread")
  13839. {
  13840. activity = NULL;
  13841. eof = false;
  13842. flags = 0;
  13843. ctx = NULL;
  13844. savedParentExtract = NULL;
  13845. savedParentExtractSize = 0;
  13846. }
  13847. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13848. {
  13849. activity = _activity;
  13850. flags = _flags;
  13851. // stop is called on our consumer's thread. We need to take care calling stop for our input to make sure it is not in mid-nextRow etc etc.
  13852. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13853. }
  13854. void connectInputStreams(bool consumerOrdered)
  13855. {
  13856. safeInput->connectInputStreams(ctx, consumerOrdered);
  13857. }
  13858. IFinalRoxieInput *queryInput() const
  13859. {
  13860. return safeInput;
  13861. }
  13862. void onCreate(IRoxieAgentContext * _ctx);
  13863. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13864. void stop();
  13865. void reset();
  13866. virtual int run();
  13867. protected:
  13868. void executeLoop();
  13869. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13870. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13871. };
  13872. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13873. {
  13874. friend class LoopFilterPseudoInput;
  13875. friend class LoopExecutorThread;
  13876. QueueOf<const void, true> ready;
  13877. CriticalSection helperCS;
  13878. CriticalSection cs;
  13879. unsigned defaultNumParallel;
  13880. LoopExecutorThread executor;
  13881. IProbeManager* probeManager;
  13882. CriticalSection canAccess;
  13883. CriticalSection scrit;
  13884. InterruptableSemaphore readySpace;
  13885. InterruptableSemaphore recordsReady;
  13886. protected:
  13887. bool includeInLoop(unsigned counter, const void * row)
  13888. {
  13889. CriticalBlock b(helperCS);
  13890. return helper.sendToLoop(counter, row);
  13891. }
  13892. public:
  13893. CRoxieServerParallelLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13894. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13895. readySpace(parallelLoopFlowLimit)
  13896. {
  13897. probeManager = _probeManager;
  13898. defaultNumParallel = 0;
  13899. }
  13900. virtual void onCreate(IHThorArg *_colocalParent)
  13901. {
  13902. CRoxieServerActivity::onCreate(_colocalParent);
  13903. executor.onCreate(ctx);
  13904. }
  13905. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13906. {
  13907. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13908. readySpace.reinit(parallelLoopFlowLimit);
  13909. recordsReady.reinit();
  13910. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13911. defaultNumParallel = helper.defaultParallelIterations();
  13912. if (!defaultNumParallel)
  13913. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13914. //MORE: If numIterations <= number of parallel iterations[1],
  13915. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13916. //being transferred via a queue
  13917. executor.start(parentExtractSize, parentExtract, paused);
  13918. }
  13919. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13920. {
  13921. if (idx)
  13922. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13923. executor.setInput(this, _sourceIdx, _in, flags);
  13924. }
  13925. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13926. {
  13927. executor.connectInputStreams(consumerOrdered);
  13928. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13929. }
  13930. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13931. {
  13932. if (idx==0)
  13933. return executor.queryInput();
  13934. else
  13935. return NULL;
  13936. }
  13937. virtual void stop()
  13938. {
  13939. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13940. readySpace.interrupt();
  13941. recordsReady.interrupt();
  13942. executor.join(); // MORE - may not be needed given stop/reset split
  13943. CRoxieServerLoopActivity::stop();
  13944. }
  13945. virtual void reset()
  13946. {
  13947. while (ready.ordinality())
  13948. ReleaseRoxieRow(ready.dequeue());
  13949. executor.reset();
  13950. CRoxieServerActivity::reset();
  13951. }
  13952. virtual const void * nextRow()
  13953. {
  13954. ActivityTimer t(activityStats, timeActivities);
  13955. for (;;)
  13956. {
  13957. if (eof)
  13958. return NULL;
  13959. recordsReady.wait();
  13960. CriticalBlock procedure(canAccess);
  13961. if (ready.ordinality())
  13962. {
  13963. const void *result = ready.dequeue();
  13964. readySpace.signal();
  13965. if (result)
  13966. processed++;
  13967. return result;
  13968. }
  13969. else
  13970. eof = true;
  13971. }
  13972. }
  13973. unsigned getNumParallel(unsigned iter)
  13974. {
  13975. return defaultNumParallel;
  13976. }
  13977. inline void enqueueResult(const void * row)
  13978. {
  13979. try
  13980. {
  13981. while(!readySpace.wait(1000))
  13982. {
  13983. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13984. }
  13985. }
  13986. catch (...)
  13987. {
  13988. ReleaseRoxieRow(row);
  13989. throw;
  13990. }
  13991. CriticalBlock b2(canAccess);
  13992. ready.enqueue(row);
  13993. recordsReady.signal();
  13994. }
  13995. inline void finishResults()
  13996. {
  13997. recordsReady.signal();
  13998. }
  13999. virtual bool fireException(IException *e)
  14000. {
  14001. readySpace.interrupt(LINK(e));
  14002. recordsReady.interrupt(e);
  14003. return true;
  14004. }
  14005. IActivityGraph * createChildGraphInstance()
  14006. {
  14007. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  14008. }
  14009. IActivityGraph * queryChildGraph()
  14010. {
  14011. return ctx->queryChildGraph(loopGraphId);
  14012. }
  14013. };
  14014. //=================================================================================
  14015. const void * LoopFilterPseudoInput::nextRow()
  14016. {
  14017. for (;;)
  14018. {
  14019. const void * next = stream->nextRow();
  14020. if (!next || activity->includeInLoop(counter, next))
  14021. return next;
  14022. activity->enqueueResult(next);
  14023. }
  14024. }
  14025. void LoopExecutorThread::onCreate(IRoxieAgentContext * _ctx)
  14026. {
  14027. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  14028. ctx = _ctx;
  14029. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  14030. }
  14031. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14032. {
  14033. savedParentExtractSize = parentExtractSize;
  14034. savedParentExtract = parentExtract;
  14035. eof = false;
  14036. StringBuffer logPrefix("[");
  14037. ctx->getLogPrefix(logPrefix).append("] ");
  14038. RestartableThread::start(logPrefix);
  14039. }
  14040. int LoopExecutorThread::run()
  14041. {
  14042. try
  14043. {
  14044. executeLoop();
  14045. }
  14046. catch (IException *e)
  14047. {
  14048. activity->fireException(e);
  14049. }
  14050. catch (...)
  14051. {
  14052. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  14053. }
  14054. return 0;
  14055. }
  14056. void LoopExecutorThread::stop()
  14057. {
  14058. safeInput->stop();
  14059. RestartableThread::join();
  14060. }
  14061. void LoopExecutorThread::reset()
  14062. {
  14063. safeInput->reset();
  14064. }
  14065. void LoopExecutorThread::executeLoop()
  14066. {
  14067. unsigned iterations = 0;
  14068. unsigned counter = 0;
  14069. unsigned outputIndex = 0;
  14070. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  14071. for (;;)
  14072. {
  14073. if (activity->activityKind == TAKloopcount)
  14074. {
  14075. if (counter == activity->maxIterations)
  14076. break;
  14077. }
  14078. else
  14079. {
  14080. //This condition isn't quite right because it needs to be whether the filtered
  14081. //input is empty. May be ok if we include that in the semantics,
  14082. if (tempResults[1-outputIndex].ordinality() == 0)
  14083. break;
  14084. }
  14085. unsigned numParallel = activity->getNumParallel(iterations);
  14086. Linked<IFinalRoxieInput> curInput;
  14087. if (iterations == 0)
  14088. curInput.set(safeInput);
  14089. else
  14090. {
  14091. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  14092. inputQueue.enqueue(NULL);
  14093. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  14094. }
  14095. SafeRowQueue * curOutput = NULL;
  14096. if (counter+numParallel > activity->maxIterations)
  14097. numParallel = activity->maxIterations - counter;
  14098. else if (counter+numParallel < activity->maxIterations)
  14099. curOutput = &tempResults[outputIndex];
  14100. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  14101. outputIndex = 1-outputIndex;
  14102. counter += numParallel;
  14103. iterations++;
  14104. }
  14105. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  14106. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  14107. while (inputQueue.ordinality())
  14108. {
  14109. const void * next = inputQueue.dequeue();
  14110. activity->enqueueResult(next);
  14111. }
  14112. activity->finishResults();
  14113. }
  14114. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  14115. {
  14116. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  14117. Linked<IFinalRoxieInput> curInput = input;
  14118. unsigned i;
  14119. for (i= 0; i != numIterations; i++)
  14120. {
  14121. unsigned thisCounter = counter+i+1;
  14122. IFinalRoxieInput * filtered = curInput;
  14123. if (flags & IHThorLoopArg::LFfiltered)
  14124. {
  14125. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  14126. newFiltered->setInput(inputIdx, curInput);
  14127. filtered = newFiltered;
  14128. savedInputs.append(*filtered);
  14129. inputIdx = 0;
  14130. }
  14131. //graph is kept, so new curInput will be guaranteed to exist
  14132. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  14133. inputIdx = 0;
  14134. }
  14135. Owned<IStrandJunction> curJunction;
  14136. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  14137. Owned<IException> failure;
  14138. try
  14139. {
  14140. curInput->start(savedParentExtractSize, savedParentExtract, false);
  14141. if (spillOutput)
  14142. {
  14143. for (;;)
  14144. {
  14145. const void * next = curStream->nextRow();
  14146. if (!next)
  14147. break;
  14148. spillOutput->enqueue(next);
  14149. }
  14150. }
  14151. else
  14152. {
  14153. for (;;)
  14154. {
  14155. const void * next = curStream->nextRow();
  14156. if (!next)
  14157. break;
  14158. activity->enqueueResult(next);
  14159. }
  14160. }
  14161. }
  14162. catch (IException *E)
  14163. {
  14164. ctx->notifyAbort(E);
  14165. failure.setown(E);
  14166. }
  14167. for (i= 0; i != numIterations; i++)
  14168. {
  14169. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14170. loopGraph->afterExecute();
  14171. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  14172. loopGraph->querySetInputResult(1, 0, nullptr);
  14173. }
  14174. curStream->stop();
  14175. curInput->reset();
  14176. if (failure)
  14177. throw failure.getClear();
  14178. }
  14179. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  14180. {
  14181. if (!cachedGraphs.isItem(i))
  14182. cachedGraphs.append(*activity->createChildGraphInstance());
  14183. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14184. loopGraph->beforeExecute();
  14185. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  14186. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  14187. activity->createCounterResult(loopGraph, counter);
  14188. return loopGraph->selectOutput(0);
  14189. }
  14190. //=================================================================================
  14191. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  14192. {
  14193. public:
  14194. IMPLEMENT_IINTERFACE
  14195. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  14196. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  14197. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  14198. virtual void toXML(const byte * self, IXmlWriter & out) { }
  14199. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  14200. virtual unsigned getMetaFlags() { return 0; }
  14201. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  14202. virtual void destruct(byte * self) {}
  14203. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14204. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14205. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  14206. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  14207. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14208. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14209. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  14210. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  14211. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  14212. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); } // could provide a static implementation if needed
  14213. };
  14214. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  14215. {
  14216. unsigned loopGraphId;
  14217. unsigned flags;
  14218. Linked<IOutputMetaData> counterMeta;
  14219. public:
  14220. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14221. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14222. {
  14223. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  14224. flags = helper->getFlags();
  14225. counterMeta.setown(new CCounterRowMetaData);
  14226. }
  14227. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  14228. {
  14229. if (flags & IHThorLoopArg::LFparallel)
  14230. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14231. else
  14232. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14233. }
  14234. };
  14235. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14236. {
  14237. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14238. }
  14239. //=================================================================================
  14240. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  14241. {
  14242. protected:
  14243. IHThorGraphLoopArg &helper;
  14244. unsigned maxIterations;
  14245. unsigned flags;
  14246. rtlRowBuilder GraphExtractBuilder;
  14247. unsigned loopGraphId;
  14248. Linked<IOutputMetaData> counterMeta;
  14249. public:
  14250. CRoxieServerGraphLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14251. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14252. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  14253. {
  14254. flags = helper.getFlags();
  14255. maxIterations = 0;
  14256. }
  14257. virtual bool needsAllocator() const { return true; }
  14258. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14259. {
  14260. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14261. int iterations = (int) helper.numIterations();
  14262. maxIterations = (iterations >= 0) ? iterations : 0;
  14263. if (maxIterations > maxGraphLoopIterations)
  14264. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  14265. if (maxIterations != 0)
  14266. {
  14267. GraphExtractBuilder.clear();
  14268. helper.createParentExtract(GraphExtractBuilder);
  14269. }
  14270. }
  14271. virtual void stop()
  14272. {
  14273. CRoxieServerActivity::stop();
  14274. GraphExtractBuilder.clear();
  14275. }
  14276. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  14277. {
  14278. if (flags & IHThorGraphLoopArg::GLFcounter)
  14279. {
  14280. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  14281. *((thor_loop_counter_t *)counterRow) = counter;
  14282. RtlLinkedDatasetBuilder builder(rowAllocator);
  14283. builder.appendOwn(counterRow);
  14284. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  14285. graph->setInputResult(0, counterResult);
  14286. }
  14287. }
  14288. };
  14289. //=================================================================================
  14290. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  14291. {
  14292. Owned<IActivityGraph> GraphQuery;
  14293. Owned<IRoxieServerChildGraph> loopGraph;
  14294. Linked<IEngineRowStream> resultStream;
  14295. bool evaluated;
  14296. public:
  14297. CRoxieServerSequentialGraphLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14298. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  14299. {
  14300. evaluated = false;
  14301. }
  14302. virtual void onCreate(IHThorArg *_colocalParent)
  14303. {
  14304. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14305. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  14306. }
  14307. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14308. {
  14309. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  14310. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  14311. loopGraph.set(GraphQuery->queryLoopGraph());
  14312. evaluated = false;
  14313. }
  14314. virtual void stop()
  14315. {
  14316. if (loopGraph)
  14317. loopGraph->clearGraphLoopResults();
  14318. CRoxieServerGraphLoopActivity::stop();
  14319. }
  14320. virtual const void * nextRow()
  14321. {
  14322. ActivityTimer t(activityStats, timeActivities);
  14323. if (!evaluated)
  14324. {
  14325. executeEntireGraph();
  14326. evaluated = true;
  14327. }
  14328. const void * ret = resultStream->nextRow();
  14329. if (ret)
  14330. processed++;
  14331. return ret;
  14332. }
  14333. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  14334. {
  14335. try
  14336. {
  14337. loopGraph->beforeExecute();
  14338. createCounterResult(loopGraph, counter);
  14339. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  14340. loopGraph->afterExecute();
  14341. }
  14342. catch (...)
  14343. {
  14344. CTXLOG("Exception thrown in graph body - cleaning up");
  14345. loopGraph->afterExecute();
  14346. throw;
  14347. }
  14348. }
  14349. void createInitialGraphInput()
  14350. {
  14351. loopGraph->clearGraphLoopResults();
  14352. RtlLinkedDatasetBuilder builder(rowAllocator);
  14353. inputStream->readAll(builder);
  14354. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  14355. loopGraph->setGraphLoopResult(0, result);
  14356. }
  14357. void executeEntireGraph()
  14358. {
  14359. createInitialGraphInput();
  14360. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  14361. {
  14362. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  14363. }
  14364. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  14365. }
  14366. };
  14367. //=================================================================================
  14368. struct GraphOutputSplitterArg : public CThorSplitArg
  14369. {
  14370. public:
  14371. virtual unsigned numBranches()
  14372. {
  14373. return 0;
  14374. }
  14375. virtual IOutputMetaData * queryOutputMeta()
  14376. {
  14377. return NULL;// get it from the parent..
  14378. }
  14379. };
  14380. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  14381. class CGraphIterationInfo : public CInterface
  14382. {
  14383. private:
  14384. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  14385. unsigned sourceIdx;
  14386. Linked<IRoxieServerActivity> sourceAct;
  14387. Linked<IFinalRoxieInput> sourceInput;
  14388. unsigned numUses;
  14389. unsigned iteration;
  14390. public:
  14391. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  14392. : sourceIdx(_sourceIdx), sourceAct(_sourceAct), sourceInput(_input), iteration(_iteration)
  14393. {
  14394. numUses = 0;
  14395. }
  14396. inline void noteUsed()
  14397. {
  14398. numUses++;
  14399. }
  14400. void createSplitter(IRoxieAgentContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14401. {
  14402. if (numUses > 1)
  14403. {
  14404. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  14405. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  14406. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  14407. splitter->onCreate(NULL);
  14408. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14409. if (probeManager)
  14410. {
  14411. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14412. probes.append(*LINK(inputProbe));
  14413. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14414. sourceIdx = 0;
  14415. }
  14416. sourceAct.setown(splitter);
  14417. sourceAct->setInput(0, sourceIdx, input);
  14418. sourceIdx = 0;
  14419. sourceInput.clear();
  14420. }
  14421. }
  14422. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14423. {
  14424. // MORE - not really necessary to create splitters in separate pass, is it?
  14425. if (factory) // we created a splitter....
  14426. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14427. IFinalRoxieInput *ret = sourceInput;
  14428. if (probeManager)
  14429. {
  14430. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14431. probes.append(*LINK(inputProbe));
  14432. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14433. // MORE - do we need to connect the stream in the probe?
  14434. }
  14435. if (factory) // we created a splitter....
  14436. sourceIdx++;
  14437. return ret;
  14438. }
  14439. };
  14440. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14441. {
  14442. Owned<IActivityGraph> childGraph;
  14443. IFinalRoxieInput * resultInput;
  14444. IEngineRowStream * resultStream;
  14445. Owned<IStrandJunction> resultJunction;
  14446. CIArrayOf<CGraphIterationInfo> outputs;
  14447. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14448. Owned<CExtractMapperInput> inputExtractMapper;
  14449. IProbeManager *probeManager;
  14450. Owned<IStatisticGatherer> childStats;
  14451. unsigned createLoopCounter;
  14452. IArrayOf<IRoxieProbe> probes;
  14453. public:
  14454. CRoxieServerParallelGraphLoopActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14455. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14456. {
  14457. inputExtractMapper.setown(new CExtractMapperInput);
  14458. resultInput = NULL;
  14459. resultStream = NULL;
  14460. createLoopCounter = 0;
  14461. if (ctx && ctx->collectingDetailedStatistics())
  14462. {
  14463. StatsScopeId rootScope(SSTnone, 0U);
  14464. childStats.setown(createStatisticsGatherer(SCTroxie, "", rootScope));
  14465. }
  14466. }
  14467. virtual void onCreate(IHThorArg *_colocalParent)
  14468. {
  14469. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14470. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14471. }
  14472. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14473. {
  14474. CRoxieServerGraphLoopActivity::gatherStatistics(statsBuilder);
  14475. if (statsBuilder && childStats)
  14476. {
  14477. //Merge any stats collected from executed graphs into the full statistics
  14478. Owned<IStatisticCollection> childCollection = childStats->getResult();
  14479. childCollection->mergeInto(*statsBuilder);
  14480. }
  14481. }
  14482. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14483. {
  14484. //Input needs to be handled very carefully.....
  14485. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14486. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14487. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14488. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14489. assertex(idx == 0);
  14490. inputExtractMapper->setInput(_sourceIdx, _in);
  14491. }
  14492. virtual void connectInputStreams(bool consumerOrdered)
  14493. {
  14494. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14495. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14496. }
  14497. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14498. {
  14499. if (idx==0)
  14500. return inputExtractMapper->queryInput();
  14501. else
  14502. return NULL;
  14503. }
  14504. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14505. {
  14506. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14507. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14508. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14509. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14510. startJunction(resultJunction);
  14511. }
  14512. virtual void stop()
  14513. {
  14514. if (resultStream)
  14515. resultStream->stop();
  14516. CRoxieServerGraphLoopActivity::stop();
  14517. }
  14518. virtual void reset()
  14519. {
  14520. if (resultInput)
  14521. resultInput->reset();
  14522. resetJunction(resultJunction);
  14523. resultInput = NULL;
  14524. resultStream = NULL;
  14525. resultJunction.clear();
  14526. ForEachItemIn(i, iterationGraphs)
  14527. iterationGraphs.item(i).gatherStatistics(childStats);
  14528. outputs.kill();
  14529. iterationGraphs.kill(); // must be done after all activities killed
  14530. if (probeManager)
  14531. {
  14532. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14533. probes.kill();
  14534. }
  14535. CRoxieServerGraphLoopActivity::reset();
  14536. }
  14537. virtual const void * nextRow()
  14538. {
  14539. ActivityTimer t(activityStats, timeActivities);
  14540. const void * ret = resultStream->nextRow();
  14541. if (ret)
  14542. processed++;
  14543. return ret;
  14544. }
  14545. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14546. {
  14547. //result(0) is the input to the graph.
  14548. resultInput = inputExtractMapper;
  14549. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14550. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14551. {
  14552. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14553. graph->beforeExecute();
  14554. iterationGraphs.append(*graph);
  14555. graph->gatherIterationUsage(*this);
  14556. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14557. outputs.append(*iteration);
  14558. }
  14559. createLoopCounter = 0;
  14560. createSplitters(probeManager, probes);
  14561. ForEachItemIn(i2, iterationGraphs)
  14562. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14563. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14564. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14565. }
  14566. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14567. {
  14568. ForEachItemIn(i, outputs)
  14569. {
  14570. CGraphIterationInfo & next = outputs.item(i);
  14571. next.createSplitter(ctx, probeManager, probes);
  14572. }
  14573. }
  14574. //IRoxieServerLoopResultProcessor
  14575. virtual void noteUseIteration(unsigned _whichIteration)
  14576. {
  14577. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14578. if (whichIteration >= 0)
  14579. {
  14580. if (!outputs.isItem(whichIteration))
  14581. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14582. outputs.item(whichIteration).noteUsed();
  14583. }
  14584. }
  14585. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14586. {
  14587. if (outputs.isItem(whichIteration))
  14588. {
  14589. CGraphIterationInfo & next = outputs.item(whichIteration);
  14590. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14591. }
  14592. return NULL;
  14593. }
  14594. };
  14595. //=================================================================================
  14596. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14597. {
  14598. unsigned loopGraphId;
  14599. unsigned flags;
  14600. Linked<IOutputMetaData> counterMeta;
  14601. public:
  14602. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14603. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14604. {
  14605. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14606. flags = helper->getFlags();
  14607. counterMeta.setown(new CCounterRowMetaData);
  14608. }
  14609. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  14610. {
  14611. if (kind == TAKparallelgraphloop)
  14612. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14613. else
  14614. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14615. }
  14616. };
  14617. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14618. {
  14619. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14620. }
  14621. //=====================================================================================================
  14622. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14623. {
  14624. class OutputAdaptor : public CExtractMapperInput
  14625. {
  14626. bool stopped;
  14627. public:
  14628. CRoxieServerLibraryCallActivity *parent;
  14629. IOutputMetaData * meta = nullptr;
  14630. unsigned oid;
  14631. unsigned processed;
  14632. unsigned numStarts = 0;
  14633. public:
  14634. OutputAdaptor()
  14635. {
  14636. parent = NULL;
  14637. oid = 0;
  14638. init();
  14639. }
  14640. ~OutputAdaptor()
  14641. {
  14642. if (traceStartStop)
  14643. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14644. }
  14645. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14646. {
  14647. parent = _parent;
  14648. meta = _meta;
  14649. oid = _oid;
  14650. }
  14651. void init()
  14652. {
  14653. processed = 0;
  14654. stopped = false;
  14655. }
  14656. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14657. {
  14658. parent->start(oid, parentExtractSize, parentExtract, paused);
  14659. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14660. numStarts++;
  14661. }
  14662. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14663. {
  14664. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14665. if (!oid) // Only need to set up once
  14666. {
  14667. parent->connectInputStreams(true); // To handle dependencies etc
  14668. }
  14669. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14670. }
  14671. //This override should not really be needed, but input is set up too late for the call to connect strands
  14672. virtual IOutputMetaData * queryOutputMeta() const
  14673. {
  14674. return meta;
  14675. }
  14676. virtual void stop()
  14677. {
  14678. if (!stopped)
  14679. {
  14680. stopped = true;
  14681. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14682. CExtractMapperInput::stop();
  14683. }
  14684. };
  14685. virtual void reset()
  14686. {
  14687. parent->reset(oid);
  14688. CExtractMapperInput::reset();
  14689. init();
  14690. };
  14691. virtual void checkAbort()
  14692. {
  14693. parent->checkAbort();
  14694. }
  14695. };
  14696. IHThorLibraryCallArg &helper;
  14697. unsigned numInputs;
  14698. unsigned numOutputs;
  14699. unsigned numActiveOutputs;
  14700. bool started;
  14701. OutputAdaptor* outputAdaptors;
  14702. CExtractMapperInput * * inputAdaptors;
  14703. bool * inputUsed;
  14704. bool * outputUsed;
  14705. Owned<IException> error;
  14706. CriticalSection crit;
  14707. rtlRowBuilder libraryExtractBuilder;
  14708. Owned<IActivityGraph> libraryGraph;
  14709. const LibraryCallFactoryExtra & extra;
  14710. public:
  14711. CRoxieServerLibraryCallActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14712. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14713. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14714. {
  14715. numInputs = _numInputs;
  14716. numOutputs = _numOutputs;
  14717. numActiveOutputs = numOutputs;
  14718. inputAdaptors = new CExtractMapperInput*[numInputs];
  14719. inputUsed = new bool[numInputs];
  14720. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14721. {
  14722. inputAdaptors[i1] = new CExtractMapperInput;
  14723. inputUsed[i1] = false;
  14724. }
  14725. outputAdaptors = new OutputAdaptor[numOutputs];
  14726. outputUsed = new bool[numOutputs];
  14727. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14728. {
  14729. unsigned actualOutput = extra.outputs.item(i2);
  14730. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(actualOutput), i2);
  14731. outputUsed[i2] = false;
  14732. }
  14733. started = false;
  14734. }
  14735. ~CRoxieServerLibraryCallActivity()
  14736. {
  14737. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14738. ::Release(inputAdaptors[i1]);
  14739. delete [] inputAdaptors;
  14740. delete [] inputUsed;
  14741. delete [] outputAdaptors;
  14742. delete [] outputUsed;
  14743. }
  14744. virtual void onCreate(IHThorArg *_colocalParent)
  14745. {
  14746. CRoxieServerActivity::onCreate(_colocalParent);
  14747. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14748. libraryGraph->onCreate(_colocalParent);
  14749. //Now map the inputs and outputs to the adapters
  14750. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14751. for (unsigned i1=0; i1<numInputs; i1++)
  14752. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14753. for (unsigned i2=0; i2<numOutputs; i2++)
  14754. {
  14755. unsigned outputIndex = extra.outputs.item(i2);
  14756. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14757. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14758. outputAdaptors[i2].connectInputStreams(ctx, true);
  14759. }
  14760. }
  14761. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14762. {
  14763. CriticalBlock b(crit);
  14764. if (error)
  14765. throw error.getLink();
  14766. if (collectFactoryStatistics)
  14767. factory->noteStarted(oid);
  14768. if (!started)
  14769. {
  14770. // even though it is not complete, we don't want to run this again if it fails.
  14771. started = true;
  14772. //see notes on splitter above
  14773. try
  14774. {
  14775. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14776. }
  14777. catch (IException *E)
  14778. {
  14779. #ifdef TRACE_SPLIT
  14780. CTXLOG("spill %d caught exception in start", activityId);
  14781. #endif
  14782. error.set(E);
  14783. throw;
  14784. }
  14785. catch (...)
  14786. {
  14787. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14788. error.set(E);
  14789. throw E;
  14790. }
  14791. //recreate the parent extract, and use it to reinitialize the graphs...
  14792. libraryExtractBuilder.clear();
  14793. helper.createParentExtract(libraryExtractBuilder);
  14794. // 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
  14795. // some inputs before we see start on others.
  14796. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14797. {
  14798. if (inputUsed[i1])
  14799. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14800. else
  14801. inputAdaptors[i1]->queryInput()->stopall();
  14802. }
  14803. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14804. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14805. //call stop on all the unused inputs.
  14806. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14807. graph->beforeExecute();
  14808. ForEachItemIn(i3, extra.unusedOutputs)
  14809. {
  14810. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14811. output->stopall();
  14812. }
  14813. }
  14814. }
  14815. virtual void stop(unsigned oid)
  14816. {
  14817. CriticalBlock b(crit);
  14818. if (--numActiveOutputs == 0)
  14819. {
  14820. //call stop on all the unused inputs.
  14821. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14822. graph->beforeExecute();
  14823. ForEachItemIn(i3, extra.unusedOutputs)
  14824. {
  14825. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14826. output->stopall();
  14827. }
  14828. CRoxieServerActivity::stop();
  14829. }
  14830. }
  14831. void reset(unsigned oid)
  14832. {
  14833. started = false;
  14834. error.clear();
  14835. numActiveOutputs = numOutputs;
  14836. if (state != STATEreset) // make sure input is only reset once
  14837. {
  14838. CRoxieServerActivity::reset();
  14839. libraryGraph->reset();
  14840. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14841. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14842. {
  14843. if (!inputUsed[i1])
  14844. inputAdaptors[i1]->reset();
  14845. }
  14846. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14847. ForEachItemIn(i3, extra.unusedOutputs)
  14848. {
  14849. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14850. output->reset();
  14851. }
  14852. }
  14853. };
  14854. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14855. {
  14856. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14857. }
  14858. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14859. {
  14860. if (idx < numInputs && inputAdaptors[idx])
  14861. return inputAdaptors[idx]->queryInput();
  14862. else
  14863. return NULL;
  14864. }
  14865. public:
  14866. virtual const void *nextRow()
  14867. {
  14868. throwUnexpected(); // Internal logic error - we are not anybody's input
  14869. }
  14870. virtual IOutputMetaData * queryOutputMeta() const
  14871. {
  14872. throwUnexpected(); // should be called on outputs instead
  14873. }
  14874. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14875. {
  14876. assertex(idx!=(unsigned)-1);
  14877. assertex(!outputUsed[idx]);
  14878. outputUsed[idx] = true;
  14879. return &outputAdaptors[idx];
  14880. }
  14881. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14882. {
  14883. if (libraryGraph)
  14884. libraryGraph->gatherStatistics(statsBuilder);
  14885. CRoxieServerActivity::gatherStatistics(statsBuilder);
  14886. }
  14887. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  14888. {
  14889. for (unsigned i = 0; i < numOutputs; i++)
  14890. addEdgeStats(statsBuilder, i, outputAdaptors[i].numStarts, outputAdaptors[i].processed, 0);
  14891. }
  14892. };
  14893. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14894. {
  14895. ForEachItemIn(i1, _other.outputs)
  14896. outputs.append(_other.outputs.item(i1));
  14897. ForEachItemIn(i2, _other.unusedOutputs)
  14898. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14899. maxOutputs = _other.maxOutputs;
  14900. graphid = _other.graphid;
  14901. libraryName.set(_other.libraryName);
  14902. embeddedGraphName.set(_other.embeddedGraphName);
  14903. interfaceHash = _other.interfaceHash;
  14904. embedded = _other.embedded;
  14905. }
  14906. void LibraryCallFactoryExtra::calcUnused()
  14907. {
  14908. for (unsigned i=0; i < maxOutputs; i++)
  14909. if (!outputs.contains(i))
  14910. unusedOutputs.append(i);
  14911. }
  14912. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14913. {
  14914. private:
  14915. CRoxieServerMultiInputInfo inputs;
  14916. LibraryCallFactoryExtra extra;
  14917. public:
  14918. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14919. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14920. {
  14921. extra.set(_extra);
  14922. extra.calcUnused();
  14923. setNumOutputs(extra.outputs.ordinality());
  14924. // Try to resolve library now so that we can detect interface mismatches early. You could argue it should only be a warning - as it is the query
  14925. // will be suspended and will remain suspended even if a suitable library is later published
  14926. if (!extra.embedded && _graphNode.getPropBool("hint[@name='required']/@value", false))
  14927. {
  14928. StringContextLogger logctx;
  14929. Owned<IQueryFactory> libraryQuery = _queryFactory.lookupLibrary(extra.libraryName, extra.interfaceHash, logctx);
  14930. }
  14931. }
  14932. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  14933. {
  14934. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14935. }
  14936. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14937. {
  14938. inputs.set(idx, source, sourceidx);
  14939. }
  14940. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14941. {
  14942. return inputs.get(idx, sourceidx);
  14943. }
  14944. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14945. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14946. {
  14947. addXrefLibraryInfo(reply, extra.libraryName);
  14948. }
  14949. };
  14950. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14951. {
  14952. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14953. }
  14954. //=====================================================================================================
  14955. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14956. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14957. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14958. {
  14959. protected:
  14960. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14961. PointerArrayOf<IEngineRowStream> selectedStreams;
  14962. PointerArrayOf<IStrandJunction> selectedJunctions;
  14963. public:
  14964. CRoxieServerNWayInputBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14965. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14966. {
  14967. }
  14968. virtual unsigned __int64 queryLocalCycles() const
  14969. {
  14970. __int64 localCycles = activityStats.totalCycles;
  14971. ForEachItemIn(i, selectedInputs)
  14972. {
  14973. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14974. }
  14975. if (localCycles < 0)
  14976. localCycles = 0;
  14977. return localCycles;
  14978. }
  14979. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14980. {
  14981. if (selectedInputs.isItem(idx))
  14982. return selectedInputs.item(idx);
  14983. else
  14984. return NULL;
  14985. }
  14986. virtual void reset()
  14987. {
  14988. ForEachItemIn(i, selectedInputs)
  14989. selectedInputs.item(i)->reset();
  14990. selectedInputs.kill();
  14991. selectedStreams.kill();
  14992. selectedJunctions.kill();
  14993. CRoxieServerMultiInputBaseActivity::reset();
  14994. }
  14995. virtual const void * nextRow()
  14996. {
  14997. throwUnexpected();
  14998. }
  14999. virtual unsigned numConcreteOutputs() const
  15000. {
  15001. return selectedInputs.ordinality();
  15002. }
  15003. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  15004. {
  15005. return queryInput(idx);
  15006. }
  15007. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  15008. {
  15009. if (selectedStreams.isItem(whichInput))
  15010. return selectedStreams.item(whichInput);
  15011. return NULL;
  15012. }
  15013. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  15014. {
  15015. if (selectedJunctions.isItem(idx))
  15016. return selectedJunctions.item(idx);
  15017. return NULL;
  15018. }
  15019. };
  15020. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  15021. {
  15022. IHThorNWayInputArg & helper;
  15023. public:
  15024. CRoxieServerNWayInputActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15025. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  15026. {
  15027. }
  15028. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15029. {
  15030. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  15031. bool selectionIsAll;
  15032. size32_t selectionLen;
  15033. rtlDataAttr selection;
  15034. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  15035. selectedInputs.kill();
  15036. selectedStreams.kill();
  15037. selectedJunctions.kill();
  15038. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  15039. if (selectionIsAll)
  15040. {
  15041. for (unsigned i=0; i < numInputs; i++)
  15042. {
  15043. selectedInputs.append(inputArray[i]);
  15044. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  15045. selectedJunctions.append(junctionArray[i]);
  15046. }
  15047. }
  15048. else
  15049. {
  15050. const size32_t * selections = (const size32_t *)selection.getdata();
  15051. unsigned max = selectionLen/sizeof(size32_t);
  15052. for (unsigned i = 0; i < max; i++)
  15053. {
  15054. unsigned nextIndex = selections[i];
  15055. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  15056. for (unsigned j=i+1; j < max; j++)
  15057. {
  15058. if (nextIndex == selections[j])
  15059. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  15060. }
  15061. if (nextIndex > numInputs || nextIndex > numStreams)
  15062. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  15063. selectedInputs.append(inputArray[nextIndex-1]);
  15064. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  15065. selectedJunctions.append(junctionArray[nextIndex-1]);
  15066. }
  15067. }
  15068. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  15069. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  15070. stop();
  15071. }
  15072. };
  15073. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  15074. {
  15075. public:
  15076. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15077. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15078. {
  15079. }
  15080. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15081. {
  15082. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  15083. }
  15084. };
  15085. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15086. {
  15087. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15088. }
  15089. //=====================================================================================================
  15090. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  15091. {
  15092. IHThorNWayGraphLoopResultReadArg & helper;
  15093. IArrayOf<IRoxieServerActivity> resultReaders;
  15094. Owned<IStrandJunction> *resultJunctions;
  15095. unsigned graphId;
  15096. bool grouped;
  15097. bool selectionIsAll;
  15098. size32_t selectionLen;
  15099. rtlDataAttr selection;
  15100. public:
  15101. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  15102. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  15103. {
  15104. grouped = helper.isGrouped();
  15105. graphId = _graphId;
  15106. selectionIsAll = false;
  15107. selectionLen = 0;
  15108. resultJunctions = NULL;
  15109. }
  15110. ~CRoxieServerNWayGraphLoopResultReadActivity()
  15111. {
  15112. delete [] resultJunctions;
  15113. }
  15114. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15115. {
  15116. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15117. if (selectedInputs.ordinality() == 0)
  15118. {
  15119. initInputSelection();
  15120. unsigned max = selectionLen / sizeof(size32_t);
  15121. const size32_t * selections = (const size32_t *)selection.getdata();
  15122. IProbeManager * probeManager = NULL; // MORE!!
  15123. for (unsigned i = 0; i < max; i++)
  15124. {
  15125. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  15126. resultReaders.append(*resultInput);
  15127. selectedInputs.append(resultInput);
  15128. resultInput->onCreate(colocalParent);
  15129. resultInput->start(parentExtractSize, parentExtract, paused);
  15130. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  15131. selectedJunctions.append(resultJunctions[i]);
  15132. }
  15133. }
  15134. // I have done with my processing - note that this won't stop my inputs
  15135. stop();
  15136. }
  15137. virtual void reset()
  15138. {
  15139. resultReaders.kill();
  15140. CRoxieServerNWayInputBaseActivity::reset();
  15141. ForEachItemIn(i, selectedStreams)
  15142. resetJunction(resultJunctions[i]);
  15143. }
  15144. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  15145. {
  15146. ensureCreated();
  15147. basehelper.onStart(parentExtract, NULL);
  15148. initInputSelection();
  15149. unsigned max = selectionLen / sizeof(size32_t);
  15150. const size32_t * selections = (const size32_t *)selection.getdata();
  15151. for (unsigned i = 0; i < max; i++)
  15152. processor.noteUseIteration(selections[i]);
  15153. }
  15154. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  15155. {
  15156. //selection etc. already initialised from the gatherIterationUsage() call.
  15157. unsigned max = selectionLen / sizeof(size32_t);
  15158. const size32_t * selections = (const size32_t *)selection.getdata();
  15159. resultJunctions = new Owned<IStrandJunction> [max];
  15160. for (unsigned i = 0; i < max; i++)
  15161. {
  15162. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  15163. selectedInputs.append(in);
  15164. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  15165. selectedJunctions.append(resultJunctions[i]);
  15166. }
  15167. }
  15168. protected:
  15169. void initInputSelection()
  15170. {
  15171. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  15172. if (selectionIsAll)
  15173. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  15174. }
  15175. };
  15176. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  15177. {
  15178. unsigned graphId;
  15179. public:
  15180. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  15181. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  15182. {
  15183. }
  15184. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15185. {
  15186. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  15187. }
  15188. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15189. {
  15190. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  15191. }
  15192. };
  15193. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  15194. {
  15195. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  15196. }
  15197. //=================================================================================
  15198. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  15199. {
  15200. public:
  15201. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  15202. IMPLEMENT_IINTERFACE
  15203. protected:
  15204. virtual const void * nextInputRow()
  15205. {
  15206. #ifdef TRACE_SEEK_REQUESTS
  15207. IRoxieContextLogger * logger = input->queryActivity();
  15208. const void * ret = doNextInputRow();
  15209. {
  15210. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15211. if (!ret)
  15212. xmlwrite.outputBool(true,"eof");
  15213. else if (input->queryOutputMeta()->hasXML())
  15214. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15215. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  15216. }
  15217. return ret;
  15218. #else
  15219. return inputStream->ungroupedNextRow();
  15220. #endif
  15221. }
  15222. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15223. {
  15224. #ifdef TRACE_SEEK_REQUESTS
  15225. IRoxieContextLogger * logger = input->queryActivity();
  15226. {
  15227. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15228. if (input->queryOutputMeta()->hasXML())
  15229. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  15230. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  15231. numFields,
  15232. stepExtra.readAheadManyResults() ? "readahead " : "",
  15233. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15234. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15235. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15236. xmlwrite.str());
  15237. }
  15238. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15239. {
  15240. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15241. if (!ret)
  15242. xmlwrite.outputBool(true,"eof");
  15243. else if (input->queryOutputMeta()->hasXML())
  15244. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15245. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  15246. numFields,
  15247. stepExtra.readAheadManyResults() ? "readahead " : "",
  15248. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15249. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15250. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15251. xmlwrite.str());
  15252. }
  15253. return ret;
  15254. #else
  15255. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15256. #endif
  15257. }
  15258. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15259. {
  15260. return input->gatherConjunctions(collector);
  15261. }
  15262. virtual void resetEOF()
  15263. {
  15264. inputStream->resetEOF();
  15265. }
  15266. virtual IInputSteppingMeta * queryInputSteppingMeta()
  15267. {
  15268. return input->querySteppingMeta();
  15269. }
  15270. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15271. {
  15272. assertex(wasCompleteMatch);
  15273. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15274. }
  15275. protected:
  15276. IFinalRoxieInput * input;
  15277. IEngineRowStream * inputStream;
  15278. };
  15279. //=================================================================================
  15280. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  15281. {
  15282. public:
  15283. CRoxieServerNWayBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15284. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15285. {
  15286. }
  15287. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15288. {
  15289. ForEachItemIn(ei, expandedInputs)
  15290. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  15291. ForEachItemIn(idx, expandedInputs)
  15292. startJunction(expandedJunctions.item(idx));
  15293. }
  15294. virtual void stop()
  15295. {
  15296. ForEachItemIn(i, expandedStreams)
  15297. expandedStreams.item(i)->stop();
  15298. CRoxieServerMultiInputBaseActivity::stop();
  15299. }
  15300. virtual void reset()
  15301. {
  15302. ForEachItemIn(idx, expandedInputs)
  15303. resetJunction(expandedJunctions.item(idx));
  15304. expandedInputs.kill();
  15305. expandedStreams.kill();
  15306. expandedJunctions.kill();
  15307. CRoxieServerMultiInputBaseActivity::reset();
  15308. }
  15309. protected:
  15310. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  15311. PointerArrayOf<IEngineRowStream> expandedStreams;
  15312. PointerArrayOf<IStrandJunction> expandedJunctions;
  15313. };
  15314. //=================================================================================
  15315. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  15316. {
  15317. public:
  15318. CRoxieServerNaryActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15319. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15320. {
  15321. }
  15322. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15323. {
  15324. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15325. for (unsigned i=0; i < numInputs; i++)
  15326. {
  15327. IFinalRoxieInput * cur = inputArray[i];
  15328. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15329. if (nWayInput)
  15330. {
  15331. nWayInput->start(parentExtractSize, parentExtract, paused);
  15332. unsigned numRealInputs = cur->numConcreteOutputs();
  15333. for (unsigned j = 0; j < numRealInputs; j++)
  15334. {
  15335. expandedInputs.append(cur->queryConcreteInput(j));
  15336. expandedStreams.append(cur->queryConcreteOutputStream(j));
  15337. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  15338. }
  15339. }
  15340. else
  15341. {
  15342. expandedInputs.append(cur);
  15343. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15344. expandedStreams.append(queryConcreteOutputStream(i));
  15345. expandedJunctions.append(queryConcreteOutputJunction(i));
  15346. }
  15347. }
  15348. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15349. }
  15350. };
  15351. //=================================================================================
  15352. class CRoxieStreamMerger : public CStreamMerger
  15353. {
  15354. public:
  15355. CRoxieStreamMerger() : CStreamMerger(true)
  15356. {
  15357. streamArray = NULL;
  15358. }
  15359. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  15360. {
  15361. CStreamMerger::initInputs(_numInputs);
  15362. streamArray = _streamArray;
  15363. }
  15364. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  15365. {
  15366. const void * next;
  15367. bool matches = true;
  15368. if (seek)
  15369. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  15370. else
  15371. next = streamArray[i]->ungroupedNextRow();
  15372. pending[i] = next;
  15373. pendingMatches[i] = matches;
  15374. return (next != NULL);
  15375. }
  15376. virtual void releaseRow(const void * row)
  15377. {
  15378. ReleaseRoxieRow(row);
  15379. }
  15380. protected:
  15381. IEngineRowStream **streamArray;
  15382. };
  15383. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  15384. {
  15385. public:
  15386. CRoxieServerNWayMergeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15387. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15388. helper((IHThorNWayMergeArg &)basehelper)
  15389. {
  15390. initializedMeta = false;
  15391. }
  15392. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15393. {
  15394. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15395. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  15396. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  15397. }
  15398. virtual void stop()
  15399. {
  15400. merger.done();
  15401. CRoxieServerNaryActivity::stop();
  15402. }
  15403. virtual void reset()
  15404. {
  15405. merger.cleanup();
  15406. CRoxieServerNaryActivity::reset();
  15407. initializedMeta = false;
  15408. }
  15409. virtual const void * nextRow()
  15410. {
  15411. ActivityTimer t(activityStats, timeActivities);
  15412. const void * next = merger.nextRow();
  15413. if (next)
  15414. processed++;
  15415. return next;
  15416. }
  15417. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15418. {
  15419. ActivityTimer t(activityStats, timeActivities);
  15420. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15421. if (next)
  15422. processed++;
  15423. return next;
  15424. }
  15425. virtual IInputSteppingMeta * querySteppingMeta()
  15426. {
  15427. if (expandedStreams.ordinality() == 0)
  15428. return NULL;
  15429. if (!initializedMeta)
  15430. {
  15431. meta.init(helper.querySteppingMeta(), false);
  15432. ForEachItemIn(i, expandedStreams)
  15433. {
  15434. if (meta.getNumFields() == 0)
  15435. break;
  15436. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  15437. meta.intersect(inputMeta);
  15438. }
  15439. initializedMeta = true;
  15440. }
  15441. if (meta.getNumFields() == 0)
  15442. return NULL;
  15443. return &meta;
  15444. }
  15445. protected:
  15446. IHThorNWayMergeArg &helper;
  15447. CRoxieStreamMerger merger;
  15448. CSteppingMeta meta;
  15449. bool initializedMeta;
  15450. };
  15451. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15452. {
  15453. public:
  15454. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15455. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15456. {
  15457. }
  15458. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15459. {
  15460. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15461. }
  15462. };
  15463. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15464. {
  15465. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15466. }
  15467. //=================================================================================
  15468. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15469. {
  15470. public:
  15471. CRoxieServerNWayMergeJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15472. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15473. helper((IHThorNWayMergeJoinArg &)basehelper),
  15474. processor(_processor)
  15475. {
  15476. }
  15477. virtual void onCreate(IHThorArg *_colocalParent)
  15478. {
  15479. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15480. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15481. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15482. }
  15483. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15484. {
  15485. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15486. ForEachItemIn(i1, expandedInputs)
  15487. {
  15488. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15489. processor.addInput(stepInput);
  15490. }
  15491. processor.beforeProcessing(inputAllocator, outputAllocator);
  15492. }
  15493. virtual void stop()
  15494. {
  15495. processor.afterProcessing();
  15496. CRoxieServerNaryActivity::stop();
  15497. }
  15498. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15499. {
  15500. return processor.gatherConjunctions(collector);
  15501. }
  15502. virtual void resetEOF()
  15503. {
  15504. processor.queryResetEOF();
  15505. }
  15506. virtual const void * nextRow()
  15507. {
  15508. ActivityTimer t(activityStats, timeActivities);
  15509. const void * next = processor.nextRow();
  15510. if (next)
  15511. processed++;
  15512. return next;
  15513. }
  15514. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15515. {
  15516. ActivityTimer t(activityStats, timeActivities);
  15517. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15518. if (next)
  15519. processed++;
  15520. return next;
  15521. }
  15522. virtual IInputSteppingMeta * querySteppingMeta()
  15523. {
  15524. return processor.queryInputSteppingMeta();
  15525. }
  15526. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15527. {
  15528. CRoxieServerNaryActivity::gatherStats(merged);
  15529. if (inputAllocator)
  15530. inputAllocator->gatherStats(merged);
  15531. if (outputAllocator)
  15532. outputAllocator->gatherStats(merged);
  15533. }
  15534. protected:
  15535. IHThorNWayMergeJoinArg & helper;
  15536. CMergeJoinProcessor & processor;
  15537. Owned<IEngineRowAllocator> inputAllocator;
  15538. Owned<IEngineRowAllocator> outputAllocator;
  15539. };
  15540. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15541. {
  15542. public:
  15543. CRoxieServerAndMergeJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15544. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15545. {
  15546. }
  15547. protected:
  15548. CAndMergeJoinProcessor andProcessor;
  15549. };
  15550. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15551. {
  15552. public:
  15553. CRoxieServerAndLeftMergeJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15554. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15555. {
  15556. }
  15557. protected:
  15558. CAndLeftMergeJoinProcessor andLeftProcessor;
  15559. };
  15560. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15561. {
  15562. public:
  15563. CRoxieServerMofNMergeJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15564. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15565. {
  15566. }
  15567. protected:
  15568. CMofNMergeJoinProcessor mofnProcessor;
  15569. };
  15570. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15571. {
  15572. public:
  15573. CRoxieServerProximityJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15574. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15575. {
  15576. }
  15577. protected:
  15578. CProximityJoinProcessor proximityProcessor;
  15579. };
  15580. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15581. {
  15582. unsigned flags;
  15583. public:
  15584. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15585. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15586. {
  15587. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15588. flags = helper->getJoinFlags();
  15589. }
  15590. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15591. {
  15592. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15593. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15594. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15595. {
  15596. case IHThorNWayMergeJoinArg::MJFinner:
  15597. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15598. case IHThorNWayMergeJoinArg::MJFleftonly:
  15599. case IHThorNWayMergeJoinArg::MJFleftouter:
  15600. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15601. case IHThorNWayMergeJoinArg::MJFmofn:
  15602. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15603. default:
  15604. throwUnexpected();
  15605. }
  15606. }
  15607. };
  15608. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15609. {
  15610. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15611. }
  15612. //=================================================================================
  15613. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15614. {
  15615. IHThorNWaySelectArg &helper;
  15616. public:
  15617. CRoxieServerNWaySelectActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15618. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15619. helper((IHThorNWaySelectArg &)basehelper)
  15620. {
  15621. }
  15622. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15623. {
  15624. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15625. unsigned whichInput = helper.getInputIndex();
  15626. selectedInput = nullptr;
  15627. selectedStream = nullptr;
  15628. if (whichInput--)
  15629. {
  15630. for (unsigned i=0; i < numInputs; i++)
  15631. {
  15632. IFinalRoxieInput * cur = inputArray[i];
  15633. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15634. if (nWayInput)
  15635. {
  15636. nWayInput->start(parentExtractSize, parentExtract, paused);
  15637. unsigned numRealInputs = cur->numConcreteOutputs();
  15638. if (whichInput < numRealInputs)
  15639. {
  15640. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15641. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15642. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15643. break;
  15644. }
  15645. whichInput -= numRealInputs;
  15646. }
  15647. else
  15648. {
  15649. if (whichInput == 0)
  15650. {
  15651. expandedInputs.append(cur);
  15652. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15653. expandedStreams.append(queryConcreteOutputStream(i));
  15654. expandedJunctions.append(queryConcreteOutputJunction(i));
  15655. break;
  15656. }
  15657. whichInput -= 1;
  15658. }
  15659. }
  15660. }
  15661. if (expandedInputs.ordinality())
  15662. {
  15663. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15664. selectedInput = expandedInputs.item(0);
  15665. selectedStream = expandedStreams.item(0);
  15666. }
  15667. }
  15668. const void * nextRow()
  15669. {
  15670. ActivityTimer t(activityStats, timeActivities);
  15671. if (!selectedStream)
  15672. return NULL;
  15673. return selectedStream->nextRow();
  15674. }
  15675. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15676. {
  15677. if (!selectedInput)
  15678. return false;
  15679. return selectedInput->gatherConjunctions(collector);
  15680. }
  15681. virtual void resetEOF()
  15682. {
  15683. if (selectedStream)
  15684. selectedStream->resetEOF();
  15685. }
  15686. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15687. {
  15688. ActivityTimer t(activityStats, timeActivities);
  15689. if (!selectedStream)
  15690. return NULL;
  15691. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15692. }
  15693. IInputSteppingMeta * querySteppingMeta()
  15694. {
  15695. if (selectedInput)
  15696. return selectedInput->querySteppingMeta();
  15697. return NULL;
  15698. }
  15699. protected:
  15700. IFinalRoxieInput * selectedInput = nullptr;
  15701. IEngineRowStream * selectedStream = nullptr;
  15702. Owned<IStrandJunction> selectedJunction;
  15703. };
  15704. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15705. {
  15706. public:
  15707. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15708. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15709. {
  15710. }
  15711. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15712. {
  15713. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15714. }
  15715. };
  15716. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15717. {
  15718. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15719. }
  15720. //=================================================================================
  15721. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15722. {
  15723. protected:
  15724. IHThorRemoteArg &helper;
  15725. CRemoteResultAdaptor remote;
  15726. public:
  15727. CRoxieServerRemoteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15728. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15729. helper((IHThorRemoteArg &)basehelper),
  15730. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15731. {
  15732. }
  15733. virtual const IResolvedFile *queryVarFileInfo() const
  15734. {
  15735. return NULL;
  15736. }
  15737. virtual void onCreate(IHThorArg *_colocalParent)
  15738. {
  15739. CRoxieServerActivity::onCreate(_colocalParent);
  15740. remote.onCreate(_colocalParent);
  15741. }
  15742. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15743. {
  15744. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15745. remote.onStart(parentExtractSize, parentExtract);
  15746. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15747. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15748. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15749. remote.flush();
  15750. remote.senddone();
  15751. }
  15752. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15753. {
  15754. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15755. }
  15756. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15757. {
  15758. if (idx==(unsigned)-1)
  15759. idx = 0;
  15760. return idx ? NULL: &remote;
  15761. }
  15762. virtual void reset()
  15763. {
  15764. processed = remote.processed;
  15765. remote.processed = 0;
  15766. CRoxieServerActivity::reset();
  15767. }
  15768. virtual void onLimitExceeded(bool isKeyed)
  15769. {
  15770. if (traceLevel > 4)
  15771. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15772. helper.onLimitExceeded();
  15773. }
  15774. virtual const void *createLimitFailRow(bool isKeyed)
  15775. {
  15776. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15777. }
  15778. virtual const void *nextRow()
  15779. {
  15780. throwUnexpected(); // I am nobody's input
  15781. }
  15782. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15783. {
  15784. CRoxieServerActivity::gatherStats(merged);
  15785. remote.gatherStats(merged);
  15786. }
  15787. };
  15788. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15789. {
  15790. public:
  15791. RemoteActivityId remoteId;
  15792. bool isRoot;
  15793. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15794. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15795. {
  15796. }
  15797. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15798. {
  15799. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15800. }
  15801. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15802. {
  15803. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15804. }
  15805. virtual bool isSink() const
  15806. {
  15807. //I don't think the action version of this is implemented - but this would be the code
  15808. return isRoot && !meta.queryOriginal();
  15809. }
  15810. virtual const StatisticsMapping &queryStatsMapping() const
  15811. {
  15812. return allStatistics; // Child queries...
  15813. }
  15814. };
  15815. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15816. {
  15817. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15818. }
  15819. //=================================================================================
  15820. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15821. {
  15822. IHThorIterateArg &helper;
  15823. OwnedConstRoxieRow defaultRecord;
  15824. OwnedConstRoxieRow left;
  15825. OwnedConstRoxieRow right;
  15826. unsigned counter;
  15827. public:
  15828. CRoxieServerIterateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15829. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15830. helper((IHThorIterateArg &)basehelper)
  15831. {
  15832. counter = 0;
  15833. }
  15834. virtual bool needsAllocator() const { return true; }
  15835. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15836. {
  15837. counter = 0;
  15838. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15839. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15840. size32_t thisSize = helper.createDefault(rowBuilder);
  15841. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15842. }
  15843. virtual void reset()
  15844. {
  15845. defaultRecord.clear();
  15846. right.clear();
  15847. left.clear();
  15848. CRoxieServerActivity::reset();
  15849. }
  15850. virtual const void * nextRow()
  15851. {
  15852. ActivityTimer t(activityStats, timeActivities);
  15853. for (;;)
  15854. {
  15855. right.setown(inputStream->nextRow());
  15856. if (!right)
  15857. {
  15858. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15859. left.clear();
  15860. counter = 0;
  15861. if (skippedGroup) continue;
  15862. return NULL;
  15863. }
  15864. try
  15865. {
  15866. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15867. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15868. if (outSize)
  15869. {
  15870. left.setown(rowBuilder.finalizeRowClear(outSize));
  15871. processed++;
  15872. return left.getLink();
  15873. }
  15874. }
  15875. catch (IException *E)
  15876. {
  15877. throw makeWrappedException(E);
  15878. }
  15879. }
  15880. }
  15881. };
  15882. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15883. {
  15884. public:
  15885. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15886. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15887. {
  15888. }
  15889. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15890. {
  15891. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15892. }
  15893. };
  15894. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15895. {
  15896. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15897. }
  15898. //=================================================================================
  15899. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15900. {
  15901. IHThorProcessArg &helper;
  15902. OwnedConstRoxieRow curRight;
  15903. OwnedConstRoxieRow initialRight;
  15904. unsigned counter;
  15905. Owned<IEngineRowAllocator> rightRowAllocator;
  15906. public:
  15907. CRoxieServerProcessActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15908. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15909. {
  15910. counter = 0;
  15911. }
  15912. virtual bool needsAllocator() const { return true; }
  15913. virtual void onCreate(IHThorArg *_colocalParent)
  15914. {
  15915. CRoxieServerActivity::onCreate(_colocalParent);
  15916. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15917. }
  15918. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15919. {
  15920. counter = 0;
  15921. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15922. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15923. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15924. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15925. curRight.set(initialRight);
  15926. }
  15927. virtual const void * nextRow()
  15928. {
  15929. ActivityTimer t(activityStats, timeActivities);
  15930. try
  15931. {
  15932. for (;;)
  15933. {
  15934. const void * in = inputStream->nextRow();
  15935. if (!in)
  15936. {
  15937. bool eog = (curRight != initialRight); // processed any records?
  15938. counter = 0;
  15939. curRight.set(initialRight);
  15940. if (eog)
  15941. return NULL;
  15942. in = inputStream->nextRow();
  15943. if (!in)
  15944. return NULL;
  15945. }
  15946. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15947. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15948. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15949. ReleaseRoxieRow(in);
  15950. if (outSize)
  15951. {
  15952. //MORE: This should be returned...
  15953. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15954. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15955. processed++;
  15956. return rowBuilder.finalizeRowClear(outSize);
  15957. }
  15958. }
  15959. }
  15960. catch (IException *E)
  15961. {
  15962. throw makeWrappedException(E);
  15963. }
  15964. }
  15965. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15966. {
  15967. CRoxieServerActivity::gatherStats(merged);
  15968. if (rightRowAllocator)
  15969. rightRowAllocator->gatherStats(merged);
  15970. }
  15971. };
  15972. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15973. {
  15974. public:
  15975. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15976. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15977. {
  15978. }
  15979. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  15980. {
  15981. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15982. }
  15983. };
  15984. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15985. {
  15986. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15987. }
  15988. //=================================================================================
  15989. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15990. {
  15991. IHThorGroupArg &helper;
  15992. bool endPending;
  15993. bool eof;
  15994. bool first;
  15995. unsigned numGroups;
  15996. unsigned numGroupMax;
  15997. unsigned numProcessedLastGroup;
  15998. const void *next;
  15999. public:
  16000. CRoxieServerGroupActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16001. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  16002. {
  16003. next = NULL;
  16004. endPending = false;
  16005. eof = false;
  16006. first = true;
  16007. numGroups = 0;
  16008. numGroupMax = 0;
  16009. numProcessedLastGroup = 0;
  16010. }
  16011. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16012. {
  16013. endPending = false;
  16014. eof = false;
  16015. first = true;
  16016. numGroups = 0;
  16017. numGroupMax = 0;
  16018. numProcessedLastGroup = processed;
  16019. assertex(next == NULL);
  16020. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16021. }
  16022. virtual void reset()
  16023. {
  16024. noteStatistic(StNumGroups, numGroups);
  16025. noteStatistic(StNumGroupMax, numGroupMax);
  16026. ReleaseClearRoxieRow(next);
  16027. CRoxieServerActivity::reset();
  16028. }
  16029. virtual const void * nextRow()
  16030. {
  16031. ActivityTimer t(activityStats, timeActivities);
  16032. if (first)
  16033. {
  16034. next = inputStream->nextRow();
  16035. first = false;
  16036. }
  16037. if (eof || endPending)
  16038. {
  16039. endPending = false;
  16040. return NULL;
  16041. }
  16042. const void * prev = next;
  16043. next = inputStream->ungroupedNextRow();
  16044. if (next)
  16045. {
  16046. assertex(prev);
  16047. if (!helper.isSameGroup(prev, next))
  16048. {
  16049. noteEndOfGroup();
  16050. endPending = true;
  16051. }
  16052. }
  16053. else
  16054. {
  16055. noteEndOfGroup();
  16056. eof = true;
  16057. }
  16058. if (prev)
  16059. processed++;
  16060. return prev;
  16061. }
  16062. inline void noteEndOfGroup()
  16063. {
  16064. unsigned numThisGroup = processed - numProcessedLastGroup;
  16065. if (numThisGroup == 0)
  16066. return;
  16067. numProcessedLastGroup = processed;
  16068. if (numThisGroup > numGroupMax)
  16069. numGroupMax = numThisGroup;
  16070. numGroups++;
  16071. }
  16072. };
  16073. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  16074. {
  16075. public:
  16076. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16077. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16078. {
  16079. }
  16080. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  16081. {
  16082. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  16083. }
  16084. virtual const StatisticsMapping &queryStatsMapping() const
  16085. {
  16086. return groupStatistics;
  16087. }
  16088. };
  16089. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16090. {
  16091. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16092. }
  16093. //=================================================================================
  16094. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  16095. {
  16096. unsigned __int64 limit;
  16097. unsigned __int64 skip;
  16098. unsigned doneThisGroup;
  16099. IHThorFirstNArg &helper;
  16100. public:
  16101. CRoxieServerFirstNActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16102. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  16103. {
  16104. doneThisGroup = 0;
  16105. limit = 0;
  16106. skip = 0;
  16107. }
  16108. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16109. {
  16110. doneThisGroup = 0;
  16111. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16112. limit = helper.getLimit();
  16113. skip = helper.numToSkip();
  16114. lateStart(parentExtractSize, parentExtract, limit > 0);
  16115. if (limit + skip >= limit)
  16116. limit += skip;
  16117. }
  16118. const void * nextRow()
  16119. {
  16120. ActivityTimer t(activityStats, timeActivities);
  16121. if (eof)
  16122. return NULL;
  16123. const void *ret;
  16124. for (;;)
  16125. {
  16126. ret = inputStream->nextRow();
  16127. if (!ret)
  16128. {
  16129. if (meta.isGrouped())
  16130. {
  16131. if (doneThisGroup > skip)
  16132. {
  16133. doneThisGroup = 0;
  16134. return NULL;
  16135. }
  16136. doneThisGroup = 0;
  16137. }
  16138. ret = inputStream->nextRow();
  16139. if (!ret)
  16140. {
  16141. eof = true;
  16142. return NULL;
  16143. }
  16144. }
  16145. doneThisGroup++;
  16146. if (doneThisGroup > skip)
  16147. break;
  16148. ReleaseRoxieRow(ret);
  16149. }
  16150. if (doneThisGroup <= limit)
  16151. {
  16152. processed++;
  16153. return ret;
  16154. }
  16155. ReleaseRoxieRow(ret);
  16156. if (meta.isGrouped())
  16157. {
  16158. while ((ret = inputStream->nextRow()) != NULL)
  16159. ReleaseRoxieRow(ret);
  16160. doneThisGroup = 0;
  16161. }
  16162. else
  16163. eof = true;
  16164. return NULL;
  16165. }
  16166. };
  16167. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  16168. {
  16169. public:
  16170. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16171. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16172. {
  16173. }
  16174. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  16175. {
  16176. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  16177. }
  16178. };
  16179. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16180. {
  16181. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16182. }
  16183. //=================================================================================
  16184. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  16185. {
  16186. bool done;
  16187. IHThorSelectNArg &helper;
  16188. public:
  16189. CRoxieServerSelectNActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16190. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  16191. {
  16192. done = false;
  16193. }
  16194. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16195. {
  16196. done = false;
  16197. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16198. }
  16199. const void *defaultRow()
  16200. {
  16201. if (!rowAllocator)
  16202. ensureRowAllocator(); // We delay as often not needed...
  16203. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16204. size32_t thisSize = helper.createDefault(rowBuilder);
  16205. return rowBuilder.finalizeRowClear(thisSize);
  16206. }
  16207. virtual const void * nextRow()
  16208. {
  16209. ActivityTimer t(activityStats, timeActivities);
  16210. if (done)
  16211. return NULL;
  16212. done = true;
  16213. processed++; // always going to return a row!
  16214. unsigned __int64 index = helper.getRowToSelect();
  16215. while (--index)
  16216. {
  16217. const void * next = inputStream->ungroupedNextRow();
  16218. if (!next)
  16219. return defaultRow();
  16220. ReleaseRoxieRow(next);
  16221. }
  16222. const void * next = inputStream->ungroupedNextRow();
  16223. if (!next)
  16224. next = defaultRow();
  16225. return next;
  16226. }
  16227. };
  16228. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  16229. {
  16230. public:
  16231. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16232. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16233. {
  16234. }
  16235. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  16236. {
  16237. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  16238. }
  16239. };
  16240. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16241. {
  16242. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16243. }
  16244. //=================================================================================
  16245. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  16246. {
  16247. IHThorJoinArg &helper;
  16248. ICompare *collate;
  16249. OwnedRowArray group;
  16250. bool matchedLeft;
  16251. BoolArray matchedRight;
  16252. bool eof;
  16253. bool first;
  16254. unsigned leftIndex;
  16255. unsigned rightIndex;
  16256. unsigned rightOuterIndex;
  16257. unsigned joinLimit;
  16258. unsigned atmostLimit;
  16259. unsigned atmostsTriggered;
  16260. unsigned abortLimit;
  16261. unsigned keepLimit;
  16262. unsigned joinCounter;
  16263. bool leftOuterJoin;
  16264. bool rightOuterJoin;
  16265. bool exclude;
  16266. bool limitFail;
  16267. bool limitOnFail;
  16268. bool cloneLeft;
  16269. bool forceSpill;
  16270. OwnedConstRoxieRow defaultLeft;
  16271. OwnedConstRoxieRow defaultRight;
  16272. OwnedConstRoxieRow lhs;
  16273. Owned<IException> failingLimit;
  16274. bool failingOuterAtmost;
  16275. Owned<IEngineRowAllocator> defaultAllocator;
  16276. Owned<IRHLimitedCompareHelper> limitedhelper;
  16277. Owned<CRHDualCache> dualcache;
  16278. Owned<IGroupedInput> groupedInput;
  16279. IRowStream *dualCacheInput;
  16280. bool fillGroup()
  16281. {
  16282. group.clear();
  16283. matchedLeft = false;
  16284. matchedRight.kill();
  16285. failingOuterAtmost = false;
  16286. const void * next;
  16287. unsigned groupCount = 0;
  16288. while((next = groupedInput->nextRow()) != NULL)
  16289. {
  16290. if(groupCount==abortLimit)
  16291. {
  16292. if(limitFail)
  16293. failLimit(next);
  16294. if (ctx->queryDebugContext())
  16295. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16296. if(limitOnFail)
  16297. {
  16298. assertex(!failingLimit);
  16299. try
  16300. {
  16301. failLimit(next);
  16302. }
  16303. catch(IException * except)
  16304. {
  16305. failingLimit.setown(except);
  16306. }
  16307. assertex(failingLimit != NULL);
  16308. group.append(next);
  16309. groupCount++;
  16310. break;
  16311. }
  16312. group.clear();
  16313. groupCount = 0;
  16314. while(next)
  16315. {
  16316. ReleaseRoxieRow(next);
  16317. next = groupedInput->nextRow();
  16318. }
  16319. }
  16320. else if(groupCount==atmostLimit)
  16321. {
  16322. atmostsTriggered++;
  16323. if(leftOuterJoin)
  16324. {
  16325. group.append(next);
  16326. groupCount++;
  16327. failingOuterAtmost = true;
  16328. break;
  16329. }
  16330. else
  16331. {
  16332. group.clear();
  16333. groupCount = 0;
  16334. while (next)
  16335. {
  16336. ReleaseRoxieRow(next);
  16337. next = groupedInput->nextRow();
  16338. }
  16339. }
  16340. }
  16341. else
  16342. {
  16343. group.append(next);
  16344. groupCount++;
  16345. }
  16346. }
  16347. if(group.ordinality()==0)
  16348. {
  16349. eof = true;
  16350. return false;
  16351. }
  16352. leftIndex = 0;
  16353. rightIndex = 0;
  16354. rightOuterIndex = 0;
  16355. joinCounter = 0;
  16356. joinLimit = keepLimit;
  16357. ForEachItemIn(idx, group)
  16358. matchedRight.append(false);
  16359. return true;
  16360. }
  16361. void failLimit(const void * next)
  16362. {
  16363. helper.onMatchAbortLimitExceeded();
  16364. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16365. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16366. {
  16367. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  16368. }
  16369. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  16370. }
  16371. virtual bool needsAllocator() const { return true; }
  16372. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except, unsigned flags)
  16373. {
  16374. try
  16375. {
  16376. if (cloneLeft && !except)
  16377. {
  16378. LinkRoxieRow(curLeft);
  16379. return curLeft;
  16380. }
  16381. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16382. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except, flags) : helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  16383. if (outsize)
  16384. return rowBuilder.finalizeRowClear(outsize);
  16385. else
  16386. return NULL;
  16387. }
  16388. catch (IException *E)
  16389. {
  16390. throw makeWrappedException(E);
  16391. }
  16392. }
  16393. void createDefaultLeft()
  16394. {
  16395. if (!defaultLeft)
  16396. {
  16397. if (!defaultAllocator)
  16398. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16399. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16400. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16401. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16402. }
  16403. }
  16404. void createDefaultRight()
  16405. {
  16406. if (!defaultRight)
  16407. {
  16408. if (!defaultAllocator)
  16409. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16410. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16411. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16412. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16413. }
  16414. }
  16415. public:
  16416. CRoxieServerSelfJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  16417. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  16418. {
  16419. collate = helper.queryCompareLeftRight();
  16420. eof = false;
  16421. first = true;
  16422. keepLimit = 0;
  16423. atmostLimit = 0;
  16424. atmostsTriggered = 0;
  16425. unsigned joinFlags = helper.getJoinFlags();
  16426. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16427. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16428. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16429. exclude = (joinFlags & JFexclude) != 0;
  16430. abortLimit = 0;
  16431. joinLimit = 0;
  16432. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  16433. getLimitType(joinFlags, limitFail, limitOnFail);
  16434. if((joinFlags & JFslidingmatch) != 0)
  16435. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  16436. failingOuterAtmost = false;
  16437. matchedLeft = false;
  16438. leftIndex = 0;
  16439. rightIndex = 0;
  16440. rightOuterIndex = 0;
  16441. joinCounter = 0;
  16442. dualCacheInput = NULL;
  16443. }
  16444. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16445. {
  16446. eof = false;
  16447. first = true;
  16448. failingLimit.clear();
  16449. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16450. keepLimit = helper.getKeepLimit();
  16451. if(keepLimit == 0)
  16452. keepLimit = (unsigned)-1;
  16453. atmostsTriggered = 0;
  16454. atmostLimit = helper.getJoinLimit();
  16455. if(atmostLimit == 0)
  16456. atmostLimit = (unsigned)-1;
  16457. else
  16458. assertex(!rightOuterJoin);
  16459. abortLimit = helper.getMatchAbortLimit();
  16460. if (abortLimit == 0)
  16461. abortLimit = (unsigned)-1;
  16462. if (rightOuterJoin)
  16463. createDefaultLeft();
  16464. if (leftOuterJoin || limitOnFail)
  16465. createDefaultRight();
  16466. ICompare *compareLeft = helper.queryCompareLeft();
  16467. if (helper.isLeftAlreadySorted())
  16468. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16469. else
  16470. {
  16471. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16472. RoxieSortAlgorithm sortAlgorithm;
  16473. if (forceSpill)
  16474. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16475. else
  16476. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16477. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16478. }
  16479. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16480. { //limited match join (s[1..n])
  16481. dualcache.setown(new CRHDualCache());
  16482. dualcache->init(groupedInput);
  16483. dualCacheInput = dualcache->queryOut1();
  16484. failingOuterAtmost = false;
  16485. matchedLeft = false;
  16486. leftIndex = 0;
  16487. rightOuterIndex = 0;
  16488. joinCounter = 0;
  16489. limitedhelper.setown(createRHLimitedCompareHelper());
  16490. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16491. }
  16492. }
  16493. virtual void reset()
  16494. {
  16495. if (atmostsTriggered)
  16496. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16497. group.clear();
  16498. groupedInput.clear();
  16499. CRoxieServerActivity::reset();
  16500. defaultLeft.clear();
  16501. defaultRight.clear();
  16502. }
  16503. virtual const void * nextRow()
  16504. {
  16505. ActivityTimer t(activityStats, timeActivities);
  16506. if (limitedhelper)
  16507. {
  16508. while(!eof) //limited match join
  16509. {
  16510. if (!group.isItem(rightIndex))
  16511. {
  16512. lhs.setown(dualCacheInput->nextRow());
  16513. if (lhs)
  16514. {
  16515. rightIndex = 0;
  16516. joinCounter = 0;
  16517. group.clear();
  16518. limitedhelper->getGroup(group,lhs);
  16519. }
  16520. else
  16521. {
  16522. eof = true;
  16523. }
  16524. }
  16525. if (group.isItem(rightIndex))
  16526. {
  16527. const void * rhs = group.item(rightIndex++);
  16528. if(helper.match(lhs, rhs))
  16529. {
  16530. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16531. if(ret)
  16532. {
  16533. processed++;
  16534. return ret;
  16535. }
  16536. }
  16537. }
  16538. }
  16539. return NULL;
  16540. }
  16541. else
  16542. {
  16543. if (first)
  16544. {
  16545. first = false;
  16546. fillGroup();
  16547. }
  16548. while(!eof)
  16549. {
  16550. if(failingOuterAtmost)
  16551. while(group.isItem(leftIndex))
  16552. {
  16553. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL, JTFmatchedleft);
  16554. if(ret)
  16555. {
  16556. processed++;
  16557. return ret;
  16558. }
  16559. }
  16560. if((joinLimit == 0) || !group.isItem(rightIndex))
  16561. {
  16562. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16563. {
  16564. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL, JTFmatchedleft);
  16565. if(ret)
  16566. {
  16567. matchedLeft = true;
  16568. processed++;
  16569. return ret;
  16570. }
  16571. }
  16572. leftIndex++;
  16573. matchedLeft = false;
  16574. rightIndex = 0;
  16575. joinCounter = 0;
  16576. joinLimit = keepLimit;
  16577. }
  16578. if(!group.isItem(leftIndex))
  16579. {
  16580. if(failingLimit || failingOuterAtmost)
  16581. {
  16582. const void * lhs;
  16583. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16584. {
  16585. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16586. ReleaseRoxieRow(lhs);
  16587. if(ret)
  16588. {
  16589. processed++;
  16590. return ret;
  16591. }
  16592. }
  16593. failingLimit.clear();
  16594. }
  16595. if(rightOuterJoin && !failingLimit)
  16596. while(group.isItem(rightOuterIndex))
  16597. if(!matchedRight.item(rightOuterIndex++))
  16598. {
  16599. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL, JTFmatchedright);
  16600. if(ret)
  16601. {
  16602. processed++;
  16603. return ret;
  16604. }
  16605. }
  16606. if(!fillGroup())
  16607. return NULL;
  16608. continue;
  16609. }
  16610. const void * lhs = group.item(leftIndex);
  16611. if(failingLimit)
  16612. {
  16613. leftIndex++;
  16614. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16615. if(ret)
  16616. {
  16617. processed++;
  16618. return ret;
  16619. }
  16620. }
  16621. else
  16622. {
  16623. const void * rhs = group.item(rightIndex++);
  16624. if(helper.match(lhs, rhs))
  16625. {
  16626. matchedLeft = true;
  16627. matchedRight.replace(true, rightIndex-1);
  16628. if(!exclude)
  16629. {
  16630. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16631. if(ret)
  16632. {
  16633. processed++;
  16634. joinLimit--;
  16635. return ret;
  16636. }
  16637. }
  16638. }
  16639. }
  16640. }
  16641. return NULL;
  16642. }
  16643. }
  16644. };
  16645. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16646. {
  16647. bool forceSpill;
  16648. public:
  16649. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16650. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16651. {
  16652. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16653. }
  16654. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  16655. {
  16656. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16657. }
  16658. virtual const StatisticsMapping &queryStatsMapping() const
  16659. {
  16660. return joinStatistics;
  16661. }
  16662. };
  16663. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16664. {
  16665. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16666. }
  16667. //=====================================================================================================
  16668. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16669. {
  16670. private:
  16671. class LookupTable : public CInterface
  16672. {
  16673. public:
  16674. LookupTable(IHThorHashJoinArg &helper)
  16675. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16676. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16677. {
  16678. size = 0;
  16679. }
  16680. virtual const void *find(const void * left) const = 0;
  16681. virtual const void *findNext(const void * left) const = 0;
  16682. protected:
  16683. ICompare * leftRightCompare;
  16684. ICompare * rightCompare;
  16685. IHash * leftHash;
  16686. IHash * rightHash;
  16687. unsigned size;
  16688. };
  16689. class DedupLookupTable : public LookupTable
  16690. {
  16691. public:
  16692. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16693. : LookupTable(helper)
  16694. {
  16695. size = (4*rightRows.length())/3 + 1;
  16696. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16697. ForEachItemIn(idx, rightRows)
  16698. add(rightRows.item(idx));
  16699. }
  16700. ~DedupLookupTable()
  16701. {
  16702. roxiemem::ReleaseRoxieRowArray(size, table);
  16703. free(table);
  16704. }
  16705. virtual const void *find(const void * left) const
  16706. {
  16707. unsigned index = leftHash->hash(left) % size;
  16708. unsigned start = index;
  16709. while (table[index])
  16710. {
  16711. if(leftRightCompare->docompare(left, table[index]) == 0)
  16712. return table[index];
  16713. index++;
  16714. if (index==size)
  16715. index = 0;
  16716. if (index==start)
  16717. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16718. }
  16719. return NULL;
  16720. }
  16721. virtual const void *findNext(const void * left) const
  16722. {
  16723. return NULL;
  16724. }
  16725. protected:
  16726. void add(const void * right)
  16727. {
  16728. unsigned index = rightHash->hash(right) % size;
  16729. unsigned start = index;
  16730. while (table[index])
  16731. {
  16732. if (rightCompare->docompare(table[index], right) == 0)
  16733. {
  16734. ReleaseRoxieRow(right);
  16735. return;
  16736. }
  16737. index++;
  16738. if (index==size)
  16739. index = 0;
  16740. if (index==start)
  16741. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16742. }
  16743. table[index] = right;
  16744. }
  16745. const void * * table;
  16746. };
  16747. class FewLookupTable : public LookupTable
  16748. {
  16749. public:
  16750. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16751. : LookupTable(helper)
  16752. {
  16753. size = (4*rightRows.length())/3 + 1;
  16754. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16755. findex = fstart = BadIndex;
  16756. ForEachItemIn(idx, rightRows)
  16757. add(rightRows.item(idx));
  16758. }
  16759. ~FewLookupTable()
  16760. {
  16761. roxiemem::ReleaseRoxieRowArray(size, table);
  16762. free(table);
  16763. }
  16764. virtual const void *find(const void * left) const
  16765. {
  16766. fstart = leftHash->hash(left) % size;
  16767. findex = fstart;
  16768. return doFind(left);
  16769. }
  16770. virtual const void *findNext(const void * left) const
  16771. {
  16772. if (findex == BadIndex)
  16773. return NULL;
  16774. advance();
  16775. return doFind(left);
  16776. }
  16777. protected:
  16778. void add(const void * right)
  16779. {
  16780. unsigned start = rightHash->hash(right) % size;
  16781. unsigned index = start;
  16782. while (table[index])
  16783. {
  16784. index++;
  16785. if (index==size)
  16786. index = 0;
  16787. if (index==start)
  16788. throwUnexpected(); //table is full, should never happen
  16789. }
  16790. table[index] = right;
  16791. }
  16792. void advance() const
  16793. {
  16794. findex++;
  16795. if(findex==size)
  16796. findex = 0;
  16797. if(findex==fstart)
  16798. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16799. }
  16800. const void *doFind(const void * left) const
  16801. {
  16802. while(table[findex])
  16803. {
  16804. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16805. return table[findex];
  16806. advance();
  16807. }
  16808. findex = BadIndex;
  16809. return NULL;
  16810. }
  16811. const void * * table;
  16812. unsigned mutable fstart;
  16813. unsigned mutable findex;
  16814. static unsigned const BadIndex;
  16815. };
  16816. class ManyLookupTable : public LookupTable
  16817. {
  16818. public:
  16819. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16820. : LookupTable(helper)
  16821. {
  16822. rightRows.swapWith(rowtable);
  16823. UInt64Array groups;
  16824. unsigned numRows = rowtable.length();
  16825. if (numRows)
  16826. {
  16827. unsigned groupStart = 0;
  16828. const void *groupStartRow = rowtable.item(0);
  16829. for (unsigned i=1; i < numRows; i++)
  16830. {
  16831. const void *thisRow = rowtable.item(i);
  16832. if (rightCompare->docompare(groupStartRow, thisRow))
  16833. {
  16834. groups.append(makeint64(groupStart, i-groupStart));
  16835. groupStart = i;
  16836. groupStartRow = thisRow;
  16837. }
  16838. }
  16839. groups.append(makeint64(groupStart, numRows-groupStart));
  16840. }
  16841. size = (4*groups.length())/3 + 1;
  16842. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16843. ForEachItemIn(idx, groups)
  16844. {
  16845. unsigned __int64 group = groups.item(idx);
  16846. unsigned groupstart = high(group);
  16847. const void *row = rowtable.item(groupstart);
  16848. add(row, group);
  16849. }
  16850. }
  16851. ~ManyLookupTable()
  16852. {
  16853. roxiemem::ReleaseRoxieRows(rowtable);
  16854. free(table);
  16855. }
  16856. void add(const void *row, unsigned __int64 group)
  16857. {
  16858. unsigned start = rightHash->hash(row) % size;
  16859. unsigned index = start;
  16860. while (table[index])
  16861. {
  16862. index++;
  16863. if (index==size)
  16864. index = 0;
  16865. if (index==start)
  16866. throwUnexpected(); //table is full, should never happen
  16867. }
  16868. table[index] = group;
  16869. }
  16870. virtual const void *find(const void * left) const
  16871. {
  16872. unsigned index = leftHash->hash(left) % size;
  16873. unsigned start = index;
  16874. while (table[index])
  16875. {
  16876. __uint64 group = table[index];
  16877. currentMatch = high(group);
  16878. const void *right = rowtable.item(currentMatch);
  16879. if (leftRightCompare->docompare(left, right) == 0)
  16880. {
  16881. currentMatch++;
  16882. matchCount = low(group) - 1;
  16883. return right;
  16884. }
  16885. index++;
  16886. if (index==size)
  16887. index = 0;
  16888. if (index==start)
  16889. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16890. }
  16891. matchCount = 0;
  16892. return NULL;
  16893. }
  16894. virtual const void *findNext(const void * left) const
  16895. {
  16896. if (!matchCount)
  16897. return NULL;
  16898. matchCount--;
  16899. return rowtable.item(currentMatch++);
  16900. }
  16901. protected:
  16902. __uint64 *table;
  16903. ConstPointerArray rowtable;
  16904. mutable unsigned currentMatch = 0;
  16905. mutable unsigned matchCount = 0;
  16906. };
  16907. IHThorHashJoinArg &helper;
  16908. bool leftOuterJoin;
  16909. bool exclude;
  16910. bool eog;
  16911. bool many;
  16912. bool dedupRHS;
  16913. bool useFewTable;
  16914. bool matchedGroup;
  16915. const void *left;
  16916. OwnedConstRoxieRow defaultRight;
  16917. Owned<LookupTable> table;
  16918. unsigned keepLimit;
  16919. unsigned atmostLimit;
  16920. unsigned atmostsTriggered;
  16921. unsigned limitLimit;
  16922. unsigned joinCounter;
  16923. bool limitFail;
  16924. bool limitOnFail;
  16925. bool hasGroupLimit;
  16926. bool isSmartJoin;
  16927. unsigned keepCount;
  16928. bool gotMatch;
  16929. bool cloneLeft;
  16930. ConstPointerArray rightGroup;
  16931. aindex_t rightGroupIndex;
  16932. Owned<IException> failingLimit;
  16933. ConstPointerArray filteredRight;
  16934. ThorActivityKind activityKind;
  16935. Owned<IEngineRowAllocator> defaultRightAllocator;
  16936. void createDefaultRight()
  16937. {
  16938. if (!defaultRight)
  16939. {
  16940. if (!defaultRightAllocator)
  16941. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16942. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16943. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16944. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16945. }
  16946. }
  16947. public:
  16948. CRoxieServerLookupJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16949. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16950. {
  16951. unsigned joinFlags = helper.getJoinFlags();
  16952. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16953. assertex((joinFlags & JFrightouter) == 0);
  16954. exclude = (joinFlags & JFexclude) != 0;
  16955. many = (joinFlags & JFmanylookup) != 0;
  16956. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16957. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16958. left = NULL;
  16959. activityKind = factory->getKind();
  16960. eog = false;
  16961. matchedGroup = false;
  16962. gotMatch = false;
  16963. keepLimit = 0;
  16964. keepCount = 0;
  16965. joinCounter = 0;
  16966. atmostLimit = 0;
  16967. atmostsTriggered = 0;
  16968. limitLimit = 0;
  16969. rightGroupIndex = 0;
  16970. hasGroupLimit = false;
  16971. isSmartJoin = (joinFlags & JFsmart) != 0;
  16972. getLimitType(joinFlags, limitFail, limitOnFail);
  16973. }
  16974. void loadRight()
  16975. {
  16976. ConstPointerArray rightset;
  16977. try
  16978. {
  16979. const void * next;
  16980. while(true)
  16981. {
  16982. next = inputStream1->ungroupedNextRow();
  16983. if(!next)
  16984. break;
  16985. rightset.append(next);
  16986. }
  16987. if (!dedupRHS)
  16988. {
  16989. if (useFewTable)
  16990. {
  16991. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16992. }
  16993. else
  16994. {
  16995. if (!helper.isRightAlreadySorted())
  16996. {
  16997. if (helper.getJoinFlags() & JFunstable)
  16998. {
  16999. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  17000. }
  17001. else
  17002. {
  17003. unsigned rightord = rightset.ordinality();
  17004. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  17005. void **temp = (void **) tempAttr.bufferBase();
  17006. void **_rows = const_cast<void * *>(rightset.getArray());
  17007. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  17008. }
  17009. }
  17010. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  17011. }
  17012. }
  17013. else
  17014. {
  17015. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  17016. }
  17017. }
  17018. catch (...)
  17019. {
  17020. roxiemem::ReleaseRoxieRows(rightset);
  17021. throw;
  17022. }
  17023. };
  17024. virtual void reset()
  17025. {
  17026. if (atmostsTriggered)
  17027. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  17028. CRoxieServerTwoInputActivity::reset();
  17029. ReleaseClearRoxieRow(left);
  17030. defaultRight.clear();
  17031. table.clear();
  17032. }
  17033. virtual bool needsAllocator() const { return true; }
  17034. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17035. {
  17036. eog = false;
  17037. matchedGroup = false;
  17038. left = NULL;
  17039. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17040. keepLimit = helper.getKeepLimit();
  17041. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  17042. atmostsTriggered = 0;
  17043. atmostLimit = helper.getJoinLimit();
  17044. limitLimit = helper.getMatchAbortLimit();
  17045. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  17046. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  17047. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  17048. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  17049. switch (activityKind)
  17050. {
  17051. case TAKlookupjoin:
  17052. case TAKlookupdenormalizegroup:
  17053. case TAKsmartjoin:
  17054. case TAKsmartdenormalizegroup:
  17055. if (leftOuterJoin)
  17056. createDefaultRight();
  17057. break;
  17058. }
  17059. if (limitOnFail)
  17060. createDefaultRight();
  17061. }
  17062. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17063. {
  17064. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17065. {
  17066. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17067. puller->setInput(0, _sourceIdx, _in);
  17068. _in = puller;
  17069. _sourceIdx = 0;
  17070. }
  17071. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17072. }
  17073. virtual const void * nextRow()
  17074. {
  17075. ActivityTimer t(activityStats, timeActivities);
  17076. if(!table)
  17077. loadRight();
  17078. switch (activityKind)
  17079. {
  17080. case TAKlookupjoin:
  17081. case TAKsmartjoin:
  17082. return nextRowJoin();
  17083. case TAKlookupdenormalize:
  17084. case TAKlookupdenormalizegroup:
  17085. case TAKsmartdenormalize:
  17086. case TAKsmartdenormalizegroup:
  17087. return nextRowDenormalize();
  17088. }
  17089. throwUnexpected();
  17090. }
  17091. private:
  17092. const void * nextRowJoin()
  17093. {
  17094. if(!table)
  17095. loadRight();
  17096. while(true)
  17097. {
  17098. const void * right = NULL;
  17099. if(!left)
  17100. {
  17101. left = inputStream->nextRow();
  17102. keepCount = keepLimit;
  17103. joinCounter = 0;
  17104. if(!left)
  17105. {
  17106. if (isSmartJoin)
  17107. left = inputStream->nextRow();
  17108. if (!left)
  17109. {
  17110. if(matchedGroup || eog)
  17111. {
  17112. matchedGroup = false;
  17113. eog = true;
  17114. return NULL;
  17115. }
  17116. eog = true;
  17117. continue;
  17118. }
  17119. }
  17120. eog = false;
  17121. gotMatch = false;
  17122. right = getRightFirst();
  17123. }
  17124. else
  17125. right = getRightNext();
  17126. const void * ret = NULL;
  17127. if(failingLimit)
  17128. {
  17129. ret = joinException(left, failingLimit);
  17130. }
  17131. else
  17132. {
  17133. while(right)
  17134. {
  17135. if(helper.match(left, right))
  17136. {
  17137. gotMatch = true;
  17138. if(exclude)
  17139. break;
  17140. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17141. if(ret)
  17142. {
  17143. processed++;
  17144. break;
  17145. }
  17146. }
  17147. right = getRightNext();
  17148. ret = NULL;
  17149. }
  17150. if(leftOuterJoin && !gotMatch)
  17151. {
  17152. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17153. gotMatch = true;
  17154. }
  17155. }
  17156. if(ret)
  17157. {
  17158. matchedGroup = true;
  17159. processed++;
  17160. if(!many || (--keepCount == 0) || failingLimit)
  17161. {
  17162. ReleaseClearRoxieRow(left);
  17163. failingLimit.clear();
  17164. }
  17165. return ret;
  17166. }
  17167. ReleaseClearRoxieRow(left);
  17168. }
  17169. }
  17170. const void * nextRowDenormalize()
  17171. {
  17172. while(true)
  17173. {
  17174. left = inputStream->nextRow();
  17175. if(!left)
  17176. {
  17177. if (!matchedGroup || isSmartJoin)
  17178. left = inputStream->nextRow();
  17179. if (!left)
  17180. {
  17181. matchedGroup = false;
  17182. return NULL;
  17183. }
  17184. }
  17185. gotMatch = false;
  17186. const void * right = getRightFirst();
  17187. const void * ret = NULL;
  17188. if (failingLimit)
  17189. ret = joinException(left, failingLimit);
  17190. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  17191. {
  17192. OwnedConstRoxieRow newLeft;
  17193. newLeft.set(left);
  17194. unsigned rowSize = 0;
  17195. unsigned leftCount = 0;
  17196. keepCount = keepLimit;
  17197. while (right)
  17198. {
  17199. try
  17200. {
  17201. if (helper.match(left, right))
  17202. {
  17203. gotMatch = true;
  17204. if (exclude)
  17205. break;
  17206. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17207. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17208. if (thisSize)
  17209. {
  17210. rowSize = thisSize;
  17211. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17212. }
  17213. if(!many || (--keepCount == 0))
  17214. break;
  17215. }
  17216. right = getRightNext();
  17217. }
  17218. catch (IException *E)
  17219. {
  17220. throw makeWrappedException(E);
  17221. }
  17222. }
  17223. if (rowSize)
  17224. ret = newLeft.getClear();
  17225. else if (leftOuterJoin && !gotMatch)
  17226. {
  17227. ret = left;
  17228. left = NULL;
  17229. }
  17230. }
  17231. else
  17232. {
  17233. filteredRight.kill();
  17234. keepCount = keepLimit;
  17235. while (right)
  17236. {
  17237. if (helper.match(left, right))
  17238. {
  17239. gotMatch = true;
  17240. if(exclude)
  17241. break;
  17242. filteredRight.append(right);
  17243. if(!many || (--keepCount == 0))
  17244. break;
  17245. }
  17246. right = getRightNext();
  17247. }
  17248. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  17249. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17250. filteredRight.kill();
  17251. }
  17252. ReleaseRoxieRow(left);
  17253. left = NULL;
  17254. failingLimit.clear();
  17255. if(ret)
  17256. {
  17257. matchedGroup = true;
  17258. processed++;
  17259. return ret;
  17260. }
  17261. }
  17262. }
  17263. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17264. {
  17265. if (cloneLeft)
  17266. {
  17267. LinkRoxieRow(left);
  17268. return left;
  17269. }
  17270. try
  17271. {
  17272. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17273. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17274. if (outSize)
  17275. return rowBuilder.finalizeRowClear(outSize);
  17276. else
  17277. return NULL;
  17278. }
  17279. catch (IException *E)
  17280. {
  17281. throw makeWrappedException(E);
  17282. }
  17283. }
  17284. const void * joinException(const void * left, IException * except)
  17285. {
  17286. try
  17287. {
  17288. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17289. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except, JTFmatchedleft);
  17290. if (outSize)
  17291. return rowBuilder.finalizeRowClear(outSize);
  17292. else
  17293. return NULL;
  17294. }
  17295. catch (IException *E)
  17296. {
  17297. throw makeWrappedException(E);
  17298. }
  17299. }
  17300. const void * denormalizeRecords(const void * left, ConstPointerArray & rows, unsigned flags)
  17301. {
  17302. try
  17303. {
  17304. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17305. unsigned numRows = rows.ordinality();
  17306. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17307. if (numRows>0)
  17308. flags |= JTFmatchedright;
  17309. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray(), flags);
  17310. if (outSize)
  17311. return rowBuilder.finalizeRowClear(outSize);
  17312. else
  17313. return NULL;
  17314. }
  17315. catch (IException *E)
  17316. {
  17317. throw makeWrappedException(E);
  17318. }
  17319. }
  17320. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  17321. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  17322. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  17323. const void *fillRightGroup()
  17324. {
  17325. rightGroup.kill();
  17326. for(const void * right = table->find(left); right; right = table->findNext(left))
  17327. {
  17328. rightGroup.append(right);
  17329. if(rightGroup.ordinality() > limitLimit)
  17330. {
  17331. if(limitFail)
  17332. failLimit();
  17333. gotMatch = true;
  17334. if (ctx->queryDebugContext())
  17335. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17336. if(limitOnFail)
  17337. {
  17338. assertex(!failingLimit);
  17339. try
  17340. {
  17341. failLimit();
  17342. }
  17343. catch(IException * e)
  17344. {
  17345. failingLimit.setown(e);
  17346. }
  17347. assertex(failingLimit != NULL);
  17348. }
  17349. else
  17350. {
  17351. rightGroup.kill();
  17352. }
  17353. break;
  17354. }
  17355. if(rightGroup.ordinality() > atmostLimit)
  17356. {
  17357. atmostsTriggered++;
  17358. rightGroup.kill();
  17359. break;
  17360. }
  17361. }
  17362. rightGroupIndex = 0;
  17363. return readRightGroup();
  17364. }
  17365. void failLimit()
  17366. {
  17367. helper.onMatchAbortLimitExceeded();
  17368. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  17369. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  17370. {
  17371. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  17372. }
  17373. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  17374. }
  17375. };
  17376. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  17377. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17378. {
  17379. public:
  17380. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17381. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17382. {
  17383. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  17384. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  17385. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  17386. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  17387. }
  17388. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  17389. {
  17390. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  17391. }
  17392. virtual const StatisticsMapping &queryStatsMapping() const
  17393. {
  17394. return joinStatistics;
  17395. }
  17396. protected:
  17397. bool useFewTable;
  17398. };
  17399. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17400. {
  17401. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17402. }
  17403. //=====================================================================================================
  17404. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  17405. {
  17406. private:
  17407. IHThorAllJoinArg &helper;
  17408. bool leftOuterJoin;
  17409. bool rightOuterJoin;
  17410. bool exclude;
  17411. OwnedConstRoxieRow defaultRight;
  17412. OwnedConstRoxieRow defaultLeft;
  17413. Owned<IEngineRowAllocator> defaultRightAllocator;
  17414. Owned<IEngineRowAllocator> defaultLeftAllocator;
  17415. const void *left;
  17416. unsigned countForLeft;
  17417. ConstPointerArray rightset;
  17418. BoolArray matchedRight; // MORE - could use a bitset...
  17419. unsigned keepLimit;
  17420. bool started;
  17421. bool eog;
  17422. bool eos;
  17423. bool matchedLeft;
  17424. bool matchedGroup;
  17425. bool leftIsGrouped;
  17426. bool cloneLeft;
  17427. unsigned rightIndex;
  17428. unsigned joinCounter;
  17429. unsigned rightOrdinality;
  17430. ThorActivityKind activityKind;
  17431. ConstPointerArray filteredRight;
  17432. void createDefaultLeft()
  17433. {
  17434. if (!defaultLeft)
  17435. {
  17436. if (!defaultLeftAllocator)
  17437. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  17438. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  17439. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  17440. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  17441. }
  17442. }
  17443. void createDefaultRight()
  17444. {
  17445. if (!defaultRight)
  17446. {
  17447. if (!defaultRightAllocator)
  17448. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17449. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17450. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17451. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17452. }
  17453. }
  17454. public:
  17455. CRoxieServerAllJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17456. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17457. {
  17458. unsigned joinFlags = helper.getJoinFlags();
  17459. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17460. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17461. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17462. keepLimit = (unsigned) -1;
  17463. exclude = (joinFlags & JFexclude) != 0;
  17464. left = NULL;
  17465. started = true;
  17466. eog = false;
  17467. eos = false;
  17468. matchedLeft = false;
  17469. matchedGroup = false;
  17470. activityKind = factory->getKind();
  17471. rightIndex = 0;
  17472. rightOrdinality = 0;
  17473. leftIsGrouped = false;
  17474. countForLeft = 0;
  17475. joinCounter = 0;
  17476. }
  17477. virtual void reset()
  17478. {
  17479. defaultRight.clear();
  17480. defaultLeft.clear();
  17481. ReleaseRoxieRows(rightset);
  17482. if (left)
  17483. {
  17484. ReleaseRoxieRow(left);
  17485. left = nullptr;
  17486. }
  17487. matchedRight.kill();
  17488. CRoxieServerTwoInputActivity::reset();
  17489. }
  17490. virtual bool needsAllocator() const { return true; }
  17491. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17492. {
  17493. eog = false;
  17494. eos = false;
  17495. matchedLeft = false;
  17496. matchedGroup = false;
  17497. started = false;
  17498. left = NULL;
  17499. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17500. keepLimit = helper.getKeepLimit();
  17501. if(keepLimit==0)
  17502. keepLimit = (unsigned) -1;
  17503. countForLeft = keepLimit;
  17504. joinCounter = 0;
  17505. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17506. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17507. createDefaultRight();
  17508. if(rightOuterJoin)
  17509. createDefaultLeft();
  17510. }
  17511. void loadRight()
  17512. {
  17513. const void * next;
  17514. while(true)
  17515. {
  17516. next = inputStream1->ungroupedNextRow();
  17517. if(!next)
  17518. break;
  17519. rightset.append(next);
  17520. matchedRight.append(false);
  17521. }
  17522. rightIndex = 0;
  17523. joinCounter = 0;
  17524. rightOrdinality = rightset.ordinality();
  17525. }
  17526. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17527. {
  17528. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17529. {
  17530. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17531. puller->setInput(0, _sourceIdx, _in);
  17532. _in = puller;
  17533. _sourceIdx = 0;
  17534. }
  17535. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17536. }
  17537. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17538. {
  17539. // MORE - could share some code with lookup join
  17540. if (cloneLeft)
  17541. {
  17542. LinkRoxieRow(left);
  17543. return left;
  17544. }
  17545. try
  17546. {
  17547. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17548. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17549. if (outSize)
  17550. return rowBuilder.finalizeRowClear(outSize);
  17551. else
  17552. return NULL;
  17553. }
  17554. catch (IException *E)
  17555. {
  17556. throw makeWrappedException(E);
  17557. }
  17558. }
  17559. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  17560. {
  17561. try
  17562. {
  17563. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17564. unsigned numRows = rows.ordinality();
  17565. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17566. if (numRows>0)
  17567. flags |= JTFmatchedright;
  17568. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray(), flags);
  17569. if (outSize)
  17570. return rowBuilder.finalizeRowClear(outSize);
  17571. else
  17572. return NULL;
  17573. }
  17574. catch (IException *E)
  17575. {
  17576. throw makeWrappedException(E);
  17577. }
  17578. }
  17579. virtual const void *nextRow()
  17580. {
  17581. ActivityTimer t(activityStats, timeActivities);
  17582. if(!started)
  17583. {
  17584. started = true;
  17585. left = inputStream->nextRow();
  17586. matchedLeft = false;
  17587. countForLeft = keepLimit;
  17588. joinCounter = 0;
  17589. if(left == NULL)
  17590. {
  17591. eos = true;
  17592. return NULL;
  17593. }
  17594. loadRight();
  17595. }
  17596. const void * ret;
  17597. const void * right;
  17598. if(eos)
  17599. return NULL;
  17600. while(true)
  17601. {
  17602. ret = NULL;
  17603. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17604. {
  17605. if(leftOuterJoin && left && !matchedLeft)
  17606. {
  17607. switch(activityKind)
  17608. {
  17609. case TAKalljoin:
  17610. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17611. break;
  17612. case TAKalldenormalize:
  17613. ret = left;
  17614. left = NULL;
  17615. break;
  17616. case TAKalldenormalizegroup:
  17617. filteredRight.kill();
  17618. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17619. break;
  17620. default:
  17621. throwUnexpected();
  17622. }
  17623. }
  17624. rightIndex = 0;
  17625. joinCounter = 0;
  17626. ReleaseRoxieRow(left);
  17627. left = NULL;
  17628. if(ret)
  17629. {
  17630. matchedGroup = true;
  17631. processed++;
  17632. return ret;
  17633. }
  17634. }
  17635. if(!left)
  17636. {
  17637. left = inputStream->nextRow();
  17638. matchedLeft = false;
  17639. countForLeft = keepLimit;
  17640. joinCounter = 0;
  17641. }
  17642. if(!left)
  17643. {
  17644. if(eog)
  17645. {
  17646. eos = true;
  17647. matchedGroup = false;
  17648. return NULL;
  17649. }
  17650. eog = true;
  17651. if (matchedGroup && leftIsGrouped)
  17652. {
  17653. matchedGroup = false;
  17654. return NULL;
  17655. }
  17656. matchedGroup = false;
  17657. continue;
  17658. }
  17659. eog = false;
  17660. switch(activityKind)
  17661. {
  17662. case TAKalljoin:
  17663. while(rightIndex < rightOrdinality)
  17664. {
  17665. right = rightset.item(rightIndex);
  17666. if(helper.match(left, right))
  17667. {
  17668. matchedLeft = true;
  17669. matchedRight.replace(true, rightIndex);
  17670. if(!exclude)
  17671. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17672. }
  17673. rightIndex++;
  17674. if(ret)
  17675. {
  17676. countForLeft--;
  17677. matchedGroup = true;
  17678. processed++;
  17679. return ret;
  17680. }
  17681. }
  17682. break;
  17683. case TAKalldenormalize:
  17684. {
  17685. OwnedConstRoxieRow newLeft;
  17686. newLeft.set(left);
  17687. unsigned rowSize = 0;
  17688. unsigned leftCount = 0;
  17689. while((rightIndex < rightOrdinality) && countForLeft)
  17690. {
  17691. right = rightset.item(rightIndex);
  17692. if(helper.match(left, right))
  17693. {
  17694. matchedLeft = true;
  17695. matchedRight.replace(true, rightIndex);
  17696. if(!exclude)
  17697. {
  17698. try
  17699. {
  17700. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17701. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17702. if(thisSize)
  17703. {
  17704. rowSize = thisSize;
  17705. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17706. --countForLeft;
  17707. }
  17708. }
  17709. catch (IException *e)
  17710. {
  17711. throw makeWrappedException(e);
  17712. }
  17713. }
  17714. }
  17715. rightIndex++;
  17716. }
  17717. if(rowSize)
  17718. {
  17719. processed++;
  17720. return newLeft.getClear();
  17721. }
  17722. }
  17723. break;
  17724. case TAKalldenormalizegroup:
  17725. filteredRight.kill();
  17726. while((rightIndex < rightOrdinality) && countForLeft)
  17727. {
  17728. right = rightset.item(rightIndex);
  17729. if(helper.match(left, right))
  17730. {
  17731. matchedLeft = true;
  17732. matchedRight.replace(true, rightIndex);
  17733. filteredRight.append(right);
  17734. --countForLeft;
  17735. }
  17736. ++rightIndex;
  17737. }
  17738. if(!exclude && filteredRight.ordinality())
  17739. {
  17740. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17741. filteredRight.kill();
  17742. if(ret)
  17743. {
  17744. processed++;
  17745. return ret;
  17746. }
  17747. }
  17748. break;
  17749. default:
  17750. throwUnexpected();
  17751. }
  17752. }
  17753. }
  17754. };
  17755. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17756. {
  17757. public:
  17758. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17759. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17760. {
  17761. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17762. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17763. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17764. }
  17765. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  17766. {
  17767. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17768. }
  17769. virtual const StatisticsMapping &queryStatsMapping() const
  17770. {
  17771. return joinStatistics;
  17772. }
  17773. };
  17774. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17775. {
  17776. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17777. }
  17778. //=====================================================================================================
  17779. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17780. {
  17781. unsigned limit;
  17782. bool hasBest;
  17783. bool eoi;
  17784. const void **sorted;
  17785. unsigned sortedCount;
  17786. unsigned curIndex;
  17787. IHThorTopNArg &helper;
  17788. ICompare &compare;
  17789. public:
  17790. CRoxieServerTopNActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17791. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17792. {
  17793. sorted = NULL;
  17794. sortedCount = 0;
  17795. curIndex = 0;
  17796. limit = 0;
  17797. eoi = false;
  17798. hasBest = false;
  17799. }
  17800. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17801. {
  17802. assertex(sorted == NULL);
  17803. sortedCount = 0;
  17804. curIndex = 0;
  17805. eoi = false;
  17806. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17807. limit = (unsigned) helper.getLimit();
  17808. hasBest = helper.hasBest();
  17809. lateStart(parentExtractSize, parentExtract, limit > 0);
  17810. // MORE - should we use an expanding array instead?
  17811. if (limit > 0)
  17812. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17813. }
  17814. virtual void reset()
  17815. {
  17816. if (sorted)
  17817. {
  17818. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17819. curIndex = 0;
  17820. sortedCount = 0;
  17821. ReleaseRoxieRow(sorted);
  17822. sorted = NULL;
  17823. }
  17824. CRoxieServerLateStartActivity::reset();
  17825. }
  17826. bool abortEarly()
  17827. {
  17828. if (hasBest && (sortedCount == limit))
  17829. {
  17830. int compare = helper.compareBest(sorted[sortedCount-1]);
  17831. if (compare == 0)
  17832. {
  17833. if (meta.isGrouped())
  17834. {
  17835. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17836. const void * next;
  17837. while ((next = inputStream->nextRow()) != NULL)
  17838. ReleaseRoxieRow(next);
  17839. }
  17840. else
  17841. eoi = true;
  17842. return true;
  17843. }
  17844. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17845. if (compare < 0)
  17846. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17847. }
  17848. return false;
  17849. }
  17850. void getSorted()
  17851. {
  17852. curIndex = 0;
  17853. sortedCount = 0;
  17854. if(eoi)
  17855. return;
  17856. const void * next;
  17857. while ((next = inputStream->nextRow()) != NULL)
  17858. {
  17859. if (sortedCount < limit)
  17860. {
  17861. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17862. sortedCount++;
  17863. if(abortEarly())
  17864. return;
  17865. }
  17866. else
  17867. {
  17868. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17869. {
  17870. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17871. ReleaseRoxieRow(sorted[sortedCount]);
  17872. if(abortEarly())
  17873. return;
  17874. }
  17875. else
  17876. {
  17877. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17878. }
  17879. }
  17880. }
  17881. }
  17882. virtual const void * nextRow()
  17883. {
  17884. ActivityTimer t(activityStats, timeActivities);
  17885. if (eof)
  17886. return NULL;
  17887. if (curIndex >= sortedCount)
  17888. {
  17889. bool eog = sortedCount != 0;
  17890. getSorted();
  17891. if(sortedCount == 0)
  17892. {
  17893. eof = true;
  17894. return NULL;
  17895. }
  17896. if (eog)
  17897. return NULL;
  17898. }
  17899. processed++;
  17900. return sorted[curIndex++];
  17901. }
  17902. };
  17903. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17904. {
  17905. public:
  17906. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17907. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17908. {
  17909. }
  17910. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  17911. {
  17912. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17913. }
  17914. };
  17915. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17916. {
  17917. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17918. }
  17919. //=================================================================================
  17920. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17921. {
  17922. protected:
  17923. unsigned __int64 rowLimit;
  17924. IHThorLimitArg &helper;
  17925. public:
  17926. CRoxieServerLimitActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17927. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17928. {
  17929. rowLimit = 0;
  17930. }
  17931. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17932. {
  17933. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17934. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17935. }
  17936. virtual const void *nextRow()
  17937. {
  17938. ActivityTimer t(activityStats, timeActivities);
  17939. const void * ret = inputStream->nextRow();
  17940. if (ret)
  17941. {
  17942. processed++;
  17943. if (processed > rowLimit)
  17944. {
  17945. ReleaseRoxieRow(ret);
  17946. if (traceLevel > 4)
  17947. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17948. helper.onLimitExceeded();
  17949. }
  17950. }
  17951. return ret;
  17952. }
  17953. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17954. {
  17955. ActivityTimer t(activityStats, timeActivities);
  17956. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17957. if (ret)
  17958. {
  17959. if (wasCompleteMatch)
  17960. processed++;
  17961. if (processed > rowLimit)
  17962. {
  17963. ReleaseRoxieRow(ret);
  17964. if (traceLevel > 4)
  17965. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17966. helper.onLimitExceeded();
  17967. }
  17968. }
  17969. return ret;
  17970. }
  17971. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17972. {
  17973. return input->gatherConjunctions(collector);
  17974. }
  17975. virtual void resetEOF()
  17976. {
  17977. //Do not reset the rowLimit
  17978. inputStream->resetEOF();
  17979. }
  17980. IInputSteppingMeta * querySteppingMeta()
  17981. {
  17982. return input->querySteppingMeta();
  17983. }
  17984. };
  17985. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17986. {
  17987. public:
  17988. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17989. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17990. {
  17991. }
  17992. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  17993. {
  17994. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17995. }
  17996. };
  17997. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17998. {
  17999. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18000. }
  18001. //=====================================================================================================
  18002. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  18003. {
  18004. ConstPointerArray buff;
  18005. bool started = false;
  18006. unsigned index = 0;
  18007. bool isFail = false;
  18008. public:
  18009. CRoxieServerSkipLimitActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  18010. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  18011. {
  18012. started = false;
  18013. index = 0;
  18014. isFail = _onFail;
  18015. }
  18016. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18017. {
  18018. started = false;
  18019. index = 0;
  18020. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  18021. }
  18022. virtual void reset()
  18023. {
  18024. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  18025. buff.kill();
  18026. index = 0;
  18027. started = false;
  18028. CRoxieServerLimitActivity::reset();
  18029. }
  18030. virtual const void *nextRow()
  18031. {
  18032. ActivityTimer t(activityStats, timeActivities);
  18033. if (!started)
  18034. pullInput();
  18035. if (buff.isItem(index))
  18036. {
  18037. const void * next = buff.item(index++);
  18038. if(next)
  18039. processed++;
  18040. return next;
  18041. }
  18042. return NULL;
  18043. }
  18044. protected:
  18045. void pullInput()
  18046. {
  18047. unsigned count = 0;
  18048. for (;;)
  18049. {
  18050. const void * next = inputStream->nextRow();
  18051. if (next == NULL)
  18052. {
  18053. next = inputStream->nextRow();
  18054. if(next == NULL)
  18055. break;
  18056. buff.append(NULL);
  18057. }
  18058. count++;
  18059. if (count > rowLimit)
  18060. {
  18061. ReleaseRoxieRow(next);
  18062. ReleaseRoxieRows(buff);
  18063. if (ctx->queryDebugContext())
  18064. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  18065. if (isFail)
  18066. {
  18067. ensureRowAllocator();
  18068. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18069. size32_t outSize = helper.transformOnLimitExceeded(rowBuilder);
  18070. if (outSize)
  18071. buff.append(rowBuilder.finalizeRowClear(outSize));
  18072. }
  18073. break;
  18074. }
  18075. buff.append(next);
  18076. }
  18077. started = true;
  18078. }
  18079. };
  18080. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  18081. {
  18082. public:
  18083. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18084. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18085. {
  18086. }
  18087. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18088. {
  18089. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  18090. }
  18091. };
  18092. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18093. {
  18094. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18095. }
  18096. //=================================================================================
  18097. class CRoxieServerCatchActivity : public CRoxieServerActivity
  18098. {
  18099. IHThorCatchArg &helper;
  18100. public:
  18101. CRoxieServerCatchActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18102. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  18103. {
  18104. }
  18105. // MORE - you could argue we should catch exceptions in START too, though not clear what to do with them
  18106. // See CRoxieServerSkipCatchActivity::start
  18107. // This is less significant now that we properly distinguish start exceptions from read exceptions in ThroughSpill activity
  18108. virtual const void *nextRow()
  18109. {
  18110. ActivityTimer t(activityStats, timeActivities);
  18111. try
  18112. {
  18113. const void *ret = inputStream->nextRow();
  18114. if (ret)
  18115. processed++;
  18116. return ret;
  18117. }
  18118. catch (IException *E)
  18119. {
  18120. E->Release();
  18121. helper.onExceptionCaught();
  18122. }
  18123. catch (...)
  18124. {
  18125. helper.onExceptionCaught();
  18126. }
  18127. throwUnexpected(); // onExceptionCaught should have thrown something
  18128. }
  18129. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18130. {
  18131. try
  18132. {
  18133. ActivityTimer t(activityStats, timeActivities);
  18134. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18135. if (ret && wasCompleteMatch)
  18136. processed++;
  18137. return ret;
  18138. }
  18139. catch (IException *E)
  18140. {
  18141. E->Release();
  18142. helper.onExceptionCaught();
  18143. }
  18144. catch (...)
  18145. {
  18146. helper.onExceptionCaught();
  18147. }
  18148. throwUnexpected(); // onExceptionCaught should have thrown something
  18149. }
  18150. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18151. {
  18152. return input->gatherConjunctions(collector);
  18153. }
  18154. virtual void resetEOF()
  18155. {
  18156. inputStream->resetEOF(); // MORE - why not in base class?
  18157. }
  18158. IInputSteppingMeta * querySteppingMeta()
  18159. {
  18160. return input->querySteppingMeta();
  18161. }
  18162. };
  18163. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  18164. {
  18165. ConstPointerArray buff;
  18166. bool started;
  18167. unsigned index;
  18168. IHThorCatchArg &helper;
  18169. bool createRow;
  18170. public:
  18171. CRoxieServerSkipCatchActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  18172. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  18173. {
  18174. started = false;
  18175. index = 0;
  18176. }
  18177. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18178. {
  18179. started = false;
  18180. index = 0;
  18181. try
  18182. {
  18183. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18184. }
  18185. catch (IException *E)
  18186. {
  18187. ensureCreated();
  18188. onException(E);
  18189. started = true;
  18190. }
  18191. catch (...)
  18192. {
  18193. ensureCreated();
  18194. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18195. started = true;
  18196. }
  18197. }
  18198. virtual void reset()
  18199. {
  18200. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  18201. buff.kill();
  18202. index = 0;
  18203. started = false;
  18204. CRoxieServerActivity::reset();
  18205. }
  18206. virtual const void *nextRow()
  18207. {
  18208. ActivityTimer t(activityStats, timeActivities);
  18209. if (!started)
  18210. pullInput();
  18211. if (buff.isItem(index))
  18212. {
  18213. const void * next = buff.item(index++);
  18214. if(next)
  18215. processed++;
  18216. return next;
  18217. }
  18218. return NULL;
  18219. }
  18220. protected:
  18221. void onException(IException *E)
  18222. {
  18223. inputStream->stop();
  18224. ReleaseRoxieRows(buff);
  18225. if (createRow)
  18226. {
  18227. ensureRowAllocator();
  18228. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18229. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  18230. if (outSize)
  18231. buff.append(rowBuilder.finalizeRowClear(outSize));
  18232. }
  18233. E->Release();
  18234. }
  18235. void pullInput()
  18236. {
  18237. try
  18238. {
  18239. bool EOGseen = false;
  18240. for (;;)
  18241. {
  18242. const void * next = inputStream->nextRow();
  18243. buff.append(next);
  18244. if (next == NULL)
  18245. {
  18246. if (EOGseen)
  18247. break;
  18248. EOGseen = true;
  18249. }
  18250. else
  18251. EOGseen = false;
  18252. }
  18253. }
  18254. catch (IException *E)
  18255. {
  18256. onException(E);
  18257. }
  18258. catch (...)
  18259. {
  18260. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18261. }
  18262. started = true;
  18263. }
  18264. };
  18265. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  18266. {
  18267. public:
  18268. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18269. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18270. {
  18271. }
  18272. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18273. {
  18274. switch (kind)
  18275. {
  18276. case TAKcatch:
  18277. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  18278. case TAKskipcatch:
  18279. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  18280. case TAKcreaterowcatch:
  18281. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  18282. default:
  18283. throwUnexpected();
  18284. }
  18285. }
  18286. };
  18287. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18288. {
  18289. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18290. }
  18291. //=================================================================================
  18292. class CRoxieServerPullActivity : public CRoxieServerActivity
  18293. {
  18294. ConstPointerArray buff;
  18295. bool started;
  18296. unsigned index;
  18297. public:
  18298. CRoxieServerPullActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18299. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18300. {
  18301. started = false;
  18302. index = 0;
  18303. }
  18304. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18305. {
  18306. started = false;
  18307. index = 0;
  18308. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18309. }
  18310. virtual void reset()
  18311. {
  18312. while (buff.isItem(index))
  18313. ReleaseRoxieRow(buff.item(index++));
  18314. buff.kill();
  18315. started = false;
  18316. index = 0;
  18317. CRoxieServerActivity::reset();
  18318. }
  18319. virtual const void *nextRow()
  18320. {
  18321. ActivityTimer t(activityStats, timeActivities);
  18322. if (!started)
  18323. pullInput();
  18324. if (buff.isItem(index))
  18325. {
  18326. const void * next = buff.item(index++);
  18327. if (next)
  18328. processed++;
  18329. return next;
  18330. }
  18331. return NULL;
  18332. }
  18333. protected:
  18334. void pullInput()
  18335. {
  18336. bool EOGseen = false;
  18337. for (;;)
  18338. {
  18339. const void * next = inputStream->nextRow();
  18340. buff.append(next);
  18341. if (next == NULL)
  18342. {
  18343. if (EOGseen)
  18344. break;
  18345. EOGseen = true;
  18346. }
  18347. else
  18348. EOGseen = false;
  18349. }
  18350. started = true;
  18351. }
  18352. };
  18353. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  18354. {
  18355. public:
  18356. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18357. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18358. {
  18359. }
  18360. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18361. {
  18362. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  18363. }
  18364. };
  18365. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18366. {
  18367. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18368. }
  18369. //=================================================================================
  18370. class CRoxieServerTraceActivity : public CRoxieServerActivity
  18371. {
  18372. public:
  18373. CRoxieServerTraceActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18374. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  18375. keepLimit(0), skip(0), sample(0)
  18376. {
  18377. assertex(meta.hasXML());
  18378. traceEnabled = defaultTraceEnabled && !isBlind();
  18379. }
  18380. virtual void onCreate(IHThorArg *_colocalParent)
  18381. {
  18382. CRoxieServerActivity::onCreate(_colocalParent);
  18383. if (ctx)
  18384. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  18385. }
  18386. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18387. {
  18388. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18389. if (traceEnabled && helper.canMatchAny())
  18390. {
  18391. keepLimit = helper.getKeepLimit();
  18392. if (keepLimit==(unsigned) -1)
  18393. keepLimit = ctx->queryOptions().traceLimit;
  18394. skip = helper.getSkip();
  18395. sample = helper.getSample();
  18396. if (sample)
  18397. sample--;
  18398. name.setown(helper.getName());
  18399. if (!name)
  18400. name.set("Row");
  18401. }
  18402. else
  18403. keepLimit = 0;
  18404. }
  18405. virtual void stop()
  18406. {
  18407. name.clear();
  18408. CRoxieServerActivity::stop();
  18409. }
  18410. virtual bool isPassThrough()
  18411. {
  18412. return true;
  18413. }
  18414. virtual const void *nextRow()
  18415. {
  18416. ActivityTimer t(activityStats, timeActivities);
  18417. const void *row = inputStream->nextRow();
  18418. if (row)
  18419. {
  18420. onTrace(row);
  18421. processed++;
  18422. }
  18423. return row;
  18424. }
  18425. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18426. {
  18427. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  18428. ActivityTimer t(activityStats, timeActivities);
  18429. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18430. if (row)
  18431. {
  18432. onTrace(row);
  18433. processed++;
  18434. }
  18435. return row;
  18436. }
  18437. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18438. {
  18439. return input->gatherConjunctions(collector);
  18440. }
  18441. virtual void resetEOF()
  18442. {
  18443. inputStream->resetEOF();
  18444. }
  18445. IInputSteppingMeta * querySteppingMeta()
  18446. {
  18447. return input->querySteppingMeta();
  18448. }
  18449. protected:
  18450. void onTrace(const void *row)
  18451. {
  18452. if (keepLimit && helper.isValid(row))
  18453. {
  18454. if (skip)
  18455. skip--;
  18456. else if (sample)
  18457. sample--;
  18458. else
  18459. {
  18460. CommonXmlWriter xmlwrite(XWFnoindent);
  18461. meta.toXML((const byte *) row, xmlwrite);
  18462. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18463. keepLimit--;
  18464. sample = helper.getSample();
  18465. if (sample)
  18466. sample--;
  18467. }
  18468. }
  18469. }
  18470. OwnedRoxieString name;
  18471. IHThorTraceArg &helper;
  18472. unsigned keepLimit;
  18473. unsigned skip;
  18474. unsigned sample;
  18475. bool traceEnabled;
  18476. };
  18477. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18478. {
  18479. public:
  18480. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18481. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18482. {
  18483. }
  18484. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18485. {
  18486. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18487. }
  18488. };
  18489. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18490. {
  18491. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18492. }
  18493. //=================================================================================
  18494. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18495. {
  18496. IHThorCaseArg &helper;
  18497. unsigned cond;
  18498. bool unusedStopped;
  18499. IEngineRowStream *active;
  18500. public:
  18501. CRoxieServerCaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18502. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18503. {
  18504. unusedStopped = false;
  18505. cond = 0;
  18506. active = NULL;
  18507. }
  18508. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18509. {
  18510. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18511. cond = helper.getBranch();
  18512. //CHOOSE defaults to the last argument if out of range.
  18513. if (cond >= numInputs)
  18514. cond = numInputs - 1;
  18515. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18516. startJunction(junctionArray[cond]);
  18517. assertex(numInputs==numStreams);
  18518. for (unsigned idx = 0; idx < numStreams; idx++)
  18519. {
  18520. if (idx!=cond)
  18521. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18522. }
  18523. active = streamArray[cond];
  18524. unusedStopped = true;
  18525. }
  18526. virtual void stop()
  18527. {
  18528. for (unsigned idx = 0; idx < numStreams; idx++)
  18529. {
  18530. if (idx==cond || !unusedStopped)
  18531. streamArray[idx]->stop();
  18532. }
  18533. CRoxieServerMultiInputBaseActivity::stop();
  18534. }
  18535. virtual void reset()
  18536. {
  18537. unusedStopped = false;
  18538. active = NULL;
  18539. CRoxieServerMultiInputBaseActivity::reset();
  18540. }
  18541. virtual const void *nextRow()
  18542. {
  18543. ActivityTimer t(activityStats, timeActivities);
  18544. if (active)
  18545. {
  18546. const void *ret = active->nextRow();
  18547. if (ret)
  18548. processed++;
  18549. return ret;
  18550. }
  18551. return NULL;
  18552. }
  18553. };
  18554. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18555. {
  18556. bool graphInvariant;
  18557. public:
  18558. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18559. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18560. {
  18561. graphInvariant = _graphInvariant;
  18562. }
  18563. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18564. {
  18565. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18566. }
  18567. virtual bool isGraphInvariant() const
  18568. {
  18569. return graphInvariant;
  18570. }
  18571. };
  18572. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18573. {
  18574. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18575. }
  18576. //=================================================================================
  18577. class CRoxieServerIfActivity : public CRoxieServerActivity
  18578. {
  18579. IHThorIfArg &helper;
  18580. IFinalRoxieInput *inputTrue;
  18581. IFinalRoxieInput *inputFalse;
  18582. IEngineRowStream *streamTrue;
  18583. IEngineRowStream *streamFalse;
  18584. unsigned sourceIdxFalse = 0;
  18585. unsigned sourceIdxTrue = 0;
  18586. Owned<IStrandJunction> junctionTrue;
  18587. Owned<IStrandJunction> junctionFalse;
  18588. bool cond;
  18589. bool unusedStopped;
  18590. public:
  18591. CRoxieServerIfActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18592. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18593. {
  18594. inputFalse = NULL;
  18595. inputTrue = NULL;
  18596. streamTrue = NULL;
  18597. streamFalse = NULL;
  18598. unusedStopped = false;
  18599. cond = false;
  18600. }
  18601. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18602. {
  18603. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18604. cond = helper.getCondition();
  18605. if (cond)
  18606. {
  18607. if (inputTrue)
  18608. {
  18609. inputTrue->start(parentExtractSize, parentExtract, paused);
  18610. startJunction(junctionTrue);
  18611. }
  18612. if (streamFalse)
  18613. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18614. }
  18615. else
  18616. {
  18617. if (inputFalse)
  18618. {
  18619. inputFalse->start(parentExtractSize, parentExtract, paused);
  18620. startJunction(junctionFalse);
  18621. }
  18622. if (streamTrue)
  18623. streamTrue->stop();
  18624. }
  18625. unusedStopped = true;
  18626. }
  18627. virtual void stop()
  18628. {
  18629. if (streamTrue && (!unusedStopped || cond))
  18630. streamTrue->stop();
  18631. if (streamFalse && (!unusedStopped || !cond))
  18632. streamFalse->stop();
  18633. CRoxieServerActivity::stop();
  18634. }
  18635. virtual unsigned __int64 queryLocalCycles() const
  18636. {
  18637. __int64 localCycles = activityStats.totalCycles;
  18638. if (inputTrue) // if conditional input cannot assume inputTrue
  18639. localCycles -= inputTrue->queryTotalCycles();
  18640. if (inputFalse)
  18641. localCycles -= inputFalse->queryTotalCycles();
  18642. if (localCycles < 0)
  18643. localCycles = 0;
  18644. return localCycles;
  18645. }
  18646. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18647. {
  18648. switch (idx)
  18649. {
  18650. case 0:
  18651. return inputTrue;
  18652. case 1:
  18653. return inputFalse;
  18654. default:
  18655. return NULL;
  18656. }
  18657. }
  18658. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18659. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18660. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18661. {
  18662. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18663. if (in)
  18664. return in->queryIndexReadActivity();
  18665. return NULL;
  18666. }
  18667. virtual void reset()
  18668. {
  18669. CRoxieServerActivity::reset();
  18670. if (inputTrue)
  18671. inputTrue->reset();
  18672. if (inputFalse)
  18673. inputFalse->reset();
  18674. resetJunction(junctionTrue);
  18675. resetJunction(junctionFalse);
  18676. unusedStopped = false;
  18677. }
  18678. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18679. {
  18680. if (idx==1)
  18681. {
  18682. inputFalse = _in;
  18683. sourceIdxFalse = _sourceIdx;
  18684. }
  18685. else
  18686. {
  18687. assertex(!idx);
  18688. inputTrue = _in;
  18689. sourceIdxTrue = _sourceIdx;
  18690. }
  18691. }
  18692. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18693. {
  18694. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18695. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18696. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18697. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18698. }
  18699. virtual const void *nextRow()
  18700. {
  18701. ActivityTimer t(activityStats, timeActivities);
  18702. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18703. if (in)
  18704. {
  18705. const void * ret;
  18706. if ((ret = in->nextRow()) != NULL)
  18707. processed++;
  18708. return ret;
  18709. }
  18710. return NULL;
  18711. }
  18712. };
  18713. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18714. {
  18715. unsigned input2;
  18716. unsigned input2idx;
  18717. bool graphInvariant;
  18718. public:
  18719. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18720. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18721. {
  18722. graphInvariant = _graphInvariant;
  18723. input2 = (unsigned)-1;
  18724. input2idx = (unsigned)-1;
  18725. }
  18726. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18727. {
  18728. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18729. }
  18730. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18731. {
  18732. if (idx==1)
  18733. {
  18734. input2 = source;
  18735. input2idx = sourceidx;
  18736. }
  18737. else
  18738. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18739. }
  18740. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18741. {
  18742. switch (idx)
  18743. {
  18744. case 1:
  18745. sourceidx = input2idx;
  18746. return input2;
  18747. case 0:
  18748. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18749. default:
  18750. return (unsigned) -1;
  18751. }
  18752. }
  18753. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18754. virtual bool isGraphInvariant() const
  18755. {
  18756. return graphInvariant;
  18757. }
  18758. };
  18759. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18760. {
  18761. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18762. }
  18763. //=================================================================================
  18764. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18765. {
  18766. CriticalSection ecrit;
  18767. Owned<IException> exception;
  18768. bool executed;
  18769. public:
  18770. CRoxieServerActionBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18771. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18772. {
  18773. executed = false;
  18774. }
  18775. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18776. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18777. {
  18778. CriticalBlock b(ecrit);
  18779. if (exception)
  18780. throw(exception.getLink());
  18781. if (!executed)
  18782. {
  18783. try
  18784. {
  18785. executed = true;
  18786. start(parentExtractSize, parentExtract, false);
  18787. doExecuteAction(parentExtractSize, parentExtract);
  18788. stop();
  18789. }
  18790. catch (IException * E)
  18791. {
  18792. ctx->notifyAbort(E);
  18793. abort();
  18794. exception.set(E);
  18795. throw;
  18796. }
  18797. }
  18798. }
  18799. virtual void reset()
  18800. {
  18801. executed = false;
  18802. exception.clear();
  18803. CRoxieServerActivity::reset();
  18804. }
  18805. virtual const void *nextRow()
  18806. {
  18807. throwUnexpected(); // I am nobody's input
  18808. }
  18809. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18810. {
  18811. return NULL;
  18812. }
  18813. };
  18814. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18815. {
  18816. IHThorIfArg &helper;
  18817. public:
  18818. CRoxieServerIfActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18819. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18820. {
  18821. }
  18822. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) override
  18823. {
  18824. bool cond;
  18825. {
  18826. ActivityTimer t(activityStats, timeActivities);
  18827. cond = helper.getCondition();
  18828. }
  18829. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18830. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18831. }
  18832. virtual void stop() override
  18833. {
  18834. if (state != STATEstopped)
  18835. {
  18836. ForEachItemIn(idx, dependencies)
  18837. {
  18838. if (dependencyControlIds.item(idx) != 0)
  18839. dependencies.item(idx).stop();
  18840. }
  18841. }
  18842. CRoxieServerActionBaseActivity::stop();
  18843. }
  18844. };
  18845. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18846. {
  18847. bool isRoot;
  18848. public:
  18849. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18850. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18851. {
  18852. }
  18853. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18854. {
  18855. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18856. }
  18857. virtual bool isSink() const
  18858. {
  18859. return isRoot;
  18860. }
  18861. };
  18862. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18863. {
  18864. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18865. }
  18866. //=================================================================================
  18867. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18868. {
  18869. public:
  18870. CRoxieServerParallelActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18871. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18872. {
  18873. }
  18874. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18875. {
  18876. #ifdef PARALLEL_EXECUTE
  18877. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18878. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18879. #else
  18880. ForEachItemIn(idx, dependencies)
  18881. {
  18882. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18883. }
  18884. #endif
  18885. }
  18886. };
  18887. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18888. {
  18889. bool isRoot;
  18890. public:
  18891. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18892. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18893. {
  18894. assertex(!isRoot); // non-internal should be expanded out..
  18895. }
  18896. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18897. {
  18898. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18899. }
  18900. virtual bool isSink() const
  18901. {
  18902. return isRoot;
  18903. }
  18904. };
  18905. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18906. {
  18907. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18908. }
  18909. //=================================================================================
  18910. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18911. {
  18912. IHThorSequentialArg &helper;
  18913. public:
  18914. CRoxieServerSequentialActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18915. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18916. {
  18917. }
  18918. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18919. {
  18920. unsigned numBranches = helper.numBranches();
  18921. try
  18922. {
  18923. for (unsigned branch=1; branch <= numBranches; branch++)
  18924. executeDependencies(parentExtractSize, parentExtract, branch);
  18925. }
  18926. catch (...)
  18927. {
  18928. for (unsigned branch=1; branch <= numBranches; branch++)
  18929. stopDependencies(parentExtractSize, parentExtract, branch);
  18930. throw;
  18931. }
  18932. }
  18933. };
  18934. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18935. {
  18936. bool isRoot;
  18937. public:
  18938. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18939. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18940. {
  18941. }
  18942. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  18943. {
  18944. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18945. }
  18946. virtual bool isSink() const
  18947. {
  18948. return isRoot;
  18949. }
  18950. };
  18951. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18952. {
  18953. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18954. }
  18955. //=================================================================================
  18956. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18957. {
  18958. public:
  18959. CRoxieServerWhenActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18960. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18961. {
  18962. savedExtractSize = 0;
  18963. savedExtract = NULL;
  18964. eofseen = false;
  18965. eogseen = false;
  18966. }
  18967. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18968. {
  18969. savedExtractSize = parentExtractSize;
  18970. savedExtract = parentExtract;
  18971. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18972. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18973. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18974. eofseen = false;
  18975. eogseen = false;
  18976. }
  18977. virtual void stop()
  18978. {
  18979. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18980. {
  18981. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18982. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18983. }
  18984. else if (state != STATEstopped)
  18985. {
  18986. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18987. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18988. }
  18989. CRoxieServerActivity::stop();
  18990. }
  18991. virtual const void *nextRow()
  18992. {
  18993. try
  18994. {
  18995. ActivityTimer t(activityStats, timeActivities); // bit of a waste of time....
  18996. const void *ret = inputStream->nextRow();
  18997. if (!ret)
  18998. {
  18999. if (eogseen)
  19000. eofseen = true;
  19001. else
  19002. eogseen = true;
  19003. }
  19004. else
  19005. eogseen = false;
  19006. return ret;
  19007. }
  19008. catch (...)
  19009. {
  19010. aborted = true;
  19011. throw;
  19012. }
  19013. }
  19014. protected:
  19015. const byte *savedExtract;
  19016. unsigned savedExtractSize;
  19017. bool eofseen;
  19018. bool eogseen;
  19019. };
  19020. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  19021. {
  19022. public:
  19023. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19024. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19025. {
  19026. }
  19027. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19028. {
  19029. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  19030. }
  19031. };
  19032. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19033. {
  19034. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19035. }
  19036. //=================================================================================
  19037. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  19038. {
  19039. public:
  19040. CRoxieServerWhenActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19041. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  19042. {
  19043. savedExtractSize = 0;
  19044. savedExtract = NULL;
  19045. }
  19046. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19047. {
  19048. savedExtractSize = parentExtractSize;
  19049. savedExtract = parentExtract;
  19050. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  19051. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  19052. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  19053. }
  19054. virtual void stop()
  19055. {
  19056. if (state != STATEstopped)
  19057. {
  19058. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  19059. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  19060. }
  19061. CRoxieServerActionBaseActivity::stop();
  19062. }
  19063. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  19064. {
  19065. executeDependencies(parentExtractSize, parentExtract, 1);
  19066. }
  19067. protected:
  19068. unsigned savedExtractSize;
  19069. const byte *savedExtract;
  19070. };
  19071. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  19072. {
  19073. public:
  19074. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  19075. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  19076. {
  19077. }
  19078. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19079. {
  19080. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  19081. }
  19082. virtual bool isSink() const
  19083. {
  19084. return isRoot;
  19085. }
  19086. private:
  19087. bool isRoot;
  19088. };
  19089. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  19090. {
  19091. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  19092. }
  19093. //=================================================================================
  19094. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  19095. {
  19096. INlpParseAlgorithm * algorithm;
  19097. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  19098. {
  19099. protected:
  19100. IHThorParseArg &helper;
  19101. INlpParser * parser;
  19102. INlpResultIterator * rowIter;
  19103. const void * in;
  19104. char * curSearchText;
  19105. size32_t curSearchTextLen;
  19106. bool processRecord(const void * inRec)
  19107. {
  19108. if (helper.searchTextNeedsFree())
  19109. rtlFree(curSearchText);
  19110. curSearchTextLen = 0;
  19111. curSearchText = NULL;
  19112. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  19113. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  19114. }
  19115. public:
  19116. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  19117. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  19118. {
  19119. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  19120. rowIter = parser->queryResultIter();
  19121. in = NULL;
  19122. curSearchText = NULL;
  19123. curSearchTextLen = 0;
  19124. }
  19125. ~ParseProcessor()
  19126. {
  19127. ::Release(parser);
  19128. }
  19129. virtual void start()
  19130. {
  19131. StrandProcessor::start();
  19132. numProcessedLastGroup = 0;
  19133. curSearchTextLen = 0;
  19134. curSearchText = NULL;
  19135. in = NULL;
  19136. parser->reset();
  19137. }
  19138. virtual void reset()
  19139. {
  19140. if (helper.searchTextNeedsFree())
  19141. rtlFree(curSearchText);
  19142. curSearchText = NULL;
  19143. ReleaseClearRoxieRow(in);
  19144. StrandProcessor::reset();
  19145. }
  19146. virtual const void * nextRow()
  19147. {
  19148. ActivityTimer t(activityStats, timeActivities);
  19149. for (;;)
  19150. {
  19151. if (rowIter->isValid())
  19152. {
  19153. OwnedConstRoxieRow out = rowIter->getRow();
  19154. rowIter->next();
  19155. processed++;
  19156. return out.getClear();
  19157. }
  19158. ReleaseClearRoxieRow(in);
  19159. in = inputStream->nextRow();
  19160. if (!in)
  19161. {
  19162. if (processed == numProcessedLastGroup)
  19163. in = inputStream->nextRow();
  19164. if (!in)
  19165. {
  19166. processed = numProcessedLastGroup;
  19167. return NULL;
  19168. }
  19169. in = inputStream->nextRow();
  19170. if (!in)
  19171. return NULL;
  19172. }
  19173. processRecord(in);
  19174. rowIter->first();
  19175. }
  19176. }
  19177. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  19178. {
  19179. try
  19180. {
  19181. return helper.transform(self, curRecord, results, walker);
  19182. }
  19183. catch (IException *E)
  19184. {
  19185. throw parent.makeWrappedException(E);
  19186. }
  19187. }
  19188. };
  19189. public:
  19190. CRoxieServerStrandedParseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  19191. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  19192. {
  19193. }
  19194. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19195. {
  19196. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  19197. onStartStrands();
  19198. }
  19199. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  19200. {
  19201. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  19202. }
  19203. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  19204. };
  19205. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  19206. {
  19207. Owned<INlpParseAlgorithm> algorithm;
  19208. Owned<IHThorParseArg> helper;
  19209. StrandOptions strandOptions;
  19210. public:
  19211. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19212. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  19213. {
  19214. helper.setown((IHThorParseArg *) helperFactory());
  19215. algorithm.setown(createThorParser(rc, *helper));
  19216. optStableInput = false;
  19217. }
  19218. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19219. {
  19220. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  19221. }
  19222. };
  19223. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19224. {
  19225. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  19226. }
  19227. //=====================================================================================================
  19228. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  19229. {
  19230. IHThorWorkUnitWriteArg &helper;
  19231. bool isReread;
  19232. bool grouped;
  19233. IRoxieServerContext *serverContext;
  19234. int sequence;
  19235. public:
  19236. CRoxieServerWorkUnitWriteActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  19237. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  19238. {
  19239. grouped = (helper.getFlags() & POFgrouped) != 0;
  19240. serverContext = ctx->queryServerContext();
  19241. if (!serverContext)
  19242. {
  19243. throw MakeStringException(ROXIE_PIPE_ERROR, "Workunit output activity cannot be executed in agent context");
  19244. }
  19245. sequence = helper.getSequence();
  19246. if (sequence >= LibraryBaseSequence)
  19247. {
  19248. IConstWorkUnit *workunit = serverContext->queryQueryFactory()->queryWorkUnit();
  19249. assertex(workunit);
  19250. const char *storedName = helper.queryName();
  19251. assertex(storedName);
  19252. Owned<IConstWUResult> queryRes = workunit->getQueryResultByName(storedName);
  19253. if (!queryRes)
  19254. throw makeStringExceptionV(0, "Library cannot write to result %s that does not exist in calling query", storedName);
  19255. Owned<IConstWUResult> libraryRes = factory->queryQueryFactory().queryWorkUnit()->getResultBySequence(sequence);
  19256. if (libraryRes) // Should always be present, but rather than assert, just ignore if not
  19257. {
  19258. SCMStringBuffer queryFormat;
  19259. SCMStringBuffer libraryFormat;
  19260. queryRes->getResultEclSchema(queryFormat);
  19261. libraryRes->getResultEclSchema(libraryFormat);
  19262. if (!streq(queryFormat.str(), libraryFormat.str()))
  19263. {
  19264. DBGLOG("Query format: %s", queryFormat.str());
  19265. DBGLOG("Library format: %s", libraryFormat.str());
  19266. throw makeStringExceptionV(0, "Library cannot write to result %s: result type in query does not match", storedName);
  19267. }
  19268. }
  19269. sequence = queryRes->getResultSequence();
  19270. }
  19271. }
  19272. virtual bool needsAllocator() const { return true; }
  19273. virtual void onExecute()
  19274. {
  19275. MemoryBuffer result;
  19276. bool saveInContext = (int) sequence < 0 || isReread;
  19277. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  19278. meta.set(input->queryOutputMeta());
  19279. Owned<IOutputRowSerializer> rowSerializer;
  19280. Owned<IXmlWriter> xmlwriter;
  19281. bool appendRaw = false;
  19282. IHpccProtocolResultsWriter *results = NULL;
  19283. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  19284. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  19285. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  19286. if ((int) sequence >= 0)
  19287. {
  19288. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  19289. if (results)
  19290. {
  19291. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  19292. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  19293. }
  19294. }
  19295. size32_t outputLimitBytes = 0;
  19296. IConstWorkUnit *workunit = sequence == ResultSequenceInternal ? nullptr : serverContext->queryWorkUnit();
  19297. if (workunit)
  19298. {
  19299. size32_t outputLimit;
  19300. if (helper.getFlags() & POFmaxsize)
  19301. outputLimit = helper.getMaxSize();
  19302. else
  19303. {
  19304. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  19305. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  19306. }
  19307. if (outputLimit>defaultDaliResultOutputMax)
  19308. 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);
  19309. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  19310. outputLimitBytes = outputLimit * 0x100000;
  19311. }
  19312. if (workunit != NULL || (results && (protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW)))
  19313. {
  19314. ensureRowAllocator();
  19315. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  19316. }
  19317. __int64 initialProcessed = processed;
  19318. RtlLinkedDatasetBuilder builder(rowAllocator);
  19319. for (;;)
  19320. {
  19321. const void *row = inputStream->nextRow();
  19322. if (saveInContext)
  19323. {
  19324. if (row || grouped)
  19325. builder.append(row);
  19326. }
  19327. if (grouped && (processed != initialProcessed))
  19328. {
  19329. if (workunit)
  19330. result.append(row == NULL);
  19331. if (results)
  19332. {
  19333. if ((protocolFlags & HPCC_PROTOCOL_NATIVE_RAW) && nativeResults)
  19334. {
  19335. char val = (char)(row == NULL);
  19336. nativeResults->appendRaw(sequence, 1, &val);
  19337. }
  19338. else if (xmlwriter)
  19339. {
  19340. xmlwriter->outputBeginNested("Row", false);
  19341. xmlwriter->outputCString("1", "@__GroupBreak__");
  19342. xmlwriter->outputEndNested("Row");
  19343. }
  19344. }
  19345. }
  19346. if (!row)
  19347. {
  19348. row = inputStream->nextRow();
  19349. if (!row)
  19350. break;
  19351. if (saveInContext)
  19352. builder.append(row);
  19353. }
  19354. processed++;
  19355. if (workunit)
  19356. {
  19357. CThorDemoRowSerializer serializerTarget(result);
  19358. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19359. }
  19360. if ((int) sequence >= 0)
  19361. {
  19362. if (appendRaw && nativeResults)
  19363. {
  19364. // MORE - should be able to serialize straight to the response...
  19365. MemoryBuffer rowbuff;
  19366. CThorDemoRowSerializer serializerTarget(rowbuff);
  19367. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19368. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  19369. }
  19370. else if (xmlwriter)
  19371. {
  19372. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  19373. helper.serializeXml((byte *) row, *xmlwriter);
  19374. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  19375. results->finalizeXmlRow(sequence);
  19376. }
  19377. else if (nativeResults)
  19378. {
  19379. SimpleOutputWriter x;
  19380. helper.serializeXml((byte *) row, x);
  19381. x.newline();
  19382. nativeResults->appendSimpleRow(sequence, x.str());
  19383. }
  19384. }
  19385. ReleaseRoxieRow(row);
  19386. if (outputLimitBytes && result.length() > outputLimitBytes)
  19387. {
  19388. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  19389. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  19390. const char *name = helper.queryName();
  19391. if (name)
  19392. errMsg.append("name=").append(name);
  19393. else
  19394. errMsg.append("sequence=").append(helper.getSequence());
  19395. errMsg.append(")");
  19396. throw MakeStringExceptionDirect(0, errMsg.str());
  19397. }
  19398. }
  19399. if (xmlwriter)
  19400. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  19401. const char *storedName = helper.queryName();
  19402. if (!storedName)
  19403. storedName = "Dataset";
  19404. if (saveInContext)
  19405. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19406. if (workunit)
  19407. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  19408. }
  19409. };
  19410. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  19411. {
  19412. bool isReread;
  19413. bool isUnused = false;
  19414. public:
  19415. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19416. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19417. {
  19418. isReread = usageCount > 0;
  19419. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  19420. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19421. isUnused = isInternal && (usageCount == 0);
  19422. }
  19423. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19424. {
  19425. if (isUnused && !CRoxieServerInternalSinkFactory::isSink())
  19426. {
  19427. if (_ctx->queryTraceLevel() > 2)
  19428. DBGLOG("Workunit write %u is unused - create null activity", id);
  19429. //Create a null sink activity that is always executed to ensure that stop() is called on the input.
  19430. return createRoxieServerNullSinkActivity(_ctx, this, _probeManager);
  19431. }
  19432. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  19433. }
  19434. virtual bool isSink() const
  19435. {
  19436. return isUnused || CRoxieServerInternalSinkFactory::isSink();
  19437. }
  19438. };
  19439. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19440. {
  19441. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19442. }
  19443. //=====================================================================================================
  19444. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  19445. {
  19446. IHThorDictionaryWorkUnitWriteArg &helper;
  19447. IRoxieServerContext *serverContext;
  19448. public:
  19449. CRoxieServerWorkUnitWriteDictActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  19450. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  19451. {
  19452. serverContext = NULL;
  19453. }
  19454. virtual void onCreate(IHThorArg *_colocalParent)
  19455. {
  19456. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19457. serverContext = ctx->queryServerContext();
  19458. if (!serverContext)
  19459. {
  19460. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in agent context");
  19461. }
  19462. }
  19463. virtual bool needsAllocator() const { return true; }
  19464. virtual void onExecute()
  19465. {
  19466. int sequence = helper.getSequence();
  19467. const char *storedName = helper.queryName();
  19468. assertex(storedName && *storedName);
  19469. assertex(sequence < 0);
  19470. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  19471. for (;;)
  19472. {
  19473. const void *row = inputStream->ungroupedNextRow();
  19474. if (!row)
  19475. break;
  19476. builder.appendOwn(row);
  19477. processed++;
  19478. }
  19479. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19480. }
  19481. };
  19482. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  19483. {
  19484. public:
  19485. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19486. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19487. {
  19488. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  19489. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19490. }
  19491. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19492. {
  19493. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  19494. }
  19495. };
  19496. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19497. {
  19498. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19499. }
  19500. //=================================================================================
  19501. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  19502. {
  19503. IHThorRemoteResultArg &helper;
  19504. public:
  19505. CRoxieServerRemoteResultActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  19506. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  19507. {
  19508. }
  19509. virtual void onExecute()
  19510. {
  19511. OwnedConstRoxieRow row = inputStream->nextRow();
  19512. helper.sendResult(row); // should be only one row or something has gone wrong!
  19513. }
  19514. };
  19515. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19516. {
  19517. public:
  19518. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19519. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19520. {
  19521. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19522. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19523. }
  19524. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19525. {
  19526. if (dependentCount==0 && !CRoxieServerInternalSinkFactory::isSink())
  19527. return new CRoxieServerNullSinkActivity(_ctx, this, _probeManager);
  19528. else
  19529. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19530. }
  19531. virtual bool isSink() const override
  19532. {
  19533. return CRoxieServerInternalSinkFactory::isSink() || dependentCount == 0; // Codegen normally optimizes these away, but if it doesn't we need to treat as a (null) sink rather than a dependency or upstream activities are not stopped properly
  19534. }
  19535. };
  19536. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19537. {
  19538. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19539. }
  19540. //=================================================================================
  19541. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19542. {
  19543. IHThorXmlParseArg &helper;
  19544. Owned<IXMLParse> xmlParser;
  19545. const void * in;
  19546. char * srchStr;
  19547. unsigned numProcessedLastGroup;
  19548. bool srchStrNeedsFree;
  19549. Owned<IColumnProvider> lastMatch;
  19550. public:
  19551. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19552. CRoxieServerXmlParseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19553. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19554. helper((IHThorXmlParseArg &)basehelper)
  19555. {
  19556. srchStrNeedsFree = helper.searchTextNeedsFree();
  19557. numProcessedLastGroup = 0;
  19558. srchStr = NULL;
  19559. in = NULL;
  19560. }
  19561. ~CRoxieServerXmlParseActivity()
  19562. {
  19563. }
  19564. virtual bool needsAllocator() const { return true; }
  19565. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19566. {
  19567. numProcessedLastGroup = 0;
  19568. srchStr = NULL;
  19569. in = NULL;
  19570. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19571. }
  19572. virtual void reset()
  19573. {
  19574. if (helper.searchTextNeedsFree())
  19575. rtlFree(srchStr);
  19576. srchStr = NULL;
  19577. ReleaseClearRoxieRow(in);
  19578. xmlParser.clear();
  19579. CRoxieServerActivity::reset();
  19580. }
  19581. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19582. {
  19583. lastMatch.set(&entry);
  19584. }
  19585. virtual const void *nextRow()
  19586. {
  19587. ActivityTimer t(activityStats, timeActivities);
  19588. for (;;)
  19589. {
  19590. if(xmlParser)
  19591. {
  19592. for (;;)
  19593. {
  19594. if(!xmlParser->next())
  19595. {
  19596. if (srchStrNeedsFree)
  19597. {
  19598. rtlFree(srchStr);
  19599. srchStr = NULL;
  19600. }
  19601. xmlParser.clear();
  19602. break;
  19603. }
  19604. if(lastMatch)
  19605. {
  19606. try
  19607. {
  19608. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19609. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19610. lastMatch.clear();
  19611. if (outSize)
  19612. {
  19613. processed++;
  19614. return rowBuilder.finalizeRowClear(outSize);
  19615. }
  19616. }
  19617. catch (IException *E)
  19618. {
  19619. throw makeWrappedException(E);
  19620. }
  19621. }
  19622. }
  19623. }
  19624. ReleaseClearRoxieRow(in);
  19625. in = inputStream->nextRow();
  19626. if(!in)
  19627. {
  19628. if(numProcessedLastGroup == processed)
  19629. in = inputStream->nextRow();
  19630. if(!in)
  19631. {
  19632. numProcessedLastGroup = processed;
  19633. return NULL;
  19634. }
  19635. }
  19636. size32_t srchLen;
  19637. helper.getSearchText(srchLen, srchStr, in);
  19638. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19639. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19640. }
  19641. }
  19642. };
  19643. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19644. {
  19645. public:
  19646. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19647. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19648. {
  19649. }
  19650. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  19651. {
  19652. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19653. }
  19654. };
  19655. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19656. {
  19657. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19658. }
  19659. //=====================================================================================================
  19660. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19661. {
  19662. protected:
  19663. IHThorDiskReadBaseArg &helper;
  19664. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  19665. IHThorCompoundExtra * compoundHelper;
  19666. RemoteActivityId remoteId; // Note we copy it rather than reference
  19667. Owned<CSkippableRemoteResultAdaptor> remote;
  19668. unsigned numParts;
  19669. unsigned __int64 rowLimit;
  19670. unsigned __int64 stopAfter;
  19671. Linked<IInMemoryIndexManager> manager;
  19672. Linked<ITranslatorSet> translators;
  19673. ScoredRowFilter postFilter;
  19674. Owned<IDirectReader> reader;
  19675. bool eof;
  19676. bool variableFileName;
  19677. bool isOpt;
  19678. bool sorted;
  19679. bool maySkip;
  19680. bool isLocal;
  19681. bool forceRemote;
  19682. bool isGrouped = false;
  19683. CachedOutputMetaData diskSize;
  19684. Owned<const IResolvedFile> varFileInfo;
  19685. inline bool useRemote()
  19686. {
  19687. return remote != NULL && (forceRemote || numParts > 1);
  19688. }
  19689. public:
  19690. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19691. CRoxieServerDiskReadBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19692. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19693. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19694. helper((IHThorDiskReadBaseArg &)basehelper),
  19695. remoteId(_remoteId),
  19696. numParts(_numParts),
  19697. manager(_manager),
  19698. translators(_translators),
  19699. sorted(_sorted),
  19700. maySkip(_maySkip),
  19701. isLocal(_isLocal)
  19702. {
  19703. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19704. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19705. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19706. compoundHelper = NULL;
  19707. eof = false;
  19708. rowLimit = (unsigned __int64) -1;
  19709. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19710. diskSize.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19711. isGrouped = diskSize.isGrouped();
  19712. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19713. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19714. }
  19715. virtual const IResolvedFile *queryVarFileInfo() const
  19716. {
  19717. return varFileInfo;
  19718. }
  19719. virtual void onCreate(IHThorArg *_colocalParent)
  19720. {
  19721. CRoxieServerActivity::onCreate(_colocalParent);
  19722. if (remote)
  19723. remote->onCreate(_colocalParent);
  19724. }
  19725. virtual bool needsAllocator() const { return true; }
  19726. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19727. {
  19728. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19729. if (compoundHelper)
  19730. {
  19731. rowLimit = compoundHelper->getRowLimit();
  19732. stopAfter = compoundHelper->getChooseNLimit();
  19733. }
  19734. if (!helper.canMatchAny())
  19735. eof = true;
  19736. else
  19737. {
  19738. if (variableFileName)
  19739. {
  19740. OwnedRoxieString fileName(helper.getFileName());
  19741. varFileInfo.setown(resolveLFNFlat(fileName, isOpt, factory->isActivityCodeSigned()));
  19742. numParts = 0;
  19743. if (varFileInfo)
  19744. numParts = varFileInfo->getNumParts();
  19745. }
  19746. if (!numParts)
  19747. {
  19748. eof = true;
  19749. }
  19750. else if (useRemote())
  19751. {
  19752. remote->onStart(parentExtractSize, parentExtract);
  19753. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19754. unsigned fileNo = 0;
  19755. // Translation into a message per channel done elsewhere....
  19756. remote->getMem(0, fileNo, 0);
  19757. remote->flush();
  19758. remote->senddone();
  19759. }
  19760. else
  19761. {
  19762. if (variableFileName)
  19763. {
  19764. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19765. unsigned expectedFormatCrc = helper.getDiskFormatCrc();
  19766. unsigned projectedFormatCrc = helper.getProjectedFormatCrc();
  19767. translators.setown(varFileInfo->getTranslators(projectedFormatCrc, helper.queryProjectedDiskRecordSize(), expectedFormatCrc, helper.queryDiskRecordSize(), getEnableFieldTranslation(), FileFormatMode::flat, queryFactory()->queryQueryFactory().queryQueryName()));
  19768. manager.setown(varFileInfo->getIndexManager(isOpt, channel, translators->queryActualLayout(0), false));
  19769. }
  19770. assertex(manager != NULL);
  19771. postFilter.clear();
  19772. helper.createSegmentMonitors(this);
  19773. const IKeyTranslator *keyTranslator = translators->queryKeyTranslator(0); // any part would do - in-memory requires all actuals to have same layout
  19774. if (keyTranslator)
  19775. keyTranslator->translate(postFilter);
  19776. reader.setown(manager->selectKey(postFilter, translators, *this));
  19777. if (!reader)
  19778. reader.setown(manager->createReader(postFilter, isGrouped, 0, 0, 1, translators));
  19779. assertex(reader);
  19780. helper.setCallback(reader);
  19781. }
  19782. }
  19783. }
  19784. virtual void append(IKeySegmentMonitor *segment)
  19785. {
  19786. segment->Release();
  19787. throwUnexpected();
  19788. }
  19789. virtual void append(FFoption option, const IFieldFilter * filter)
  19790. {
  19791. if (filter->isWild())
  19792. filter->Release();
  19793. else
  19794. postFilter.addFilter(*filter);
  19795. }
  19796. virtual void stop()
  19797. {
  19798. if (useRemote())
  19799. remote->onStop();
  19800. CRoxieServerActivity::stop();
  19801. }
  19802. virtual void reset()
  19803. {
  19804. if (useRemote())
  19805. {
  19806. processed = remote->processed;
  19807. remote->processed = 0;
  19808. remote->onReset();
  19809. }
  19810. varFileInfo.clear();
  19811. eof = false;
  19812. reader.clear();
  19813. CRoxieServerActivity::reset();
  19814. }
  19815. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19816. {
  19817. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19818. }
  19819. virtual void onLimitExceeded(bool isKeyed)
  19820. {
  19821. if (traceLevel > 4)
  19822. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19823. assertex(compoundHelper);
  19824. if (isKeyed) // MORE does this exist for diskread? should it?
  19825. {
  19826. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19827. {
  19828. if (ctx->queryDebugContext())
  19829. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19830. throw makeLimitSkipException(true);
  19831. }
  19832. else
  19833. {
  19834. UNIMPLEMENTED;
  19835. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19836. }
  19837. }
  19838. else
  19839. {
  19840. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19841. {
  19842. if (ctx->queryDebugContext())
  19843. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19844. throw makeLimitSkipException(false);
  19845. }
  19846. else
  19847. compoundHelper->onLimitExceeded();
  19848. }
  19849. }
  19850. virtual const void * createLimitFailRow(bool isKeyed)
  19851. {
  19852. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19853. assertex(limitTransformExtra);
  19854. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19855. if (outSize)
  19856. return rowBuilder.finalizeRowClear(outSize);
  19857. return NULL;
  19858. }
  19859. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19860. {
  19861. CRoxieServerActivity::gatherStats(merged);
  19862. if (remote)
  19863. remote->gatherStats(merged);
  19864. }
  19865. };
  19866. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19867. {
  19868. IHThorDiskReadArg * readHelper;
  19869. ConstPointerArray readrows;
  19870. bool readAheadDone;
  19871. unsigned readIndex;
  19872. unsigned lastGroupProcessed;
  19873. bool someInGroup = false;
  19874. public:
  19875. CRoxieServerDiskReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19876. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19877. {
  19878. compoundHelper = (IHThorDiskReadArg *)&helper;
  19879. readHelper = (IHThorDiskReadArg *)&helper;
  19880. limitTransformExtra = readHelper;
  19881. readAheadDone = false;
  19882. readIndex = 0;
  19883. lastGroupProcessed = processed;
  19884. }
  19885. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19886. {
  19887. rowLimit = compoundHelper->getRowLimit();
  19888. stopAfter = compoundHelper->getChooseNLimit();
  19889. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19890. readAheadDone = false;
  19891. readIndex = 0;
  19892. lastGroupProcessed = processed;
  19893. someInGroup = false;
  19894. }
  19895. virtual void reset()
  19896. {
  19897. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19898. readrows.kill();
  19899. readAheadDone = false;
  19900. readIndex = 0;
  19901. lastGroupProcessed = processed;
  19902. someInGroup = false;
  19903. CRoxieServerDiskReadBaseActivity::reset();
  19904. }
  19905. virtual const void *nextRow()
  19906. {
  19907. ActivityTimer t(activityStats, timeActivities);
  19908. if (eof)
  19909. return NULL;
  19910. else if (useRemote())
  19911. return remote->nextRow();
  19912. else if (maySkip)
  19913. {
  19914. if (!readAheadDone)
  19915. {
  19916. unsigned preprocessed = 0;
  19917. while (!eof)
  19918. {
  19919. const void *row = _nextRow();
  19920. if (row)
  19921. preprocessed++;
  19922. if (preprocessed > rowLimit)
  19923. {
  19924. ReleaseRoxieRow(row);
  19925. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19926. readrows.kill();
  19927. readIndex = 0;
  19928. eof = true;
  19929. if (ctx->queryDebugContext())
  19930. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19931. if (helper.getFlags() & TDRlimitskips)
  19932. return NULL;
  19933. else if (helper.getFlags() & TDRlimitcreates)
  19934. return createLimitFailRow(false);
  19935. else
  19936. throwUnexpected();
  19937. }
  19938. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19939. {
  19940. eof = true;
  19941. ReleaseRoxieRow(row);
  19942. break;
  19943. }
  19944. readrows.append(row);
  19945. }
  19946. readAheadDone = true;
  19947. }
  19948. if (readrows.isItem(readIndex))
  19949. {
  19950. const void *ret = readrows.item(readIndex++);
  19951. if (ret)
  19952. processed++;
  19953. return ret;
  19954. }
  19955. else
  19956. {
  19957. eof = true;
  19958. return NULL;
  19959. }
  19960. }
  19961. else
  19962. {
  19963. const void *ret = _nextRow();
  19964. if (ret)
  19965. {
  19966. processed++;
  19967. if (processed > rowLimit)
  19968. {
  19969. if (traceLevel > 4)
  19970. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19971. ReleaseRoxieRow(ret);
  19972. compoundHelper->onLimitExceeded();
  19973. throwUnexpected(); // onLimitExceeded is not supposed to return
  19974. }
  19975. if (processed > stopAfter) // MORE - bit of a strange place to check
  19976. {
  19977. eof = true;
  19978. ReleaseRoxieRow(ret);
  19979. return NULL;
  19980. }
  19981. }
  19982. return ret;
  19983. }
  19984. }
  19985. const void *_nextRow()
  19986. {
  19987. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19988. unsigned transformedSize = 0;
  19989. for (;;)
  19990. {
  19991. const byte *nextRec = reader->nextRow();
  19992. if (nextRec)
  19993. {
  19994. someInGroup = true;
  19995. if (likely(readHelper->canMatch(nextRec)))
  19996. {
  19997. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19998. reader->finishedRow();
  19999. if (transformedSize)
  20000. break;
  20001. }
  20002. else
  20003. reader->finishedRow();
  20004. }
  20005. else if (isGrouped)
  20006. {
  20007. if (lastGroupProcessed != processed)
  20008. {
  20009. someInGroup = false;
  20010. lastGroupProcessed = processed;
  20011. return nullptr;
  20012. }
  20013. else if (!someInGroup)
  20014. {
  20015. eof = true;
  20016. return nullptr;
  20017. }
  20018. }
  20019. else
  20020. {
  20021. eof = true;
  20022. return nullptr;
  20023. }
  20024. }
  20025. return rowBuilder.finalizeRowClear(transformedSize);
  20026. }
  20027. };
  20028. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  20029. {
  20030. IHThorXmlReadArg * readHelper;
  20031. Owned<IXmlToRowTransformer> rowTransformer;
  20032. Owned<IXMLParse> xmlParser;
  20033. Owned<IColumnProvider> lastMatch;
  20034. unsigned __int64 fileoffset;
  20035. IDirectStreamReader *streamReader = nullptr;
  20036. public:
  20037. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  20038. CRoxieServerXmlReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20039. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20040. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  20041. {
  20042. compoundHelper = NULL;
  20043. readHelper = (IHThorXmlReadArg *)&helper;
  20044. fileoffset = 0;
  20045. }
  20046. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20047. {
  20048. rowLimit = readHelper->getRowLimit();
  20049. stopAfter = readHelper->getChooseNLimit();
  20050. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20051. if (!useRemote())
  20052. {
  20053. rowTransformer.set(readHelper->queryTransformer());
  20054. assertex(reader != NULL);
  20055. streamReader = reader->queryDirectStreamReader();
  20056. assertex(streamReader != NULL);
  20057. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  20058. if (factory->getKind()==TAKjsonread)
  20059. xmlParser.setown(createJSONParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  20060. else
  20061. xmlParser.setown(createXMLParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  20062. }
  20063. }
  20064. virtual void reset()
  20065. {
  20066. CRoxieServerDiskReadBaseActivity::reset();
  20067. rowTransformer.clear();
  20068. xmlParser.clear();
  20069. }
  20070. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  20071. {
  20072. fileoffset = startOffset;
  20073. lastMatch.set(&entry);
  20074. }
  20075. //interface IThorDiskCallback
  20076. virtual unsigned __int64 getFilePosition(const void * row)
  20077. {
  20078. return fileoffset;
  20079. }
  20080. virtual unsigned __int64 getLocalFilePosition(const void * row)
  20081. {
  20082. return streamReader->makeFilePositionLocal(fileoffset);
  20083. }
  20084. virtual const char * queryLogicalFilename(const void * row)
  20085. {
  20086. return reader->queryLogicalFilename(row);
  20087. }
  20088. virtual const byte * lookupBlob(unsigned __int64 id) { UNIMPLEMENTED; }
  20089. virtual const void *nextRow()
  20090. {
  20091. ActivityTimer t(activityStats, timeActivities);
  20092. if (eof)
  20093. return NULL;
  20094. else if (useRemote())
  20095. return remote->nextRow();
  20096. assertex(xmlParser != NULL);
  20097. try
  20098. {
  20099. while (!eof)
  20100. {
  20101. //call to next() will callback on the IXmlSelect interface
  20102. bool gotNext = false;
  20103. gotNext = xmlParser->next();
  20104. if(!gotNext)
  20105. eof = true;
  20106. else if (lastMatch)
  20107. {
  20108. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20109. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  20110. lastMatch.clear();
  20111. fileoffset = 0;
  20112. if (sizeGot)
  20113. {
  20114. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  20115. if (processed > rowLimit)
  20116. {
  20117. if (traceLevel > 4)
  20118. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20119. readHelper->onLimitExceeded();
  20120. throwUnexpected(); // onLimitExceeded is not supposed to return
  20121. }
  20122. processed++;
  20123. if (processed > stopAfter) // MORE - bit of a strange place to check
  20124. {
  20125. eof = true;
  20126. return NULL;
  20127. }
  20128. return ret.getClear();
  20129. }
  20130. }
  20131. }
  20132. return NULL;
  20133. }
  20134. catch(IException *E)
  20135. {
  20136. throw makeWrappedException(E);
  20137. }
  20138. }
  20139. };
  20140. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  20141. {
  20142. IHThorCsvReadArg *readHelper;
  20143. ICsvParameters * csvInfo;
  20144. unsigned headerLines;
  20145. unsigned maxDiskSize;
  20146. CSVSplitter csvSplitter;
  20147. unsigned __int64 localOffset;
  20148. IDirectStreamReader *streamReader = nullptr;
  20149. const char *quotes;
  20150. const char *separators;
  20151. const char *terminators;
  20152. const char *escapes;
  20153. size32_t maxRowSize;
  20154. public:
  20155. CRoxieServerCsvReadActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20156. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators,
  20157. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  20158. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators),
  20159. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  20160. {
  20161. compoundHelper = NULL;
  20162. readHelper = (IHThorCsvReadArg *)&helper;
  20163. rowLimit = readHelper->getRowLimit();
  20164. stopAfter = readHelper->getChooseNLimit();
  20165. csvInfo = readHelper->queryCsvParameters();
  20166. maxDiskSize = csvInfo->queryMaxSize();
  20167. localOffset = 0;
  20168. headerLines = 0;
  20169. }
  20170. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20171. {
  20172. rowLimit = readHelper->getRowLimit();
  20173. stopAfter = readHelper->getChooseNLimit();
  20174. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20175. if (!useRemote())
  20176. {
  20177. if (!eof)
  20178. {
  20179. assertex(reader != nullptr);
  20180. streamReader = reader->queryDirectStreamReader();
  20181. assertex(streamReader != nullptr);
  20182. headerLines = csvInfo->queryHeaderLen();
  20183. if (headerLines && isLocal && streamReader->queryFilePart() != 1)
  20184. 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...
  20185. if (varFileInfo)
  20186. {
  20187. const IPropertyTree *options = varFileInfo->queryProperties();
  20188. if (options)
  20189. {
  20190. quotes = options->queryProp("@csvQuote");
  20191. separators = options->queryProp("@csvSeparate");
  20192. terminators = options->queryProp("@csvTerminate");
  20193. escapes = options->queryProp("@csvEscape");
  20194. }
  20195. }
  20196. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  20197. }
  20198. }
  20199. }
  20200. virtual const void *nextRow()
  20201. {
  20202. ActivityTimer t(activityStats, timeActivities);
  20203. if (eof)
  20204. return NULL;
  20205. else if (useRemote())
  20206. return remote->nextRow();
  20207. try
  20208. {
  20209. while (!eof)
  20210. {
  20211. size32_t thisLineLength = csvSplitter.splitLine(streamReader, maxRowSize);
  20212. if (!thisLineLength)
  20213. break;
  20214. if (headerLines)
  20215. {
  20216. headerLines--;
  20217. streamReader->skip(thisLineLength);
  20218. }
  20219. else
  20220. {
  20221. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20222. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  20223. streamReader->skip(thisLineLength);
  20224. if (transformedSize)
  20225. {
  20226. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  20227. if (processed > rowLimit)
  20228. {
  20229. readHelper->onLimitExceeded();
  20230. throwUnexpected(); // onLimitExceeded is not supposed to return
  20231. }
  20232. processed++;
  20233. if (processed > stopAfter) // MORE - bit of a strange place to check
  20234. {
  20235. eof = true;
  20236. return NULL;
  20237. }
  20238. return ret.getClear();
  20239. }
  20240. }
  20241. }
  20242. return NULL;
  20243. }
  20244. catch(IException *E)
  20245. {
  20246. throw makeWrappedException(E);
  20247. }
  20248. }
  20249. virtual void reset()
  20250. {
  20251. CRoxieServerDiskReadBaseActivity::reset();
  20252. csvSplitter.reset();
  20253. localOffset = 0;
  20254. }
  20255. virtual unsigned __int64 getFilePosition(const void * row)
  20256. {
  20257. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  20258. }
  20259. virtual unsigned __int64 getLocalFilePosition(const void * row)
  20260. {
  20261. UNIMPLEMENTED;
  20262. }
  20263. };
  20264. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  20265. {
  20266. IHThorDiskNormalizeArg *normalizeHelper;
  20267. bool firstPending;
  20268. public:
  20269. CRoxieServerDiskNormalizeActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20270. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager, _translators)
  20271. {
  20272. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  20273. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  20274. limitTransformExtra = normalizeHelper;
  20275. firstPending = true;
  20276. }
  20277. virtual void reset()
  20278. {
  20279. firstPending = true;
  20280. CRoxieServerDiskReadBaseActivity::reset();
  20281. }
  20282. virtual const void *nextRow()
  20283. {
  20284. ActivityTimer t(activityStats, timeActivities);
  20285. if (eof)
  20286. return NULL;
  20287. else if (useRemote())
  20288. return remote->nextRow();
  20289. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20290. unsigned transformedSize = 0;
  20291. for (;;)
  20292. {
  20293. while (firstPending)
  20294. {
  20295. const byte *nextRec = reader->nextRow();
  20296. if (!nextRec)
  20297. {
  20298. eof = true;
  20299. return NULL;
  20300. }
  20301. if (normalizeHelper->first(nextRec))
  20302. firstPending = false;
  20303. reader->finishedRow();
  20304. }
  20305. transformedSize = normalizeHelper->transform(rowBuilder);
  20306. firstPending = !normalizeHelper->next();
  20307. if (transformedSize)
  20308. break;
  20309. }
  20310. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  20311. processed++;
  20312. if (processed > rowLimit)
  20313. {
  20314. compoundHelper->onLimitExceeded();
  20315. throwUnexpected(); // onLimitExceeded is not supposed to return
  20316. }
  20317. if (processed > stopAfter) // MORE - bit of a strange place to check
  20318. {
  20319. eof = true;
  20320. return NULL;
  20321. }
  20322. return recBuffer.getClear();
  20323. }
  20324. };
  20325. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  20326. {
  20327. protected:
  20328. bool done;
  20329. public:
  20330. CRoxieServerDiskAggregateBaseActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20331. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager, _translators),
  20332. done(false)
  20333. {
  20334. }
  20335. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20336. {
  20337. done = false;
  20338. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20339. }
  20340. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  20341. {
  20342. if (idx==(unsigned)-1)
  20343. idx = 0;
  20344. return idx ? NULL: this;
  20345. }
  20346. };
  20347. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  20348. {
  20349. IHThorDiskCountArg & countHelper;
  20350. unsigned __int64 choosenLimit;
  20351. unsigned __int64 getSkippedCount()
  20352. {
  20353. unsigned flags = countHelper.getFlags();
  20354. if (flags & TDRlimitskips)
  20355. return 0;
  20356. else if (flags & TDRlimitcreates)
  20357. return 1;
  20358. else
  20359. {
  20360. countHelper.onLimitExceeded();
  20361. throwUnexpected(); // onLimitExceeded should always throw exception
  20362. }
  20363. }
  20364. public:
  20365. CRoxieServerDiskCountActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20366. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20367. countHelper((IHThorDiskCountArg &)basehelper)
  20368. {
  20369. choosenLimit = 0;
  20370. }
  20371. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20372. {
  20373. choosenLimit = countHelper.getChooseNLimit();
  20374. rowLimit = countHelper.getRowLimit();
  20375. // keyedLimit = countHelper->getKeyedLimit(); // more - should there be one?
  20376. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20377. }
  20378. virtual const void *nextRow()
  20379. {
  20380. ActivityTimer t(activityStats, timeActivities);
  20381. if (done) return NULL;
  20382. done = true;
  20383. unsigned __int64 totalCount = 0;
  20384. if (helper.canMatchAny() && !eof)
  20385. {
  20386. if (useRemote())
  20387. {
  20388. for (;;)
  20389. {
  20390. const void * next = remote->nextRow();
  20391. if (!next)
  20392. break;
  20393. if (meta.getFixedSize() == 1)
  20394. totalCount += *(byte *)next;
  20395. else
  20396. totalCount += *(unsigned __int64 *)next;
  20397. ReleaseRoxieRow(next);
  20398. if (totalCount > rowLimit)
  20399. {
  20400. totalCount = getSkippedCount();
  20401. break;
  20402. }
  20403. else if (totalCount >= choosenLimit)
  20404. {
  20405. totalCount = choosenLimit;
  20406. break;
  20407. }
  20408. }
  20409. }
  20410. else
  20411. {
  20412. for (;;)
  20413. {
  20414. const byte *nextRec = reader->nextRow();
  20415. if (!nextRec)
  20416. break;
  20417. totalCount += countHelper.numValid(nextRec);
  20418. reader->finishedRow();
  20419. if (totalCount > rowLimit)
  20420. {
  20421. totalCount = getSkippedCount();
  20422. break;
  20423. }
  20424. else if (totalCount >= choosenLimit)
  20425. {
  20426. totalCount = choosenLimit;
  20427. break;
  20428. }
  20429. }
  20430. }
  20431. }
  20432. processed++;
  20433. size32_t rowSize = meta.getFixedSize();
  20434. void * result = rowAllocator->createRow();
  20435. if (rowSize == 1)
  20436. *(byte *)result = (byte)totalCount;
  20437. else
  20438. {
  20439. assertex(rowSize == sizeof(unsigned __int64));
  20440. *(unsigned __int64 *)result = totalCount;
  20441. }
  20442. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20443. }
  20444. };
  20445. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20446. {
  20447. IHThorCompoundAggregateExtra & aggregateHelper;
  20448. public:
  20449. CRoxieServerDiskAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20450. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20451. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20452. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20453. {
  20454. }
  20455. const void * gatherMerged()
  20456. {
  20457. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20458. size32_t finalSize = 0;
  20459. if (useRemote())
  20460. {
  20461. const void * firstRow = remote->nextRow();
  20462. if (!firstRow)
  20463. {
  20464. rowBuilder.ensureRow();
  20465. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20466. }
  20467. else
  20468. {
  20469. // NOTE need to clone this because going to modify below, could special case 1 row only
  20470. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20471. ReleaseRoxieRow(firstRow);
  20472. }
  20473. for (;;)
  20474. {
  20475. const void * next = remote->nextRow();
  20476. if (!next)
  20477. break;
  20478. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20479. ReleaseRoxieRow(next);
  20480. }
  20481. }
  20482. else
  20483. {
  20484. aggregateHelper.clearAggregate(rowBuilder);
  20485. if (helper.canMatchAny() && !eof)
  20486. {
  20487. for (;;)
  20488. {
  20489. const byte *nextRec = reader->nextRow();
  20490. if (!nextRec)
  20491. break;
  20492. aggregateHelper.processRow(rowBuilder, nextRec);
  20493. reader->finishedRow();
  20494. }
  20495. }
  20496. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20497. }
  20498. return rowBuilder.finalizeRowClear(finalSize);
  20499. }
  20500. virtual const void *nextRow()
  20501. {
  20502. ActivityTimer t(activityStats, timeActivities);
  20503. if (done) return NULL;
  20504. const void * ret = gatherMerged();
  20505. processed++;
  20506. done = true;
  20507. return ret;
  20508. }
  20509. };
  20510. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20511. {
  20512. IHThorDiskGroupAggregateArg & aggregateHelper;
  20513. RowAggregator resultAggregator;
  20514. bool gathered;
  20515. public:
  20516. CRoxieServerDiskGroupAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20517. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20518. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20519. resultAggregator(aggregateHelper, aggregateHelper),
  20520. gathered(false)
  20521. {
  20522. }
  20523. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20524. {
  20525. gathered= false;
  20526. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20527. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  20528. }
  20529. virtual void reset()
  20530. {
  20531. resultAggregator.reset();
  20532. CRoxieServerDiskAggregateBaseActivity::reset();
  20533. }
  20534. void gatherMerged()
  20535. {
  20536. if (useRemote())
  20537. {
  20538. for (;;)
  20539. {
  20540. const void * next = remote->nextRow();
  20541. if (!next)
  20542. break;
  20543. resultAggregator.mergeElement(next);
  20544. ReleaseRoxieRow(next);
  20545. }
  20546. }
  20547. else
  20548. {
  20549. if (helper.canMatchAny() && !eof)
  20550. {
  20551. Owned<IInMemoryFileProcessor> processor = createGroupAggregateRecordProcessor(resultAggregator, aggregateHelper, reader);
  20552. processor->doQuery(NULL, 0, 0, 0);
  20553. }
  20554. }
  20555. gathered = true;
  20556. }
  20557. virtual const void *nextRow()
  20558. {
  20559. ActivityTimer t(activityStats, timeActivities);
  20560. if (done)
  20561. return NULL;
  20562. if (!gathered)
  20563. gatherMerged();
  20564. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20565. if (next)
  20566. {
  20567. processed++;
  20568. return next->finalizeRowClear();
  20569. }
  20570. done = true;
  20571. return NULL;
  20572. }
  20573. };
  20574. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20575. {
  20576. public:
  20577. RemoteActivityId remoteId;
  20578. bool isLocal;
  20579. bool sorted;
  20580. bool maySkip;
  20581. bool variableFileName;
  20582. Owned<ITranslatorSet> translators;
  20583. Owned<IInMemoryIndexManager> manager;
  20584. Owned<const IResolvedFile> datafile;
  20585. const char *quotes;
  20586. const char *separators;
  20587. const char *terminators;
  20588. const char *escapes;
  20589. size32_t maxCsvRowSize;
  20590. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20591. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20592. {
  20593. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20594. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20595. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20596. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20597. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20598. quotes = separators = terminators = escapes = NULL;
  20599. if (!variableFileName)
  20600. {
  20601. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20602. OwnedRoxieString fileName(helper->getFileName());
  20603. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  20604. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20605. if (isLocal || isSimple)
  20606. {
  20607. if (datafile)
  20608. {
  20609. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20610. unsigned expectedFormatCrc = helper->getDiskFormatCrc();
  20611. unsigned projectedFormatCrc = helper->getProjectedFormatCrc();
  20612. translators.setown(datafile->getTranslators(projectedFormatCrc, helper->queryProjectedDiskRecordSize(), expectedFormatCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), expectedFileMode(), queryFactory.queryQueryName()));
  20613. manager.setown(datafile->getIndexManager(isOpt, channel, translators->queryActualLayout(0), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false)));
  20614. const IPropertyTree *options = datafile->queryProperties();
  20615. if (options)
  20616. {
  20617. quotes = options->queryProp("@csvQuote");
  20618. separators = options->queryProp("@csvSeparate");
  20619. terminators = options->queryProp("@csvTerminate");
  20620. escapes = options->queryProp("@csvEscape");
  20621. }
  20622. }
  20623. else
  20624. manager.setown(createInMemoryIndexManager(helper->queryProjectedDiskRecordSize()->queryRecordAccessor(true), true, nullptr));
  20625. }
  20626. }
  20627. switch (kind)
  20628. {
  20629. case TAKcsvread:
  20630. {
  20631. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20632. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20633. if (workunit)
  20634. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20635. break;
  20636. }
  20637. default:
  20638. maxCsvRowSize = 0; // unused
  20639. }
  20640. }
  20641. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  20642. {
  20643. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20644. switch (kind)
  20645. {
  20646. case TAKcsvread:
  20647. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators,
  20648. quotes, separators, terminators, escapes, maxCsvRowSize);
  20649. case TAKxmlread:
  20650. case TAKjsonread:
  20651. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20652. case TAKdiskread:
  20653. case TAKspillread:
  20654. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20655. case TAKdisknormalize:
  20656. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager, translators);
  20657. case TAKdiskcount:
  20658. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20659. case TAKdiskaggregate:
  20660. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20661. case TAKdiskgroupaggregate:
  20662. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20663. }
  20664. throwUnexpected();
  20665. }
  20666. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20667. {
  20668. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20669. }
  20670. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20671. {
  20672. if (datafile)
  20673. addXrefFileInfo(reply, datafile);
  20674. else
  20675. {
  20676. // Temporarily resolve the file
  20677. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20678. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20679. {
  20680. OwnedRoxieString fileName(helper->getFileName());
  20681. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true, isActivityCodeSigned());
  20682. if (temp)
  20683. addXrefFileInfo(reply, temp);
  20684. }
  20685. }
  20686. }
  20687. virtual const StatisticsMapping &queryStatsMapping() const
  20688. {
  20689. return diskStatistics;
  20690. }
  20691. };
  20692. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20693. {
  20694. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20695. }
  20696. //=================================================================================
  20697. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20698. {
  20699. public:
  20700. Owned<IKeyArray> keySet;
  20701. Owned<ITranslatorSet> translators;
  20702. RemoteActivityId remoteId;
  20703. bool isSimple;
  20704. bool isLocal;
  20705. bool maySkip;
  20706. bool sorted;
  20707. bool variableFileName;
  20708. unsigned maxSeekLookahead;
  20709. Owned<const IResolvedFile> indexfile;
  20710. CRoxieServerSideCache *cache;
  20711. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20712. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20713. {
  20714. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20715. unsigned flags = indexHelper->getFlags();
  20716. sorted = (flags & TIRunordered) == 0;
  20717. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20718. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20719. if (!variableFileName)
  20720. {
  20721. bool isOpt = (flags & TIRoptional) != 0;
  20722. OwnedRoxieString indexName(indexHelper->getFileName());
  20723. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  20724. if (indexfile)
  20725. {
  20726. unsigned projectedCrc = indexHelper->getProjectedFormatCrc();
  20727. unsigned expectedCrc = indexHelper->getDiskFormatCrc();
  20728. IOutputMetaData *projectedMeta = indexHelper->queryProjectedDiskRecordSize();
  20729. IOutputMetaData *expectedMeta = indexHelper->queryDiskRecordSize();
  20730. translators.setown(indexfile->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), FileFormatMode::index, queryFactory.queryQueryName()));
  20731. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  20732. }
  20733. }
  20734. isSimple = isLocal;
  20735. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20736. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20737. {
  20738. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20739. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20740. isSimple = true;
  20741. }
  20742. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20743. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20744. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20745. }
  20746. ~CRoxieServerBaseIndexActivityFactory()
  20747. {
  20748. delete cache;
  20749. }
  20750. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20751. {
  20752. if (indexfile)
  20753. addXrefFileInfo(reply, indexfile);
  20754. else
  20755. {
  20756. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20757. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20758. {
  20759. OwnedRoxieString indexName(indexHelper->getFileName());
  20760. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true, isActivityCodeSigned());
  20761. if (temp)
  20762. addXrefFileInfo(reply, temp);
  20763. }
  20764. }
  20765. }
  20766. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20767. {
  20768. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20769. }
  20770. virtual IRoxieServerSideCache *queryServerSideCache() const
  20771. {
  20772. return cache;
  20773. }
  20774. virtual const StatisticsMapping &queryStatsMapping() const
  20775. {
  20776. return indexStatistics;
  20777. }
  20778. };
  20779. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20780. {
  20781. protected:
  20782. IHThorIndexReadBaseArg &indexHelper;
  20783. IHThorSteppedSourceExtra *steppedExtra;
  20784. Linked<IKeyArray> keySet;
  20785. Linked<ITranslatorSet> translators;
  20786. CSkippableRemoteResultAdaptor remote;
  20787. CIndexTransformCallback callback;
  20788. bool sorted;
  20789. bool variableFileName;
  20790. bool variableInfoPending;
  20791. bool isOpt;
  20792. bool isLocal;
  20793. unsigned __int64 rowLimit;
  20794. unsigned __int64 keyedLimit;
  20795. unsigned __int64 choosenLimit;
  20796. unsigned accepted;
  20797. unsigned rejected;
  20798. unsigned seekGEOffset;
  20799. Owned<IKeyManager> tlk;
  20800. Owned<const IResolvedFile> varFileInfo;
  20801. const RemoteActivityId &remoteId;
  20802. void setVariableFileInfo()
  20803. {
  20804. OwnedRoxieString indexName(indexHelper.getFileName());
  20805. varFileInfo.setown(resolveLFNIndex(indexName, isOpt, defaultPrivilegedUser));
  20806. if (varFileInfo)
  20807. {
  20808. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  20809. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  20810. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  20811. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  20812. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), FileFormatMode::index, factory->queryQueryFactory().queryQueryName()));
  20813. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  20814. }
  20815. variableInfoPending = false;
  20816. }
  20817. public:
  20818. CRoxieServerIndexActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20819. bool _sorted, bool _isLocal, bool _maySkip)
  20820. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20821. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20822. keySet(_factory->keySet),
  20823. translators(_factory->translators),
  20824. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20825. sorted(_sorted),
  20826. isLocal(_isLocal) ,
  20827. remoteId(_remoteId)
  20828. {
  20829. indexHelper.setCallback(&callback);
  20830. steppedExtra = indexHelper.querySteppingExtra();
  20831. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20832. variableInfoPending = false;
  20833. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20834. seekGEOffset = 0;
  20835. // started = false;
  20836. rejected = accepted = 0;
  20837. rowLimit = choosenLimit = keyedLimit = 0;
  20838. }
  20839. virtual const IResolvedFile *queryVarFileInfo() const
  20840. {
  20841. return varFileInfo;
  20842. }
  20843. virtual void onCreate(IHThorArg *_colocalParent)
  20844. {
  20845. CRoxieServerActivity::onCreate(_colocalParent);
  20846. remote.onCreate(_colocalParent);
  20847. }
  20848. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20849. {
  20850. accepted = 0;
  20851. rejected = 0;
  20852. rowLimit = (unsigned __int64) -1;
  20853. keyedLimit = (unsigned __int64 ) -1;
  20854. choosenLimit = I64C(0x7fffffffffffffff);
  20855. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20856. remote.onStart(parentExtractSize, parentExtract);
  20857. variableInfoPending = variableFileName;
  20858. }
  20859. void processAllKeys()
  20860. {
  20861. try
  20862. {
  20863. bool noLocal = factory->queryQueryFactory().queryOptions().disableLocalOptimizations || seekGEOffset > 0;
  20864. if (indexHelper.canMatchAny())
  20865. {
  20866. if (variableInfoPending)
  20867. setVariableFileInfo();
  20868. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20869. if (keySet)
  20870. {
  20871. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20872. // 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
  20873. // However order is probably better to iterate fileno's inside partnos
  20874. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20875. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20876. {
  20877. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20878. if (thisBase)
  20879. {
  20880. unsigned fileNo = 0;
  20881. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20882. if (!thisKey->isTopLevelKey())
  20883. {
  20884. if (keyedLimit != (unsigned __int64) -1)
  20885. {
  20886. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20887. {
  20888. Owned<IKeyManager> countKey;
  20889. countKey.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20890. countKey->setLayoutTranslator(translators->queryTranslator(fileNo));
  20891. createSegmentMonitors(countKey);
  20892. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20893. if (count > keyedLimit)
  20894. {
  20895. if (traceLevel > 4)
  20896. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20897. onLimitExceeded(true);
  20898. }
  20899. }
  20900. }
  20901. }
  20902. if (seekGEOffset && !thisKey->isTopLevelKey())
  20903. {
  20904. tlk.setown(createSingleKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, seekGEOffset, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20905. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20906. }
  20907. else
  20908. {
  20909. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20910. if (!thisKey->isTopLevelKey())
  20911. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20912. else
  20913. tlk->setLayoutTranslator(nullptr);
  20914. }
  20915. createSegmentMonitors(tlk);
  20916. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20917. {
  20918. StringBuffer out;
  20919. tlk->describeFilter(out);
  20920. CTXLOG("Using filter %s", out.str());
  20921. if (ctx->queryProbeManager())
  20922. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20923. }
  20924. tlk->reset();
  20925. for (;;) // for each file part
  20926. {
  20927. //block for TransformCallbackAssociation
  20928. {
  20929. TransformCallbackAssociation associate(callback, tlk);
  20930. if (thisKey->isTopLevelKey())
  20931. {
  20932. if (thisKey->isFullySorted())
  20933. {
  20934. while (tlk->lookup(false))
  20935. {
  20936. unsigned agentPart = (unsigned)extractFpos(tlk);
  20937. if (agentPart)
  20938. {
  20939. accepted++;
  20940. remote.getMem(agentPart, fileNo, 0); // the cached context is all we need to send
  20941. if (sorted && numChannels>1)
  20942. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20943. }
  20944. }
  20945. }
  20946. else
  20947. {
  20948. unsigned agentPart = tlk->getPartition(); // Returns 0 if no partition info, or filter cannot be partitioned
  20949. remote.getMem(agentPart, fileNo, 0);
  20950. }
  20951. }
  20952. else
  20953. {
  20954. // Single - part key. We process locally unless smart-stepping is involved, in which case we need to ensure that
  20955. // we do the proper two-stage merge.
  20956. // Unfortunately processSingleKey will not use the merger we carefully set up before,
  20957. // so we disable the local processing in that case
  20958. if (noLocal)
  20959. remote.getMem(1, fileNo, 0); // 1 because it's a single part key
  20960. else if (processSingleKey(thisKey, translators->queryTranslator(fileNo)))
  20961. break;
  20962. }
  20963. }
  20964. if (++fileNo < thisBase->numParts())
  20965. {
  20966. thisKey = thisBase->queryPart(fileNo);
  20967. tlk->setKey(thisKey);
  20968. if (!thisKey->isTopLevelKey())
  20969. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20970. else
  20971. tlk->setLayoutTranslator(nullptr);
  20972. tlk->reset();
  20973. }
  20974. else
  20975. break;
  20976. }
  20977. tlk->releaseSegmentMonitors();
  20978. tlk->setKey(NULL);
  20979. }
  20980. }
  20981. }
  20982. }
  20983. remote.flush();
  20984. remote.senddone();
  20985. }
  20986. catch (IException *E)
  20987. {
  20988. remote.setException(E);
  20989. }
  20990. }
  20991. virtual void createSegmentMonitors(IKeyManager *key)
  20992. {
  20993. indexHelper.createSegmentMonitors(key);
  20994. key->finishSegmentMonitors();
  20995. }
  20996. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) = 0;
  20997. virtual void reset()
  20998. {
  20999. if (accepted)
  21000. noteStatistic(StNumIndexAccepted, accepted);
  21001. if (rejected)
  21002. noteStatistic(StNumIndexRejected, rejected);
  21003. remote.onReset();
  21004. CRoxieServerActivity::reset();
  21005. if (varFileInfo)
  21006. {
  21007. keySet.clear();
  21008. varFileInfo.clear();
  21009. }
  21010. variableInfoPending = false;
  21011. }
  21012. virtual void stop()
  21013. {
  21014. remote.onStop();
  21015. CRoxieServerActivity::stop();
  21016. }
  21017. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21018. {
  21019. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21020. }
  21021. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  21022. {
  21023. CRoxieServerActivity::gatherStats(merged);
  21024. remote.gatherStats(merged);
  21025. }
  21026. };
  21027. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  21028. {
  21029. protected:
  21030. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  21031. public:
  21032. CRoxieServerIndexReadBaseActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21033. bool _sorted, bool _isLocal, bool _maySkip)
  21034. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip)
  21035. {
  21036. }
  21037. virtual void reset()
  21038. {
  21039. remote.onReset();
  21040. CRoxieServerIndexActivity::reset();
  21041. }
  21042. virtual const void *nextRow()
  21043. {
  21044. ActivityTimer t(activityStats, timeActivities);
  21045. try
  21046. {
  21047. const void *ret = remote.nextRow();
  21048. if (ret)
  21049. processed++;
  21050. return ret;
  21051. }
  21052. catch (IException *E)
  21053. {
  21054. throw makeWrappedException(E);
  21055. }
  21056. }
  21057. protected:
  21058. virtual const void * createLimitFailRow(bool isKeyed)
  21059. {
  21060. ensureRowAllocator();
  21061. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21062. assertex(limitTransformExtra);
  21063. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  21064. if (outSize)
  21065. return rowBuilder.finalizeRowClear(outSize);
  21066. return NULL;
  21067. }
  21068. };
  21069. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  21070. {
  21071. protected:
  21072. IHThorIndexReadArg & readHelper;
  21073. ISteppingMeta *rawMeta = nullptr;
  21074. CSteppingMeta steppingMeta;
  21075. unsigned * seekSizes = nullptr;
  21076. bool optimizeSteppedPostFilter;
  21077. ISteppingMeta * projectedMeta = nullptr;
  21078. unsigned maxSeekLookahead;
  21079. public:
  21080. CRoxieServerIndexReadActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  21081. bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  21082. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  21083. readHelper((IHThorIndexReadArg &)basehelper)
  21084. {
  21085. limitTransformExtra = &readHelper;
  21086. rawMeta = readHelper.queryRawSteppingMeta();
  21087. unsigned flags = indexHelper.getFlags();
  21088. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21089. seekSizes = NULL;
  21090. maxSeekLookahead = _maxSeekLookahead;
  21091. if (rawMeta)
  21092. {
  21093. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21094. unsigned maxFields = rawMeta->getNumFields();
  21095. seekGEOffset = fields[0].offset;
  21096. seekSizes = new unsigned[maxFields];
  21097. seekSizes[0] = fields[0].size;
  21098. for (unsigned i=1; i < maxFields; i++)
  21099. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21100. projectedMeta = readHelper.queryProjectedSteppingMeta();
  21101. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  21102. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  21103. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21104. steppingMeta.init(useMeta, hasPostFilter);
  21105. }
  21106. }
  21107. ~CRoxieServerIndexReadActivity()
  21108. {
  21109. delete [] seekSizes;
  21110. }
  21111. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21112. {
  21113. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  21114. steppingMeta.setDistributed();
  21115. if (steppedExtra)
  21116. steppingMeta.setExtra(steppedExtra);
  21117. rowLimit = readHelper.getRowLimit();
  21118. keyedLimit = readHelper.getKeyedLimit();
  21119. choosenLimit = readHelper.getChooseNLimit();
  21120. if (!paused)
  21121. processAllKeys();
  21122. }
  21123. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  21124. {
  21125. public:
  21126. IMPLEMENT_IINTERFACE;
  21127. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  21128. {
  21129. Link();
  21130. return const_cast<LazyLocalKeyReader*> (this);
  21131. }
  21132. virtual const void *getMessageHeader(unsigned &length) const
  21133. {
  21134. length = 0;
  21135. return NULL;
  21136. }
  21137. virtual const void *getMessageMetadata(unsigned &length) const
  21138. {
  21139. length = 0;
  21140. return NULL;
  21141. }
  21142. virtual void discard() const
  21143. {
  21144. // nothing to do.
  21145. }
  21146. unsigned keyedCount;
  21147. unsigned matched;
  21148. bool EOFseen;
  21149. Owned<IKeyIndexSet> keySet;
  21150. Owned<IKeyManager> tlk;
  21151. CRoxieServerIndexReadActivity &owner;
  21152. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, const IDynamicTransform * trans)
  21153. : owner(_owner)
  21154. {
  21155. keyedCount = 0;
  21156. matched = 0;
  21157. EOFseen = false;
  21158. keySet.setown(createKeyIndexSet());
  21159. keySet->addIndex(LINK(key));
  21160. if (owner.seekGEOffset)
  21161. tlk.setown(createKeyMerger(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet, owner.seekGEOffset, &owner, owner.indexHelper.hasNewSegmentMonitors(), !owner.isBlind()));
  21162. else
  21163. tlk.setown(createLocalKeyManager(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet->queryPart(0), &owner, owner.indexHelper.hasNewSegmentMonitors(), !owner.isBlind()));
  21164. if (!key->isTopLevelKey())
  21165. tlk->setLayoutTranslator(trans);
  21166. owner.indexHelper.createSegmentMonitors(tlk);
  21167. tlk->finishSegmentMonitors();
  21168. tlk->reset();
  21169. }
  21170. virtual const void *getNext(int length)
  21171. {
  21172. TransformCallbackAssociation associate(owner.callback, tlk);
  21173. while (tlk->lookup(true))
  21174. {
  21175. keyedCount++;
  21176. if (keyedCount > owner.keyedLimit)
  21177. {
  21178. owner.onLimitExceeded(true); // Should throw exception
  21179. throwUnexpected();
  21180. }
  21181. size32_t transformedSize;
  21182. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  21183. byte const * keyRow = tlk->queryKeyBuffer();
  21184. if (likely(owner.readHelper.canMatch(keyRow)))
  21185. {
  21186. try
  21187. {
  21188. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  21189. owner.callback.finishedRow();
  21190. }
  21191. catch (IException *E)
  21192. {
  21193. throw owner.makeWrappedException(E);
  21194. }
  21195. if (transformedSize)
  21196. {
  21197. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  21198. matched++;
  21199. if (matched > owner.rowLimit)
  21200. {
  21201. owner.onLimitExceeded(false); // Should throw exception
  21202. throwUnexpected();
  21203. }
  21204. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  21205. {
  21206. break;
  21207. }
  21208. owner.accepted++;
  21209. return result.getClear();
  21210. }
  21211. else
  21212. owner.rejected++;
  21213. }
  21214. else
  21215. {
  21216. owner.callback.finishedRow(); // since filter might have accessed a blob
  21217. owner.rejected++;
  21218. }
  21219. }
  21220. EOFseen = true;
  21221. return NULL;
  21222. }
  21223. virtual bool atEOF() const
  21224. {
  21225. return EOFseen;
  21226. }
  21227. virtual bool isSerialized() const
  21228. {
  21229. return false;
  21230. }
  21231. };
  21232. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21233. {
  21234. ensureRowAllocator();
  21235. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  21236. return false;
  21237. }
  21238. virtual void onLimitExceeded(bool isKeyed)
  21239. {
  21240. if (traceLevel > 4)
  21241. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21242. if (isKeyed)
  21243. {
  21244. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21245. {
  21246. if (ctx->queryDebugContext())
  21247. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21248. throw makeLimitSkipException(true);
  21249. }
  21250. else
  21251. readHelper.onKeyedLimitExceeded();
  21252. }
  21253. else
  21254. {
  21255. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21256. {
  21257. if (ctx->queryDebugContext())
  21258. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21259. throw makeLimitSkipException(false);
  21260. }
  21261. else
  21262. readHelper.onLimitExceeded();
  21263. }
  21264. }
  21265. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  21266. {
  21267. out.append((unsigned short) numFields);
  21268. out.append((unsigned short) seekLen);
  21269. out.append((unsigned short) stepExtra.queryFlags());
  21270. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  21271. if (seeks)
  21272. {
  21273. unsigned lookahead = 40000/seekLen;
  21274. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  21275. lookahead = maxSeekLookahead;
  21276. seeks->ensureFilled(seek, numFields, lookahead);
  21277. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  21278. unsigned serialized = 1; // rawseek is always serialized...
  21279. unsigned patchLength = out.length();
  21280. out.append(serialized); // NOTE - we come back and patch with the actual value...
  21281. out.append(seekLen, rawSeek);
  21282. if (seeks->ordinality())
  21283. {
  21284. const void *lastSeek = rawSeek;
  21285. byte *nextSeek = NULL;
  21286. if (projectedMeta)
  21287. nextSeek = (byte *) alloca(seekLen);
  21288. for (unsigned i = 0; i < seeks->ordinality(); i++)
  21289. {
  21290. if (projectedMeta)
  21291. {
  21292. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  21293. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21294. }
  21295. else
  21296. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  21297. int diff = memcmp(nextSeek, lastSeek, seekLen);
  21298. if (diff > 0)
  21299. {
  21300. serialized++;
  21301. out.append(seekLen, nextSeek);
  21302. lastSeek = (const byte *) out.reserve(0) - seekLen;
  21303. }
  21304. }
  21305. unsigned length = out.length();
  21306. out.setWritePos(patchLength);
  21307. out.append(serialized);
  21308. out.setWritePos(length);
  21309. }
  21310. }
  21311. else
  21312. {
  21313. out.append(false);
  21314. out.append(1);
  21315. out.append(seekLen, rawSeek);
  21316. }
  21317. }
  21318. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21319. {
  21320. ActivityTimer t(activityStats, timeActivities);
  21321. try
  21322. {
  21323. unsigned seeklen = 0;
  21324. const void *rawSeek = NULL;
  21325. if (seek && numFields)
  21326. {
  21327. seeklen = seekSizes[numFields-1];
  21328. rawSeek = (const byte *)seek + seekGEOffset;
  21329. if (projectedMeta)
  21330. {
  21331. byte * temp = (byte *) alloca(seeklen);
  21332. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  21333. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21334. rawSeek = (byte *)temp;
  21335. }
  21336. }
  21337. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  21338. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  21339. processed++;
  21340. return ret;
  21341. }
  21342. catch (IException *E)
  21343. {
  21344. throw makeWrappedException(E);
  21345. }
  21346. }
  21347. virtual IInputSteppingMeta * querySteppingMeta()
  21348. {
  21349. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21350. return &steppingMeta;
  21351. return NULL;
  21352. }
  21353. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21354. {
  21355. if (variableInfoPending)
  21356. setVariableFileInfo();
  21357. return this;
  21358. }
  21359. virtual IKeyArray *getKeySet() const
  21360. {
  21361. return keySet.getLink();
  21362. }
  21363. virtual const IResolvedFile *getVarFileInfo() const
  21364. {
  21365. return varFileInfo.getLink();
  21366. }
  21367. virtual ITranslatorSet *getTranslators() const override
  21368. {
  21369. return translators.getLink();
  21370. }
  21371. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21372. {
  21373. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21374. }
  21375. virtual IRoxieServerActivity *queryActivity() { return this; }
  21376. virtual const RemoteActivityId& queryRemoteId() const
  21377. {
  21378. return remoteId;
  21379. }
  21380. };
  21381. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  21382. {
  21383. IHThorIndexReadArg & indexHelper;
  21384. IHThorSteppedSourceExtra * steppedExtra;
  21385. bool eof;
  21386. Linked<IKeyArray>keySet;
  21387. Owned<IKeyIndexSet>keyIndexSet;
  21388. Owned<IKeyManager> tlk;
  21389. Linked<ITranslatorSet> translators;
  21390. CIndexTransformCallback callback;
  21391. unsigned __int64 keyedLimit;
  21392. unsigned rowLimit;
  21393. unsigned chooseNLimit;
  21394. unsigned accepted;
  21395. unsigned rejected;
  21396. unsigned keyedCount;
  21397. ISteppingMeta * rawMeta;
  21398. ISteppingMeta * projectedMeta;
  21399. size32_t seekGEOffset;
  21400. unsigned * seekSizes;
  21401. CSteppingMeta steppingMeta;
  21402. Owned<const IResolvedFile> varFileInfo;
  21403. const RemoteActivityId &remoteId;
  21404. bool firstRead;
  21405. bool variableFileName;
  21406. bool variableInfoPending;
  21407. bool isOpt;
  21408. bool isLocal;
  21409. bool optimizeSteppedPostFilter;
  21410. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  21411. void initKeySet()
  21412. {
  21413. if (keySet->length() > 1 || rawMeta != NULL)
  21414. {
  21415. if (translators->isTranslatingKeyed())
  21416. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Keyed Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  21417. if (!translators->hasConsistentTranslation())
  21418. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Mixture of layout translation is not available when merging key parts or smart-stepping");
  21419. }
  21420. keyIndexSet.setown(createKeyIndexSet());
  21421. for (unsigned part = 0; part < keySet->length(); part++)
  21422. {
  21423. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  21424. if (kib)
  21425. {
  21426. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  21427. {
  21428. IKeyIndex *k = kib->queryPart(subpart);
  21429. if (k)
  21430. {
  21431. assertex(!k->isTopLevelKey());
  21432. keyIndexSet->addIndex(LINK(k));
  21433. }
  21434. }
  21435. }
  21436. }
  21437. }
  21438. void setVariableFileInfo()
  21439. {
  21440. OwnedRoxieString indexName(indexHelper.getFileName());
  21441. varFileInfo.setown(resolveLFNIndex(indexName, isOpt, defaultPrivilegedUser));
  21442. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  21443. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  21444. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  21445. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  21446. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), FileFormatMode::index, factory->queryQueryFactory().queryQueryName()));
  21447. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  21448. initKeySet();
  21449. variableInfoPending = false;
  21450. }
  21451. void onEOF()
  21452. {
  21453. callback.setManager(NULL);
  21454. eof = true;
  21455. tlk.clear();
  21456. }
  21457. public:
  21458. CRoxieServerSimpleIndexReadActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21459. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21460. indexHelper((IHThorIndexReadArg &)basehelper),
  21461. keySet(_factory->keySet),
  21462. translators(_factory->translators),
  21463. remoteId(_remoteId),
  21464. isLocal(_isLocal)
  21465. {
  21466. rowLimit = 0;
  21467. keyedLimit = 0;
  21468. chooseNLimit = 0;
  21469. indexHelper.setCallback(&callback);
  21470. steppedExtra = indexHelper.querySteppingExtra();
  21471. unsigned flags = indexHelper.getFlags();
  21472. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21473. variableInfoPending = false;
  21474. isOpt = (flags & TIRoptional) != 0;
  21475. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21476. firstRead = true;
  21477. accepted = 0;
  21478. rejected = 0;
  21479. keyedCount = 0;
  21480. eof = false;
  21481. rawMeta = indexHelper.queryRawSteppingMeta();
  21482. projectedMeta = indexHelper.queryProjectedSteppingMeta();
  21483. seekGEOffset = 0;
  21484. seekSizes = NULL;
  21485. if (rawMeta)
  21486. {
  21487. // MORE - should check all keys in maxFields list can actually be keyed.
  21488. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21489. unsigned maxFields = rawMeta->getNumFields();
  21490. seekGEOffset = fields[0].offset;
  21491. seekSizes = new unsigned[maxFields];
  21492. seekSizes[0] = fields[0].size;
  21493. for (unsigned i=1; i < maxFields; i++)
  21494. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21495. bool hasPostFilter = indexHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21496. if (projectedMeta)
  21497. steppingMeta.init(projectedMeta, hasPostFilter);
  21498. else
  21499. steppingMeta.init(rawMeta, hasPostFilter);
  21500. }
  21501. }
  21502. virtual const IResolvedFile *queryVarFileInfo() const
  21503. {
  21504. return varFileInfo;
  21505. }
  21506. ~CRoxieServerSimpleIndexReadActivity()
  21507. {
  21508. delete [] seekSizes;
  21509. }
  21510. virtual bool needsAllocator() const { return true; }
  21511. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21512. {
  21513. firstRead = true;
  21514. accepted = 0;
  21515. rejected = 0;
  21516. keyedCount = 0;
  21517. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21518. if (steppedExtra)
  21519. steppingMeta.setExtra(steppedExtra);
  21520. eof = !indexHelper.canMatchAny();
  21521. if (variableFileName)
  21522. variableInfoPending = true;
  21523. else
  21524. {
  21525. variableInfoPending = false;
  21526. if (!keyIndexSet)
  21527. initKeySet();
  21528. }
  21529. }
  21530. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21531. {
  21532. if (variableInfoPending)
  21533. setVariableFileInfo();
  21534. return this;
  21535. }
  21536. virtual IKeyArray *getKeySet() const
  21537. {
  21538. return keySet.getLink();
  21539. }
  21540. virtual const IResolvedFile *getVarFileInfo() const
  21541. {
  21542. return varFileInfo.getLink();
  21543. }
  21544. virtual ITranslatorSet *getTranslators() const override
  21545. {
  21546. return translators.getLink();
  21547. }
  21548. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21549. {
  21550. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21551. }
  21552. virtual IRoxieServerActivity *queryActivity() { return this; }
  21553. virtual const RemoteActivityId& queryRemoteId() const
  21554. {
  21555. return remoteId;
  21556. }
  21557. const void *nextRow()
  21558. {
  21559. bool matched = true;
  21560. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21561. }
  21562. unsigned __int64 checkCount(unsigned __int64 limit)
  21563. {
  21564. unsigned numParts = keyIndexSet->numParts();
  21565. unsigned __int64 result = 0;
  21566. for (unsigned i = 0; i < numParts; i++)
  21567. {
  21568. Owned<IKeyManager> countTlk = createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(i), this, indexHelper.hasNewSegmentMonitors(), !isBlind());
  21569. countTlk->setLayoutTranslator(translators->queryTranslator(i));
  21570. indexHelper.createSegmentMonitors(countTlk);
  21571. countTlk->finishSegmentMonitors();
  21572. result += countTlk->checkCount(limit-result);
  21573. if (result > limit)
  21574. break;
  21575. }
  21576. return result;
  21577. }
  21578. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21579. {
  21580. ActivityTimer t(activityStats, timeActivities);
  21581. if (eof)
  21582. return NULL;
  21583. if (firstRead)
  21584. {
  21585. if (variableInfoPending)
  21586. setVariableFileInfo();
  21587. rowLimit = (unsigned) indexHelper.getRowLimit();
  21588. chooseNLimit = (unsigned) indexHelper.getChooseNLimit();
  21589. unsigned numParts = keyIndexSet->numParts();
  21590. if (!numParts)
  21591. {
  21592. onEOF();
  21593. return NULL;
  21594. }
  21595. if (numParts > 1 || seekGEOffset)
  21596. {
  21597. tlk.setown(createKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet, seekGEOffset, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  21598. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21599. }
  21600. else
  21601. {
  21602. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(0), this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  21603. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21604. }
  21605. indexHelper.createSegmentMonitors(tlk);
  21606. tlk->finishSegmentMonitors();
  21607. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21608. {
  21609. StringBuffer out;
  21610. tlk->describeFilter(out);
  21611. CTXLOG("Using filter %s", out.str());
  21612. if (ctx->queryProbeManager())
  21613. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21614. }
  21615. tlk->reset();
  21616. callback.setManager(tlk);
  21617. keyedLimit = indexHelper.getKeyedLimit();
  21618. if (keyedLimit != (unsigned __int64) -1)
  21619. {
  21620. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21621. {
  21622. unsigned __int64 count = checkCount(keyedLimit);
  21623. if (count > keyedLimit)
  21624. {
  21625. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21626. indexHelper.onKeyedLimitExceeded();
  21627. const void * ret = NULL;
  21628. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21629. ret = createKeyedLimitOnFailRow();
  21630. onEOF();
  21631. return ret;
  21632. }
  21633. keyedLimit = (unsigned __int64) -1;
  21634. }
  21635. }
  21636. firstRead = false;
  21637. }
  21638. if (accepted == chooseNLimit)
  21639. {
  21640. onEOF();
  21641. return NULL;
  21642. }
  21643. const byte * rawSeek = NULL;
  21644. unsigned seekSize = 0;
  21645. if (seek)
  21646. {
  21647. seekSize = seekSizes[numFields-1];
  21648. rawSeek = (const byte *)seek + seekGEOffset;
  21649. if (projectedMeta)
  21650. {
  21651. byte *temp = (byte *) alloca(seekSize);
  21652. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21653. indexHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21654. rawSeek = (byte *)temp;
  21655. }
  21656. #ifdef _DEBUG
  21657. // StringBuffer seekStr;
  21658. // for (unsigned i = 0; i < seekSize; i++)
  21659. // {
  21660. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21661. // }
  21662. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21663. #endif
  21664. }
  21665. const byte * originalRawSeek = rawSeek;
  21666. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21667. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21668. {
  21669. checkAbort();
  21670. keyedCount++;
  21671. if (keyedCount > keyedLimit)
  21672. {
  21673. indexHelper.onKeyedLimitExceeded();
  21674. break;
  21675. }
  21676. byte const * keyRow = tlk->queryKeyBuffer();
  21677. if (likely(indexHelper.canMatch(keyRow)))
  21678. {
  21679. #ifdef _DEBUG
  21680. // StringBuffer recstr;
  21681. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21682. // for (unsigned i = 0; i < size; i++)
  21683. // {
  21684. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21685. // }
  21686. // DBGLOG("nextRowGE Got %s", recstr.str());
  21687. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21688. assertex(!"smart seek failure");
  21689. #endif
  21690. size32_t transformedSize;
  21691. rowBuilder.ensureRow();
  21692. try
  21693. {
  21694. transformedSize =indexHelper.transform(rowBuilder, keyRow);
  21695. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21696. //then return a mismatch record - so the join code can start seeking on the other input.
  21697. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21698. {
  21699. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21700. {
  21701. transformedSize = indexHelper.unfilteredTransform(rowBuilder, keyRow);
  21702. if (transformedSize != 0)
  21703. wasCompleteMatch = false;
  21704. }
  21705. }
  21706. callback.finishedRow();
  21707. }
  21708. catch (IException *E)
  21709. {
  21710. throw makeWrappedException(E);
  21711. }
  21712. if (transformedSize)
  21713. {
  21714. accepted++;
  21715. if (accepted > rowLimit)
  21716. {
  21717. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21718. {
  21719. throwUnexpected(); // should not have used simple variant if maySkip set...
  21720. }
  21721. if (traceLevel > 4)
  21722. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21723. indexHelper.onLimitExceeded();
  21724. break;
  21725. }
  21726. processed++;
  21727. #ifdef _DEBUG
  21728. // const byte *ret = (const byte *) out.get();
  21729. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21730. // queryOutputMeta()->toXML(ret, xmlwrite);
  21731. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21732. #endif
  21733. return rowBuilder.finalizeRowClear(transformedSize);
  21734. }
  21735. else
  21736. rejected++;
  21737. }
  21738. else
  21739. {
  21740. callback.finishedRow(); // since filter might have accessed a blob
  21741. rejected++;
  21742. }
  21743. rawSeek = NULL;
  21744. }
  21745. onEOF();
  21746. return NULL;
  21747. }
  21748. virtual void reset()
  21749. {
  21750. onEOF();
  21751. if (accepted)
  21752. noteStatistic(StNumIndexAccepted, accepted);
  21753. if (rejected)
  21754. noteStatistic(StNumIndexRejected, rejected);
  21755. if (variableFileName)
  21756. {
  21757. varFileInfo.clear();
  21758. translators.clear();
  21759. }
  21760. variableInfoPending = false;
  21761. CRoxieServerActivity::reset();
  21762. }
  21763. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21764. {
  21765. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21766. }
  21767. virtual IInputSteppingMeta * querySteppingMeta()
  21768. {
  21769. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21770. return &steppingMeta;
  21771. return NULL;
  21772. }
  21773. protected:
  21774. const void * createKeyedLimitOnFailRow()
  21775. {
  21776. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21777. size32_t outSize = indexHelper.transformOnKeyedLimitExceeded(rowBuilder);
  21778. if (outSize)
  21779. return rowBuilder.finalizeRowClear(outSize);
  21780. return NULL;
  21781. }
  21782. };
  21783. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21784. {
  21785. public:
  21786. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21787. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21788. {
  21789. }
  21790. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  21791. {
  21792. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21793. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21794. else if (isSimple && !maySkip)
  21795. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21796. else
  21797. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip, maxSeekLookahead);
  21798. }
  21799. };
  21800. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21801. {
  21802. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21803. }
  21804. //--------------------------------------------------------------------------------------------------------------------------
  21805. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21806. {
  21807. bool done;
  21808. public:
  21809. CRoxieServerNullCountActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21810. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21811. {
  21812. done = false;
  21813. }
  21814. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21815. {
  21816. done = false;
  21817. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21818. }
  21819. virtual bool needsAllocator() const { return true; }
  21820. virtual const void *nextRow()
  21821. {
  21822. ActivityTimer t(activityStats, timeActivities);
  21823. if (done) return NULL;
  21824. done = true;
  21825. size32_t rowSize = meta.getFixedSize();
  21826. void * nullRow = rowAllocator->createRow();
  21827. if (rowSize == 1)
  21828. *(byte *)nullRow = 0;
  21829. else
  21830. {
  21831. assertex(rowSize == sizeof(unsigned __int64));
  21832. *(unsigned __int64 *)nullRow = 0;
  21833. }
  21834. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21835. }
  21836. };
  21837. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21838. {
  21839. IHThorIndexCountArg & countHelper;
  21840. bool done;
  21841. public:
  21842. CRoxieServerIndexCountActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21843. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21844. countHelper((IHThorIndexCountArg &)basehelper),
  21845. done(false)
  21846. {
  21847. }
  21848. virtual bool needsAllocator() const { return true; }
  21849. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21850. {
  21851. done = false;
  21852. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21853. choosenLimit = countHelper.getChooseNLimit();
  21854. rowLimit = countHelper.getRowLimit();
  21855. keyedLimit = countHelper.getKeyedLimit();
  21856. if (!paused)
  21857. processAllKeys();
  21858. }
  21859. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21860. {
  21861. unsigned __int64 count = 0;
  21862. if (countHelper.hasFilter())
  21863. {
  21864. while (tlk->lookup(true))
  21865. {
  21866. try
  21867. {
  21868. count += countHelper.numValid(tlk->queryKeyBuffer());
  21869. callback.finishedRow();
  21870. }
  21871. catch (IException *E)
  21872. {
  21873. throw makeWrappedException(E);
  21874. }
  21875. accepted++;
  21876. if (count >= choosenLimit) // MORE - what about limit?
  21877. break;
  21878. }
  21879. }
  21880. else
  21881. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21882. if (count)
  21883. {
  21884. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  21885. if (count > choosenLimit)
  21886. count = choosenLimit;
  21887. void * recBuffer = rowAllocator->createRow();
  21888. if (meta.getFixedSize() == 1)
  21889. *(byte *)recBuffer = (byte)count;
  21890. else
  21891. {
  21892. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21893. *(unsigned __int64 *)recBuffer = count;
  21894. }
  21895. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21896. result->append(recBuffer);
  21897. remote.injectResult(result.getClear());
  21898. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21899. if (count >= choosenLimit)
  21900. return true;
  21901. }
  21902. return false;
  21903. }
  21904. virtual void onLimitExceeded(bool isKeyed)
  21905. {
  21906. if (traceLevel > 4)
  21907. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21908. if (isKeyed)
  21909. {
  21910. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21911. {
  21912. if (ctx->queryDebugContext())
  21913. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21914. throw makeLimitSkipException(true);
  21915. }
  21916. else
  21917. {
  21918. countHelper.onKeyedLimitExceeded();
  21919. }
  21920. }
  21921. else
  21922. {
  21923. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21924. {
  21925. if (ctx->queryDebugContext())
  21926. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21927. throw makeLimitSkipException(false);
  21928. }
  21929. else
  21930. {
  21931. countHelper.onLimitExceeded();
  21932. }
  21933. }
  21934. }
  21935. virtual const void *createLimitFailRow(bool isKeyed)
  21936. {
  21937. throwUnexpected();
  21938. }
  21939. virtual const void *nextRow()
  21940. {
  21941. ActivityTimer t(activityStats, timeActivities);
  21942. if (done) return NULL;
  21943. done = true;
  21944. unsigned __int64 totalCount = 0;
  21945. // Checking keyed limit on server is a bit odd - we only know the counts after postfiltering by the time we are on the server
  21946. // The count needs to behave the same as the output, which will regard a keyed limit as exceeded if the sum of the postfiltered outputs exceeds the keyed limit
  21947. bool hasKeyedLimit = (keyedLimit != (unsigned __int64) -1);
  21948. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21949. try
  21950. {
  21951. for (;;)
  21952. {
  21953. const void * next = remote.nextRow();
  21954. if (!next)
  21955. break;
  21956. if (meta.getFixedSize() == 1)
  21957. totalCount += *(byte *)next;
  21958. else
  21959. totalCount += *(unsigned __int64 *) next;
  21960. ReleaseRoxieRow(next);
  21961. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit && !hasKeyedLimit)) // can't break out early if there is a possibility of later agent throwing limit exception
  21962. break;
  21963. }
  21964. if (totalCount > rowLimit)
  21965. {
  21966. unsigned flags = indexHelper.getFlags();
  21967. if (flags & TIRlimitskips)
  21968. totalCount = 0;
  21969. else if (flags & TIRlimitcreates)
  21970. totalCount = 1;
  21971. else
  21972. countHelper.onLimitExceeded();
  21973. }
  21974. else if (totalCount > keyedLimit)
  21975. {
  21976. unsigned flags = indexHelper.getFlags();
  21977. if (flags & TIRkeyedlimitskips)
  21978. totalCount = 0;
  21979. else if (flags & TIRkeyedlimitcreates)
  21980. totalCount = 1;
  21981. else
  21982. countHelper.onLimitExceeded();
  21983. }
  21984. else if (totalCount > choosenLimit)
  21985. totalCount = choosenLimit;
  21986. }
  21987. catch (IException *E)
  21988. {
  21989. if (QUERYINTERFACE(E, LimitSkipException))
  21990. {
  21991. totalCount = 0;
  21992. unsigned flags = indexHelper.getFlags();
  21993. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21994. {
  21995. if (flags & TIRkeyedlimitcreates)
  21996. totalCount++;
  21997. }
  21998. else
  21999. {
  22000. if (flags & TIRlimitcreates)
  22001. totalCount++;
  22002. }
  22003. if (totalCount > choosenLimit)
  22004. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  22005. E->Release();
  22006. }
  22007. else
  22008. throw ;
  22009. }
  22010. processed++;
  22011. void * result = rowAllocator->createRow();
  22012. if (meta.getFixedSize() == 1)
  22013. *(byte *)result = (byte)totalCount;
  22014. else
  22015. {
  22016. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  22017. *(unsigned __int64 *)result = totalCount;
  22018. }
  22019. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  22020. }
  22021. };
  22022. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22023. {
  22024. public:
  22025. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22026. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22027. {
  22028. }
  22029. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  22030. {
  22031. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22032. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  22033. // else if (isSimple)
  22034. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22035. else
  22036. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22037. }
  22038. };
  22039. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22040. {
  22041. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22042. }
  22043. //--------------------------------------------------------------------------------------------------------------------------
  22044. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  22045. {
  22046. IHThorIndexAggregateArg &aggregateHelper;
  22047. bool done;
  22048. public:
  22049. CRoxieServerNullIndexAggregateActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22050. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22051. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  22052. {
  22053. done = false;
  22054. }
  22055. virtual bool needsAllocator() const { return true; }
  22056. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22057. {
  22058. done = false;
  22059. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22060. }
  22061. virtual const void *nextRow()
  22062. {
  22063. ActivityTimer t(activityStats, timeActivities);
  22064. if (done) return NULL;
  22065. done = true;
  22066. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  22067. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  22068. return rowBuilder.finalizeRowClear(thisSize);
  22069. }
  22070. };
  22071. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  22072. {
  22073. IHThorCompoundAggregateExtra & aggregateHelper;
  22074. bool done;
  22075. public:
  22076. CRoxieServerIndexAggregateActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  22077. const RemoteActivityId &_remoteId, bool _isLocal)
  22078. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  22079. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  22080. done(false)
  22081. {
  22082. }
  22083. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22084. {
  22085. done = false;
  22086. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  22087. if (!paused)
  22088. processAllKeys();
  22089. }
  22090. virtual bool needsAllocator() const { return true; }
  22091. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22092. {
  22093. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22094. while (tlk->lookup(true))
  22095. {
  22096. if (!rowBuilder.exists())
  22097. {
  22098. rowBuilder.ensureRow();
  22099. aggregateHelper.clearAggregate(rowBuilder);
  22100. }
  22101. try
  22102. {
  22103. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer());
  22104. callback.finishedRow();
  22105. }
  22106. catch (IException *E)
  22107. {
  22108. throw makeWrappedException(E);
  22109. }
  22110. accepted++;
  22111. }
  22112. if (aggregateHelper.processedAnyRows())
  22113. {
  22114. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  22115. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  22116. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  22117. result->append(recBuffer);
  22118. remote.injectResult(result.getClear());
  22119. }
  22120. return false;
  22121. }
  22122. virtual void onLimitExceeded(bool isKeyed)
  22123. {
  22124. if (traceLevel > 4)
  22125. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22126. throwUnexpected();
  22127. }
  22128. virtual const void *createLimitFailRow(bool isKeyed)
  22129. {
  22130. throwUnexpected();
  22131. }
  22132. const void * gatherMerged()
  22133. {
  22134. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22135. const void * firstRow = remote.nextRow();
  22136. size32_t finalSize = 0;
  22137. if (!firstRow)
  22138. {
  22139. rowBuilder.ensureRow();
  22140. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  22141. }
  22142. else
  22143. {
  22144. // NOTE need to clone this because going to modify below, could special case 1 row only
  22145. finalSize = cloneRow(rowBuilder, firstRow, meta);
  22146. ReleaseRoxieRow(firstRow);
  22147. }
  22148. for (;;)
  22149. {
  22150. const void * next = remote.nextRow();
  22151. if (!next)
  22152. break;
  22153. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  22154. ReleaseRoxieRow(next);
  22155. }
  22156. return rowBuilder.finalizeRowClear(finalSize);
  22157. }
  22158. virtual const void *nextRow()
  22159. {
  22160. ActivityTimer t(activityStats, timeActivities);
  22161. if (done) return NULL;
  22162. const void * ret = gatherMerged();
  22163. processed++;
  22164. done = true;
  22165. return ret;
  22166. }
  22167. };
  22168. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22169. {
  22170. public:
  22171. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22172. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22173. {
  22174. }
  22175. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  22176. {
  22177. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22178. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  22179. // else if (isSimple)
  22180. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22181. else
  22182. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22183. }
  22184. };
  22185. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22186. {
  22187. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22188. }
  22189. //--------------------------------------------------------------------------------------------------------------------------
  22190. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  22191. {
  22192. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  22193. RowAggregator singleAggregator;
  22194. RowAggregator resultAggregator;
  22195. unsigned groupSegCount;
  22196. bool gathered;
  22197. bool eof;
  22198. public:
  22199. CRoxieServerIndexGroupAggregateActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  22200. const RemoteActivityId &_remoteId, bool _isLocal)
  22201. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  22202. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  22203. singleAggregator(aggregateHelper, aggregateHelper),
  22204. resultAggregator(aggregateHelper, aggregateHelper),
  22205. gathered(false), eof(true)
  22206. {
  22207. groupSegCount = 0;
  22208. }
  22209. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  22210. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22211. {
  22212. eof = false;
  22213. gathered= false;
  22214. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  22215. groupSegCount = 0;
  22216. if (!paused)
  22217. processAllKeys();
  22218. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  22219. }
  22220. virtual bool needsAllocator() const { return true; }
  22221. virtual void reset()
  22222. {
  22223. resultAggregator.reset();
  22224. CRoxieServerIndexActivity::reset();
  22225. }
  22226. virtual void processRow(const void * next)
  22227. {
  22228. singleAggregator.addRow(next);
  22229. }
  22230. virtual void createSegmentMonitors(IKeyManager *key)
  22231. {
  22232. ThorActivityKind kind = factory->getKind();
  22233. CRoxieServerIndexActivity::createSegmentMonitors(key);
  22234. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  22235. groupSegCount = aggregateHelper.getGroupingMaxField();
  22236. else
  22237. groupSegCount = 0;
  22238. }
  22239. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22240. {
  22241. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  22242. singleAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  22243. ThorActivityKind kind = factory->getKind();
  22244. while (tlk->lookup(true))
  22245. {
  22246. try
  22247. {
  22248. if (groupSegCount && !trans)
  22249. {
  22250. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer());
  22251. callback.finishedRow();
  22252. if (kind==TAKindexgroupcount)
  22253. {
  22254. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  22255. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  22256. }
  22257. if (!tlk->nextRange(groupSegCount))
  22258. break;
  22259. }
  22260. else
  22261. {
  22262. aggregateHelper.processRow(tlk->queryKeyBuffer(), this);
  22263. callback.finishedRow();
  22264. }
  22265. }
  22266. catch (IException *E)
  22267. {
  22268. throw makeWrappedException(E);
  22269. }
  22270. accepted++;
  22271. }
  22272. for (;;)
  22273. {
  22274. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  22275. if (!next)
  22276. break;
  22277. result->append(next->finalizeRowClear());
  22278. }
  22279. remote.injectResult(result.getClear());
  22280. singleAggregator.reset();
  22281. return false;
  22282. }
  22283. virtual void onLimitExceeded(bool isKeyed)
  22284. {
  22285. if (traceLevel > 4)
  22286. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22287. throwUnexpected();
  22288. }
  22289. virtual const void *createLimitFailRow(bool isKeyed)
  22290. {
  22291. throwUnexpected();
  22292. }
  22293. void gatherMerged()
  22294. {
  22295. gathered = true;
  22296. for (;;)
  22297. {
  22298. const void * next = remote.nextRow();
  22299. if (!next)
  22300. break;
  22301. resultAggregator.mergeElement(next);
  22302. ReleaseRoxieRow(next);
  22303. }
  22304. }
  22305. virtual const void *nextRow()
  22306. {
  22307. ActivityTimer t(activityStats, timeActivities);
  22308. if (eof)
  22309. return NULL;
  22310. if (!gathered)
  22311. gatherMerged();
  22312. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  22313. if (next)
  22314. {
  22315. processed++;
  22316. return next->finalizeRowClear();
  22317. }
  22318. eof = true;
  22319. return NULL;
  22320. }
  22321. };
  22322. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22323. {
  22324. public:
  22325. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22326. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22327. {
  22328. }
  22329. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  22330. {
  22331. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22332. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22333. // else if (isSimple)
  22334. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22335. else
  22336. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22337. }
  22338. };
  22339. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22340. {
  22341. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22342. }
  22343. //--------------------------------------------------------------------------------------------------------------------------
  22344. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  22345. {
  22346. IHThorIndexNormalizeArg & readHelper;
  22347. public:
  22348. CRoxieServerIndexNormalizeActivity(IRoxieAgentContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  22349. bool _sorted, bool _isLocal, bool _maySkip)
  22350. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  22351. readHelper((IHThorIndexNormalizeArg &)basehelper)
  22352. {
  22353. limitTransformExtra = &readHelper;
  22354. }
  22355. virtual bool needsAllocator() const { return true; }
  22356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22357. {
  22358. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  22359. rowLimit = readHelper.getRowLimit();
  22360. keyedLimit = readHelper.getKeyedLimit();
  22361. choosenLimit = readHelper.getChooseNLimit();
  22362. if (!paused)
  22363. processAllKeys();
  22364. }
  22365. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22366. {
  22367. unsigned keyedCount = 0;
  22368. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22369. while (tlk->lookup(true))
  22370. {
  22371. keyedCount++;
  22372. if (keyedCount > keyedLimit)
  22373. {
  22374. if (traceLevel > 4)
  22375. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22376. onLimitExceeded(true);
  22377. break;
  22378. }
  22379. size32_t transformedSize;
  22380. if (readHelper.first(tlk->queryKeyBuffer()))
  22381. {
  22382. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  22383. do
  22384. {
  22385. if (accepted>=choosenLimit)
  22386. break;
  22387. rowBuilder.ensureRow();
  22388. try
  22389. {
  22390. transformedSize = readHelper.transform(rowBuilder);
  22391. }
  22392. catch (IException *E)
  22393. {
  22394. throw makeWrappedException(E);
  22395. }
  22396. if (transformedSize)
  22397. {
  22398. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22399. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22400. accepted++;
  22401. }
  22402. else
  22403. rejected++;
  22404. } while (readHelper.next());
  22405. remote.injectResult(result.getClear());
  22406. callback.finishedRow();
  22407. if (accepted>=choosenLimit)
  22408. return true;
  22409. }
  22410. }
  22411. return false;
  22412. }
  22413. virtual void onLimitExceeded(bool isKeyed)
  22414. {
  22415. if (traceLevel > 4)
  22416. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22417. if (isKeyed)
  22418. {
  22419. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22420. {
  22421. if (ctx->queryDebugContext())
  22422. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22423. throw makeLimitSkipException(true);
  22424. }
  22425. else
  22426. readHelper.onKeyedLimitExceeded();
  22427. }
  22428. else
  22429. {
  22430. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  22431. {
  22432. if (ctx->queryDebugContext())
  22433. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22434. throw makeLimitSkipException(false);
  22435. }
  22436. else
  22437. readHelper.onLimitExceeded();
  22438. }
  22439. }
  22440. };
  22441. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22442. {
  22443. public:
  22444. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22445. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22446. {
  22447. }
  22448. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  22449. {
  22450. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22451. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22452. else
  22453. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip);
  22454. }
  22455. };
  22456. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22457. {
  22458. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22459. }
  22460. //=================================================================================
  22461. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22462. {
  22463. IHThorFetchBaseArg &helper;
  22464. Linked<IFilePartMap> map;
  22465. CRemoteResultAdaptor remote;
  22466. RecordPullerThread puller;
  22467. bool needsRHS;
  22468. bool variableFileName;
  22469. bool isOpt;
  22470. Owned<const IResolvedFile> varFileInfo;
  22471. Owned<IEngineRowAllocator> extractAllocator;
  22472. public:
  22473. CRoxieServerFetchActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22474. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22475. {
  22476. needsRHS = helper.transformNeedsRhs();
  22477. if (needsRHS)
  22478. extractAllocator.setown(createRowAllocator(helper.queryExtractedSize()));
  22479. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22480. isOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22481. }
  22482. virtual const IResolvedFile *queryVarFileInfo() const
  22483. {
  22484. return varFileInfo;
  22485. }
  22486. virtual void onCreate(IHThorArg *_colocalParent)
  22487. {
  22488. CRoxieServerActivity::onCreate(_colocalParent);
  22489. remote.onCreate(_colocalParent);
  22490. }
  22491. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22492. {
  22493. if (idx)
  22494. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22495. puller.setInput(this, _sourceIdx, _in);
  22496. }
  22497. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22498. {
  22499. puller.connectInputStreams(ctx, consumerOrdered);
  22500. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22501. }
  22502. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22503. {
  22504. if (idx==0)
  22505. return puller.queryInput();
  22506. else
  22507. return NULL;
  22508. }
  22509. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22510. {
  22511. CRoxieServerActivity::gatherStats(merged);
  22512. remote.gatherStats(merged);
  22513. }
  22514. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22515. {
  22516. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22517. remote.onStart(parentExtractSize, parentExtract);
  22518. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22519. if (variableFileName)
  22520. {
  22521. OwnedRoxieString fname(helper.getFileName());
  22522. varFileInfo.setown(resolveLFNFlat(fname, isOpt, defaultPrivilegedUser));
  22523. if (varFileInfo)
  22524. map.setown(varFileInfo->getFileMap());
  22525. }
  22526. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22527. }
  22528. virtual void stop()
  22529. {
  22530. // Called from remote, so no need to call back to it....
  22531. puller.stop();
  22532. CRoxieServerActivity::stop();
  22533. }
  22534. virtual void reset()
  22535. {
  22536. processed = remote.processed;
  22537. remote.processed = 0;
  22538. puller.reset();
  22539. if (variableFileName)
  22540. {
  22541. varFileInfo.clear();
  22542. map.clear();
  22543. }
  22544. CRoxieServerActivity::reset();
  22545. }
  22546. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22547. {
  22548. if (idx==(unsigned)-1)
  22549. idx = 0;
  22550. return idx ? NULL : &remote;
  22551. }
  22552. virtual void processRow(const void *row)
  22553. {
  22554. // called from puller thread
  22555. offset_t rp = helper.extractPosition(row);
  22556. unsigned partNo;
  22557. if (isLocalFpos(rp))
  22558. partNo = getLocalFposPart(rp) + 1;
  22559. else
  22560. partNo = map->mapOffset(rp);
  22561. if (needsRHS)
  22562. {
  22563. RtlDynamicRowBuilder rb(extractAllocator, true);
  22564. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22565. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22566. *(offset_t *) block = rp;
  22567. block += sizeof(rp);
  22568. *(unsigned *) block = rhsSize;
  22569. block += sizeof(rhsSize);
  22570. memcpy(block, rb.row(), rhsSize);
  22571. }
  22572. else
  22573. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22574. ReleaseRoxieRow(row);
  22575. }
  22576. void processEOG()
  22577. {
  22578. #ifdef FETCH_PRESERVES_GROUPING
  22579. UNIMPLEMENTED;
  22580. #endif
  22581. // else discard is correct
  22582. }
  22583. void processGroup(const ConstPointerArray &)
  22584. {
  22585. throwUnexpected();
  22586. }
  22587. void processDone()
  22588. {
  22589. // called from puller thread
  22590. remote.flush();
  22591. remote.senddone();
  22592. }
  22593. virtual bool fireException(IException *e)
  22594. {
  22595. return remote.fireException(e);
  22596. }
  22597. virtual void onLimitExceeded(bool isKeyed)
  22598. {
  22599. if (traceLevel > 4)
  22600. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22601. if (isKeyed)
  22602. throwUnexpected();
  22603. helper.onLimitExceeded();
  22604. }
  22605. virtual const void *createLimitFailRow(bool isKeyed)
  22606. {
  22607. UNIMPLEMENTED;
  22608. }
  22609. virtual const void *nextRow()
  22610. {
  22611. throwUnexpected(); // I am nobody's input
  22612. }
  22613. };
  22614. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22615. {
  22616. RemoteActivityId remoteId;
  22617. Owned<IFilePartMap> map;
  22618. bool variableFileName;
  22619. Owned<const IResolvedFile> datafile;
  22620. public:
  22621. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22622. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22623. {
  22624. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22625. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22626. if (!variableFileName)
  22627. {
  22628. OwnedRoxieString fname(helper->getFileName());
  22629. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22630. (helper->getFetchFlags() & FFdatafileoptional) != 0,
  22631. true, true,
  22632. _queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  22633. if (datafile)
  22634. map.setown(datafile->getFileMap());
  22635. }
  22636. }
  22637. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  22638. {
  22639. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22640. }
  22641. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22642. {
  22643. if (datafile)
  22644. addXrefFileInfo(reply, datafile);
  22645. else
  22646. {
  22647. // Temporarily resolve the file
  22648. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22649. if ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22650. {
  22651. OwnedRoxieString fileName(helper->getFileName());
  22652. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true, isActivityCodeSigned());
  22653. if (temp)
  22654. addXrefFileInfo(reply, temp);
  22655. }
  22656. }
  22657. }
  22658. virtual const StatisticsMapping &queryStatsMapping() const
  22659. {
  22660. return diskStatistics;
  22661. }
  22662. };
  22663. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22664. {
  22665. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22666. }
  22667. // MORE - is there any point keeping this now?
  22668. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22669. {
  22670. public:
  22671. Owned<const IResolvedFile> indexfile;
  22672. Owned<const IResolvedFile> datafile;
  22673. StringAttr fileName;
  22674. StringAttr indexName;
  22675. Owned<IKeyArray> keySet;
  22676. Owned<IFileIOArray> files;
  22677. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22678. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22679. {
  22680. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22681. {
  22682. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22683. return; // ignore 'spills'
  22684. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22685. ThorActivityKind kind = getActivityKind(_graphNode);
  22686. if (kind != TAKdiskwrite && kind != TAKspillwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22687. {
  22688. fileName.set(queryNodeFileName(_graphNode, kind));
  22689. indexName.set(queryNodeIndexName(_graphNode, kind));
  22690. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22691. {
  22692. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22693. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  22694. if (indexfile)
  22695. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  22696. }
  22697. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22698. {
  22699. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22700. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  22701. if (datafile)
  22702. {
  22703. if (isLocal)
  22704. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22705. }
  22706. }
  22707. }
  22708. }
  22709. catch(IException *E)
  22710. {
  22711. StringBuffer errors;
  22712. E->errorMessage(errors);
  22713. OERRLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22714. E->Release();
  22715. }
  22716. }
  22717. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), sanitizeSourceFile(__FILE__), __LINE__); }
  22718. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22719. {
  22720. if (!allFilesDynamic)
  22721. {
  22722. if (datafile)
  22723. addXrefFileInfo(reply, datafile);
  22724. if (indexfile)
  22725. addXrefFileInfo(reply, indexfile);
  22726. }
  22727. else
  22728. {
  22729. Owned<const IResolvedFile> temp;
  22730. if (fileName.length())
  22731. {
  22732. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  22733. if (temp)
  22734. addXrefFileInfo(reply, temp);
  22735. }
  22736. if (indexName.length())
  22737. {
  22738. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  22739. if (temp)
  22740. addXrefFileInfo(reply, temp);
  22741. }
  22742. }
  22743. }
  22744. };
  22745. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22746. {
  22747. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22748. }
  22749. //=====================================================================================================
  22750. // Keyed joins...
  22751. //
  22752. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22753. // may have RHS matches on, and sends the relevant fields to the relevant agents.
  22754. // A separate thread (the caller's thread) is waiting on agent replies, and once it has all replies for a given LHS record or group of records, calls
  22755. // the transform and returns rows that are created.
  22756. // 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)
  22757. //
  22758. //=====================================================================================================
  22759. class CJoinGroup;
  22760. interface IJoinProcessor
  22761. {
  22762. virtual void processEOG() = 0;
  22763. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22764. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22765. virtual bool fireException(IException *E) = 0;
  22766. virtual void processCompletedGroups() = 0;
  22767. };
  22768. //------------------------------------------------------------------------------------------------------
  22769. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22770. // It gathers all the corresponding RHS rows, keeping track of how may agent transactions are pending in endMarkersPending
  22771. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22772. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22773. // per-query limits etc (Note that the pointer array block is not though).
  22774. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22775. //
  22776. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off agent requests
  22777. // notePending will be called once for every agent request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22778. // initial count when created.
  22779. // Agent replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22780. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22781. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22782. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22783. // remaining reference and the JoinGroup will be processed and destroyed.
  22784. //
  22785. //------------------------------------------------------------------------------------------------------
  22786. class CJoinGroup : public CInterface
  22787. {
  22788. protected:
  22789. const void *left; // LHS row
  22790. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22791. atomic_t endMarkersPending; // How many agent responses still waiting for
  22792. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22793. unsigned lastPartNo;
  22794. unsigned pos;
  22795. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22796. public:
  22797. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22798. {
  22799. return a->allocate(size, activityId);
  22800. }
  22801. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22802. {
  22803. ReleaseRoxieRow(ptr);
  22804. }
  22805. void operator delete(void *ptr)
  22806. {
  22807. ReleaseRoxieRow(ptr);
  22808. }
  22809. public:
  22810. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22811. {
  22812. #ifdef TRACE_JOINGROUPS
  22813. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22814. #endif
  22815. candidates = 0;
  22816. lastPartNo = 0;
  22817. pos = 0;
  22818. left = _left;
  22819. groupStart = _groupStart;
  22820. if (_groupStart)
  22821. {
  22822. atomic_inc(&_groupStart->endMarkersPending);
  22823. }
  22824. atomic_set(&endMarkersPending, 1);
  22825. }
  22826. ~CJoinGroup()
  22827. {
  22828. #ifdef TRACE_JOINGROUPS
  22829. DBGLOG("Destroying joinGroup %p", this);
  22830. #endif
  22831. if (left)
  22832. {
  22833. ReleaseRoxieRow(left);
  22834. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22835. rows.kill();
  22836. }
  22837. }
  22838. inline bool isHeadRecord() const
  22839. {
  22840. return left==NULL;
  22841. }
  22842. inline bool complete() const
  22843. {
  22844. return atomic_read(&endMarkersPending) == 0;
  22845. }
  22846. #ifdef TRACE_JOINGROUPS
  22847. inline void notePending(unsigned lineNo)
  22848. #else
  22849. inline void notePending()
  22850. #endif
  22851. {
  22852. assert(!complete());
  22853. atomic_inc(&endMarkersPending);
  22854. #ifdef TRACE_JOINGROUPS
  22855. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22856. #endif
  22857. }
  22858. inline bool inGroup(CJoinGroup *leader) const
  22859. {
  22860. return groupStart==leader;
  22861. }
  22862. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22863. {
  22864. // Single threaded by now
  22865. assert(complete());
  22866. return rows.item(idx);
  22867. }
  22868. #ifdef TRACE_JOINGROUPS
  22869. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22870. #else
  22871. bool noteEndReceived(unsigned candidateCount)
  22872. #endif
  22873. {
  22874. assert(!complete());
  22875. if (candidateCount)
  22876. {
  22877. candidates += candidateCount;
  22878. }
  22879. #ifdef TRACE_JOINGROUPS
  22880. 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);
  22881. #endif
  22882. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22883. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22884. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22885. CJoinGroup *localGroupStart = groupStart;
  22886. if (atomic_dec_and_test(&endMarkersPending))
  22887. {
  22888. if (localGroupStart)
  22889. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22890. else
  22891. return true;
  22892. }
  22893. else
  22894. return false;
  22895. }
  22896. inline const void *queryLeft() const
  22897. {
  22898. return left;
  22899. }
  22900. void addRightMatch(KeyedJoinHeader *right)
  22901. {
  22902. assert(!complete());
  22903. unsigned short partNo = right->partNo;
  22904. if (partNo != lastPartNo)
  22905. {
  22906. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22907. if (partNo > lastPartNo)
  22908. pos = rows.length();
  22909. while (pos>0)
  22910. {
  22911. if (rows.item(pos-1)->partNo <= partNo)
  22912. break;
  22913. pos--;
  22914. }
  22915. lastPartNo = partNo;
  22916. }
  22917. rows.add(right, pos);
  22918. pos++;
  22919. }
  22920. inline unsigned rowsSeen() const
  22921. {
  22922. assert(complete());
  22923. return rows.length();
  22924. }
  22925. inline unsigned candidateCount() const
  22926. {
  22927. assert(complete());
  22928. return candidates;
  22929. }
  22930. };
  22931. #ifdef TRACE_JOINGROUPS
  22932. #define notePending() notePending(__LINE__)
  22933. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22934. #endif
  22935. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22936. {
  22937. private:
  22938. SafeQueueOf<const void, true> ready;
  22939. public:
  22940. IHThorKeyedJoinArg &helper;
  22941. unsigned joinProcessed;
  22942. bool isFullKey;
  22943. bool eof;
  22944. bool isSimple;
  22945. bool allPulled;
  22946. ActivityTimeAccumulator activityStats;
  22947. unsigned activityId;
  22948. RecordPullerThread &puller;
  22949. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22950. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22951. IJoinProcessor &processor;
  22952. KeyedJoinRemoteAdaptor(IRoxieAgentContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22953. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22954. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22955. : CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22956. helper(_helper),
  22957. isFullKey(_isFullKey),
  22958. isSimple(_isSimple),
  22959. activityId(_activity.queryId()),
  22960. puller(_puller),
  22961. processor(_processor)
  22962. {
  22963. joinProcessed = 0;
  22964. allPulled = false;
  22965. eof = false;
  22966. }
  22967. virtual void onCreate(IHThorArg *_colocalArg)
  22968. {
  22969. CRemoteResultAdaptor::onCreate(_colocalArg);
  22970. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22971. }
  22972. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22973. {
  22974. eof = false;
  22975. joinProcessed = 0;
  22976. activityStats.totalCycles = 0;
  22977. allPulled = false;
  22978. assertex(ready.ordinality()==0);
  22979. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22980. }
  22981. virtual void reset()
  22982. {
  22983. CRemoteResultAdaptor::reset();
  22984. while (ready.ordinality())
  22985. {
  22986. const void *goer = ready.dequeue();
  22987. if (goer)
  22988. ReleaseRoxieRow(goer);
  22989. }
  22990. while (injected.ordinality())
  22991. {
  22992. const void *goer = injected.dequeue();
  22993. if (goer)
  22994. ReleaseRoxieRow(goer);
  22995. }
  22996. }
  22997. inline void addResult(const void *row)
  22998. {
  22999. ready.enqueue(row);
  23000. }
  23001. virtual unsigned __int64 queryTotalCycles() const
  23002. {
  23003. return activityStats.totalCycles;
  23004. }
  23005. virtual const void *nextRow()
  23006. {
  23007. ActivityTimer t(activityStats, timeActivities);
  23008. for (;;)
  23009. {
  23010. if (eof)
  23011. return NULL;
  23012. processAgentResults();
  23013. if (ready.ordinality())
  23014. {
  23015. const void *result = ready.dequeue();
  23016. if (result)
  23017. joinProcessed++;
  23018. return result;
  23019. }
  23020. else
  23021. eof = true;
  23022. }
  23023. }
  23024. void gatherStats(CRuntimeStatisticCollection & merged) const
  23025. {
  23026. CRemoteResultAdaptor::gatherStats(merged);
  23027. if (ccdRecordAllocator)
  23028. ccdRecordAllocator->gatherStats(merged);
  23029. }
  23030. private:
  23031. void processAgentResults()
  23032. {
  23033. while (!ready.ordinality())
  23034. {
  23035. KeyedJoinHeader *fetchedData;
  23036. if (isSimple)
  23037. {
  23038. while (!allPulled && !injected.ordinality())
  23039. {
  23040. if (!puller.pullRecords(1))
  23041. {
  23042. puller.done();
  23043. allPulled = true;
  23044. }
  23045. }
  23046. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  23047. }
  23048. else
  23049. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  23050. if (fetchedData)
  23051. {
  23052. CJoinGroup *thisGroup = fetchedData->thisGroup;
  23053. if (fetchedData->partNo == (unsigned short) -1)
  23054. {
  23055. #ifdef TRACE_JOINGROUPS
  23056. CTXLOG("Got end for group %p", thisGroup);
  23057. #endif
  23058. unsigned candidateCount = (unsigned) fetchedData->fpos;
  23059. ReleaseRoxieRow(fetchedData);
  23060. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  23061. }
  23062. else
  23063. {
  23064. #ifdef TRACE_JOINGROUPS
  23065. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  23066. #endif
  23067. thisGroup->addRightMatch(fetchedData);
  23068. if (isFullKey)
  23069. {
  23070. #ifdef TRACE_JOINGROUPS
  23071. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  23072. #endif
  23073. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  23074. }
  23075. }
  23076. }
  23077. else
  23078. break;
  23079. }
  23080. }
  23081. };
  23082. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  23083. {
  23084. IHThorKeyedJoinArg &helper;
  23085. Owned<IKeyManager> tlk;
  23086. Linked<IKeyArray> keySet;
  23087. Linked<ITranslatorSet> translators;
  23088. CRemoteResultAdaptor remote;
  23089. RecordPullerThread puller;
  23090. IOutputMetaData *indexReadMeta;
  23091. IJoinProcessor *joinHandler;
  23092. bool variableIndexFileName;
  23093. bool indexReadInputRecordVariable;
  23094. bool isLocal;
  23095. Owned<IEngineRowAllocator> indexReadAllocator;
  23096. Owned<const IResolvedFile> varFileInfo;
  23097. IFinalRoxieInput *indexReadInput;
  23098. unsigned indexReadIdx = 0;
  23099. IIndexReadActivityInfo *rootIndex;
  23100. public:
  23101. CRoxieServerFullKeyedJoinHead(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  23102. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23103. helper((IHThorKeyedJoinArg &)basehelper),
  23104. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors(), !isBlind())),
  23105. keySet(_keySet),
  23106. translators(_translators),
  23107. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  23108. puller(false),
  23109. indexReadMeta(_indexReadMeta),
  23110. joinHandler(_joinHandler),
  23111. isLocal(_isLocal)
  23112. {
  23113. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23114. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23115. indexReadInput = NULL;
  23116. rootIndex = NULL;
  23117. }
  23118. virtual const IResolvedFile *queryVarFileInfo() const
  23119. {
  23120. return varFileInfo;
  23121. }
  23122. virtual void onCreate(IHThorArg *_colocalParent)
  23123. {
  23124. CRoxieServerActivity::onCreate(_colocalParent);
  23125. remote.onCreate(_colocalParent);
  23126. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23127. }
  23128. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23129. {
  23130. if (!idx)
  23131. puller.setInput(this, _sourceIdx, _in);
  23132. else if (idx==1)
  23133. {
  23134. indexReadInput = _in;
  23135. indexReadIdx = _sourceIdx;
  23136. }
  23137. else
  23138. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23139. }
  23140. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23141. {
  23142. puller.connectInputStreams(ctx, consumerOrdered);
  23143. //No rows are read from indexReadInput, so no need to extract the streams
  23144. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23145. }
  23146. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23147. {
  23148. switch (idx)
  23149. {
  23150. case 0:
  23151. return puller.queryInput();
  23152. case 1:
  23153. return indexReadInput;
  23154. default:
  23155. return NULL;
  23156. }
  23157. }
  23158. virtual void serializeExtra(MemoryBuffer &out)
  23159. {
  23160. if (helper.getJoinFlags() & JFindexfromactivity)
  23161. {
  23162. assertex(rootIndex);
  23163. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23164. indexId.serialize(out);
  23165. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23166. MemoryBuffer tmp;
  23167. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23168. if (rootIndex->queryActivity()->queryVarFileInfo())
  23169. {
  23170. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23171. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23172. }
  23173. unsigned ctxlen = tmp.length();
  23174. out.append(ctxlen).append(tmp);
  23175. }
  23176. }
  23177. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23178. {
  23179. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23180. if (indexReadInput)
  23181. {
  23182. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23183. rootIndex = indexReadInput->queryIndexReadActivity();
  23184. if (!rootIndex)
  23185. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23186. }
  23187. remote.onStart(parentExtractSize, parentExtract);
  23188. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23189. if (rootIndex)
  23190. {
  23191. varFileInfo.setown(rootIndex->getVarFileInfo());
  23192. translators.setown(rootIndex->getTranslators());
  23193. keySet.setown(rootIndex->getKeySet());
  23194. }
  23195. else if (variableIndexFileName)
  23196. {
  23197. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23198. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0, factory->isActivityCodeSigned()));
  23199. if (varFileInfo)
  23200. {
  23201. unsigned expectedCrc = helper.getIndexFormatCrc();
  23202. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23203. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), FileFormatMode::index, factory->queryQueryFactory().queryQueryName()));
  23204. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23205. }
  23206. }
  23207. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  23208. }
  23209. virtual void stop()
  23210. {
  23211. puller.stop();
  23212. CRoxieServerActivity::stop();
  23213. }
  23214. virtual void reset()
  23215. {
  23216. CRoxieServerActivity::reset();
  23217. puller.reset();
  23218. if (varFileInfo)
  23219. {
  23220. keySet.clear();
  23221. varFileInfo.clear();
  23222. }
  23223. }
  23224. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23225. {
  23226. if (idx==(unsigned)-1)
  23227. idx = 0;
  23228. return idx ? NULL : &remote;
  23229. }
  23230. virtual void processRow(const void *row)
  23231. {
  23232. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  23233. // called from front puller thread
  23234. // buffer up an IndexRead request
  23235. if (keySet && helper.leftCanMatch(row))
  23236. {
  23237. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  23238. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  23239. OwnedConstRoxieRow extracted;
  23240. if (indexReadSize)
  23241. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  23242. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  23243. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23244. {
  23245. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23246. if (thisBase)
  23247. {
  23248. unsigned fileNo = 0;
  23249. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23250. try
  23251. {
  23252. tlk->setKey(thisKey);
  23253. if (!thisKey->isTopLevelKey())
  23254. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23255. else
  23256. tlk->setLayoutTranslator(nullptr);
  23257. helper.createSegmentMonitors(tlk, extracted);
  23258. if (rootIndex)
  23259. rootIndex->mergeSegmentMonitors(tlk);
  23260. tlk->finishSegmentMonitors();
  23261. tlk->reset();
  23262. for (;;)
  23263. {
  23264. typedef const void * cvp;
  23265. if (thisKey->isTopLevelKey())
  23266. {
  23267. bool locallySorted = !thisKey->isFullySorted();
  23268. while (locallySorted || tlk->lookup(false))
  23269. {
  23270. unsigned agentPart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23271. if (locallySorted || agentPart)
  23272. {
  23273. cvp *outputBuffer = (cvp *) remote.getMem(agentPart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23274. *outputBuffer++ = jg;
  23275. if (indexReadInputRecordVariable)
  23276. {
  23277. *(unsigned *) outputBuffer = indexReadSize;
  23278. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  23279. }
  23280. jg->notePending();
  23281. memcpy(outputBuffer, extracted, indexReadSize);
  23282. if (!agentPart)
  23283. {
  23284. for (unsigned i = 1; i < numChannels; i++)
  23285. jg->notePending();
  23286. }
  23287. if (locallySorted)
  23288. break;
  23289. }
  23290. }
  23291. }
  23292. else
  23293. {
  23294. // MORE - this code seems to be duplicated in half keyed
  23295. unsigned accepted = 0;
  23296. unsigned rejected = 0;
  23297. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  23298. jg->notePending();
  23299. unsigned candidateCount = 0;
  23300. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23301. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23302. while (tlk->lookup(true))
  23303. {
  23304. candidateCount++;
  23305. indexRecordsRead++;
  23306. KLBlobProviderAdapter adapter(tlk);
  23307. const byte *indexRow = tlk->queryKeyBuffer();
  23308. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23309. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23310. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23311. {
  23312. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23313. rhs->fpos = fpos;
  23314. rhs->thisGroup = jg;
  23315. rhs->partNo = partNo;
  23316. result->append(rhs);
  23317. }
  23318. else
  23319. {
  23320. rejected++;
  23321. postFiltered++;
  23322. }
  23323. }
  23324. // output an end marker for the matches to this group
  23325. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23326. endMarker->fpos = (offset_t) candidateCount;
  23327. endMarker->thisGroup = jg;
  23328. endMarker->partNo = (unsigned short) -1;
  23329. result->append(endMarker);
  23330. remote.injectResult(result.getClear());
  23331. if (accepted)
  23332. noteStatistic(StNumIndexAccepted, accepted);
  23333. if (rejected)
  23334. noteStatistic(StNumIndexRejected, rejected);
  23335. }
  23336. if (++fileNo < thisBase->numParts())
  23337. {
  23338. thisKey = thisBase->queryPart(fileNo);
  23339. tlk->setKey(thisKey);
  23340. if (!thisKey->isTopLevelKey())
  23341. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23342. else
  23343. tlk->setLayoutTranslator(nullptr);
  23344. tlk->reset();
  23345. }
  23346. else
  23347. break;
  23348. }
  23349. tlk->releaseSegmentMonitors();
  23350. tlk->setKey(NULL);
  23351. }
  23352. catch (...)
  23353. {
  23354. tlk->releaseSegmentMonitors();
  23355. tlk->setKey(NULL);
  23356. throw;
  23357. }
  23358. }
  23359. }
  23360. joinHandler->noteEndReceived(jg, 0);
  23361. }
  23362. else
  23363. {
  23364. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23365. }
  23366. }
  23367. void processGroup(const ConstPointerArray &)
  23368. {
  23369. throwUnexpected();
  23370. }
  23371. virtual void processEOG()
  23372. {
  23373. joinHandler->processEOG();
  23374. }
  23375. virtual void processDone()
  23376. {
  23377. // called from puller thread
  23378. remote.flush();
  23379. remote.senddone();
  23380. }
  23381. virtual void onLimitExceeded(bool isKeyed)
  23382. {
  23383. if (traceLevel > 4)
  23384. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23385. if (isKeyed)
  23386. throwUnexpected();
  23387. helper.onLimitExceeded();
  23388. }
  23389. virtual const void *createLimitFailRow(bool isKeyed)
  23390. {
  23391. throwUnexpected();
  23392. }
  23393. virtual bool fireException(IException *e)
  23394. {
  23395. // called from puller thread on failure
  23396. remote.fireException(LINK(e));
  23397. return joinHandler->fireException(e);
  23398. }
  23399. virtual const void *nextRow()
  23400. {
  23401. throwUnexpected(); // I am nobody's input
  23402. }
  23403. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23404. {
  23405. CRoxieServerActivity::gatherStats(merged);
  23406. remote.gatherStats(merged);
  23407. if (indexReadAllocator)
  23408. indexReadAllocator->gatherStats(merged);
  23409. }
  23410. };
  23411. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23412. {
  23413. protected:
  23414. IHThorKeyedJoinArg &helper;
  23415. KeyedJoinRemoteAdaptor remote;
  23416. RecordPullerThread puller;
  23417. OwnedConstRoxieRow defaultRight;
  23418. Owned<IEngineRowAllocator> defaultRightAllocator;
  23419. unsigned joinFlags;
  23420. unsigned atMost;
  23421. unsigned atmostsTriggered;
  23422. unsigned abortLimit;
  23423. unsigned keepLimit;
  23424. bool limitFail;
  23425. bool limitOnFail;
  23426. bool preserveGroups;
  23427. bool cloneLeft;
  23428. bool isSimple;
  23429. bool isLocal;
  23430. ThorActivityKind activityKind;
  23431. CJoinGroup *groupStart;
  23432. CriticalSection groupsCrit;
  23433. QueueOf<CJoinGroup, false> groups;
  23434. IFinalRoxieInput *indexReadInput;
  23435. unsigned indexReadIdx = 0;
  23436. Owned<IStrandJunction> indexReadJunction;
  23437. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23438. IIndexReadActivityInfo *rootIndex;
  23439. void createDefaultRight()
  23440. {
  23441. if (!defaultRight)
  23442. {
  23443. if (!defaultRightAllocator)
  23444. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23445. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23446. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23447. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23448. }
  23449. }
  23450. public:
  23451. CRoxieServerKeyedJoinBase(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23452. , bool isFull, bool _isSimple, bool _isLocal)
  23453. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23454. helper((IHThorKeyedJoinArg &)basehelper),
  23455. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23456. puller(false),
  23457. joinFlags(_joinFlags),
  23458. atMost(0),
  23459. abortLimit(0),
  23460. keepLimit(0),
  23461. limitFail(false),
  23462. limitOnFail(false),
  23463. preserveGroups(meta.isGrouped()),
  23464. cloneLeft(false),
  23465. isSimple(_isSimple),
  23466. isLocal(_isLocal)
  23467. {
  23468. groupStart = NULL;
  23469. activityKind = _factory->getKind();
  23470. indexReadInput = NULL;
  23471. rootIndex = NULL;
  23472. atmostsTriggered = 0;
  23473. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23474. }
  23475. virtual void onCreate(IHThorArg *_colocalParent)
  23476. {
  23477. CRoxieServerActivity::onCreate(_colocalParent);
  23478. remote.onCreate(_colocalParent);
  23479. }
  23480. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23481. {
  23482. if (!idx)
  23483. puller.setInput(this, _sourceIdx, _in);
  23484. else if (idx==1)
  23485. {
  23486. indexReadInput = _in;
  23487. indexReadIdx = _sourceIdx;
  23488. }
  23489. else
  23490. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23491. }
  23492. virtual void connectInputStreams(bool consumerOrdered)
  23493. {
  23494. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23495. puller.connectInputStreams(ctx, consumerOrdered);
  23496. if (indexReadInput)
  23497. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23498. }
  23499. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23500. {
  23501. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23502. if (indexReadInput)
  23503. {
  23504. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23505. rootIndex = indexReadInput->queryIndexReadActivity();
  23506. if (!rootIndex)
  23507. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23508. }
  23509. remote.onStart(parentExtractSize, parentExtract);
  23510. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23511. atmostsTriggered = 0;
  23512. atMost = helper.getJoinLimit();
  23513. if (atMost == 0) atMost = (unsigned)-1;
  23514. abortLimit = helper.getMatchAbortLimit();
  23515. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23516. keepLimit = helper.getKeepLimit();
  23517. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23518. getLimitType(joinFlags, limitFail, limitOnFail);
  23519. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23520. if ((joinFlags & JFleftouter) || limitOnFail)
  23521. createDefaultRight();
  23522. }
  23523. virtual void stop()
  23524. {
  23525. puller.stop();
  23526. if (indexReadStream)
  23527. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23528. CRoxieServerActivity::stop();
  23529. }
  23530. virtual unsigned __int64 queryLocalCycles() const
  23531. {
  23532. __int64 localCycles = remote.activityStats.totalCycles;
  23533. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23534. if (localCycles < 0)
  23535. localCycles = 0;
  23536. return localCycles;
  23537. }
  23538. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23539. {
  23540. CRoxieServerActivity::gatherStats(merged);
  23541. remote.gatherStats(merged);
  23542. }
  23543. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23544. {
  23545. if (idx==0)
  23546. return puller.queryInput();
  23547. else if (idx==1)
  23548. return indexReadInput;
  23549. else
  23550. return NULL;
  23551. }
  23552. virtual void reset()
  23553. {
  23554. activityStats.totalCycles = remote.activityStats.totalCycles;
  23555. remote.activityStats.totalCycles = 0;
  23556. processed = remote.joinProcessed;
  23557. remote.joinProcessed = 0;
  23558. defaultRight.clear();
  23559. if (indexReadInput)
  23560. indexReadInput->reset();
  23561. if (atmostsTriggered)
  23562. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23563. CRoxieServerActivity::reset();
  23564. puller.reset();
  23565. while (groups.ordinality())
  23566. {
  23567. ::Release(groups.dequeue());
  23568. }
  23569. }
  23570. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23571. {
  23572. if (idx==(unsigned)-1)
  23573. idx = 0;
  23574. return idx ? NULL : &remote;
  23575. }
  23576. virtual CJoinGroup *createJoinGroup(const void *row)
  23577. {
  23578. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23579. CriticalBlock c(groupsCrit);
  23580. if (preserveGroups && !groupStart)
  23581. {
  23582. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23583. groups.enqueue(groupStart);
  23584. }
  23585. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23586. groups.enqueue(jg);
  23587. return jg;
  23588. }
  23589. void endGroup()
  23590. {
  23591. CriticalBlock c(groupsCrit);
  23592. if (groupStart)
  23593. noteEndReceived(groupStart, 0);
  23594. groupStart = NULL;
  23595. }
  23596. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23597. {
  23598. if (jg->noteEndReceived(candidateCount))
  23599. processCompletedGroups();
  23600. }
  23601. void processCompletedGroups()
  23602. {
  23603. CriticalBlock c(groupsCrit);
  23604. while (groups.ordinality())
  23605. {
  23606. if (!groups.head()->complete())
  23607. break;
  23608. Owned<CJoinGroup> head = groups.dequeue();
  23609. if (preserveGroups)
  23610. {
  23611. assert(head->isHeadRecord());
  23612. assert(groups.head()->inGroup(head));
  23613. unsigned joinGroupSize = 0;
  23614. while (groups.ordinality() && groups.head()->inGroup(head))
  23615. {
  23616. Owned<CJoinGroup> finger = groups.dequeue();
  23617. joinGroupSize += doJoinGroup(finger);
  23618. }
  23619. if (joinGroupSize)
  23620. remote.addResult(NULL);
  23621. }
  23622. else
  23623. doJoinGroup(head);
  23624. }
  23625. }
  23626. void failLimit(const void * left)
  23627. {
  23628. helper.onMatchAbortLimitExceeded();
  23629. CommonXmlWriter xmlwrite(0);
  23630. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23631. {
  23632. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23633. }
  23634. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23635. }
  23636. virtual bool needsAllocator() const { return true; }
  23637. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23638. {
  23639. if (cloneLeft && !except)
  23640. {
  23641. LinkRoxieRow(left);
  23642. remote.addResult((void *) left);
  23643. return 1;
  23644. }
  23645. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23646. unsigned outSize;
  23647. try
  23648. {
  23649. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23650. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned)fpos_or_count, group) :
  23651. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23652. }
  23653. catch (IException *E)
  23654. {
  23655. throw makeWrappedException(E);
  23656. }
  23657. if (outSize)
  23658. {
  23659. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23660. remote.addResult(shrunk);
  23661. return 1;
  23662. }
  23663. else
  23664. return 0;
  23665. }
  23666. unsigned doJoinGroup(CJoinGroup *jg)
  23667. {
  23668. unsigned matched = jg->rowsSeen();
  23669. unsigned added = 0;
  23670. const void *left = jg->queryLeft();
  23671. if (jg->candidateCount() > abortLimit)
  23672. {
  23673. if (limitFail)
  23674. failLimit(left);
  23675. if (ctx->queryDebugContext())
  23676. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23677. if (limitOnFail)
  23678. {
  23679. Owned<IException> except;
  23680. try
  23681. {
  23682. failLimit(left);
  23683. }
  23684. catch(IException * e)
  23685. {
  23686. except.setown(e);
  23687. }
  23688. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23689. }
  23690. }
  23691. else if (!matched || jg->candidateCount() > atMost)
  23692. {
  23693. if (jg->candidateCount() > atMost)
  23694. atmostsTriggered++;
  23695. switch (joinFlags & JFtypemask)
  23696. {
  23697. case JFleftouter:
  23698. case JFleftonly:
  23699. switch (activityKind)
  23700. {
  23701. case TAKkeyedjoin:
  23702. case TAKkeyeddenormalizegroup:
  23703. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23704. break;
  23705. case TAKkeyeddenormalize:
  23706. LinkRoxieRow(left);
  23707. remote.addResult((void *) left);
  23708. added++;
  23709. break;
  23710. }
  23711. break;
  23712. }
  23713. }
  23714. else if (!(joinFlags & JFexclude))
  23715. {
  23716. unsigned idx = 0;
  23717. switch (activityKind)
  23718. {
  23719. case TAKkeyedjoin:
  23720. while (idx < matched)
  23721. {
  23722. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23723. added += doTransform(left, &rhs->rhsdata, 0, NULL, NULL, idx+1);
  23724. if (added==keepLimit)
  23725. break;
  23726. idx++;
  23727. }
  23728. break;
  23729. case TAKkeyeddenormalize:
  23730. {
  23731. OwnedConstRoxieRow newLeft;
  23732. newLeft.set(left);
  23733. unsigned rowSize = 0;
  23734. unsigned rightAdded = 0;
  23735. while (idx < matched)
  23736. {
  23737. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23738. try
  23739. {
  23740. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23741. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23742. if (transformedSize)
  23743. {
  23744. rowSize = transformedSize;
  23745. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23746. rightAdded++;
  23747. if (rightAdded==keepLimit)
  23748. break;
  23749. }
  23750. idx++;
  23751. }
  23752. catch (IException *E)
  23753. {
  23754. throw makeWrappedException(E);
  23755. }
  23756. }
  23757. if (rowSize)
  23758. {
  23759. remote.addResult(newLeft.getClear());
  23760. added++;
  23761. }
  23762. }
  23763. break;
  23764. case TAKkeyeddenormalizegroup:
  23765. {
  23766. ConstPointerArray extractedRows;
  23767. while (idx < matched && idx < keepLimit)
  23768. {
  23769. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23770. extractedRows.append((void *) &rhs->rhsdata);
  23771. idx++;
  23772. }
  23773. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23774. }
  23775. break;
  23776. }
  23777. }
  23778. return added;
  23779. }
  23780. virtual void processDone()
  23781. {
  23782. // called from puller thread
  23783. remote.flush();
  23784. remote.senddone();
  23785. }
  23786. virtual void onLimitExceeded(bool isKeyed)
  23787. {
  23788. if (traceLevel > 4)
  23789. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23790. if (isKeyed)
  23791. throwUnexpected();
  23792. helper.onLimitExceeded();
  23793. }
  23794. virtual const void *createLimitFailRow(bool isKeyed)
  23795. {
  23796. throwUnexpected();
  23797. }
  23798. virtual bool fireException(IException *e)
  23799. {
  23800. // called from puller thread on failure
  23801. return remote.fireException(e);
  23802. }
  23803. virtual const void *nextRow()
  23804. {
  23805. throwUnexpected(); // I am nobody's input
  23806. }
  23807. };
  23808. #ifdef _MSC_VER
  23809. #pragma warning ( push )
  23810. #pragma warning ( disable: 4355 )
  23811. #endif
  23812. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23813. {
  23814. CRoxieServerFullKeyedJoinHead head;
  23815. Owned<IEngineRowAllocator> fetchInputAllocator;
  23816. Linked<IFilePartMap> map;
  23817. bool variableFetchFileName;
  23818. Owned<const IResolvedFile> varFetchFileInfo;
  23819. CachedOutputMetaData fetchInputFields;
  23820. public:
  23821. CRoxieServerKeyedJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, ITranslatorSet *_keyTranslators, IOutputMetaData *_indexReadMeta,
  23822. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23823. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23824. head(_ctx, _factory, _probeManager, _headId, _key, _keyTranslators, _indexReadMeta, this, _isLocal),
  23825. map(_map)
  23826. {
  23827. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23828. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23829. }
  23830. virtual const IResolvedFile *queryVarFileInfo() const
  23831. {
  23832. return varFetchFileInfo;
  23833. }
  23834. virtual void onCreate(IHThorArg *_colocalParent)
  23835. {
  23836. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23837. head.onCreate(_colocalParent);
  23838. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23839. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23840. }
  23841. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23842. {
  23843. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23844. if (variableFetchFileName)
  23845. {
  23846. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23847. OwnedRoxieString fname(helper.getFileName());
  23848. varFetchFileInfo.setown(resolveLFNFlat(fname, isFetchOpt, factory->isActivityCodeSigned()));
  23849. if (varFetchFileInfo)
  23850. {
  23851. // Note - we don't need to do any translation on the disk part of full-keyed joins
  23852. map.setown(varFetchFileInfo->getFileMap());
  23853. }
  23854. }
  23855. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23856. }
  23857. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23858. {
  23859. head.setInput(idx, _sourceIdx, _in);
  23860. }
  23861. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23862. {
  23863. connectInputStreams(consumerOrdered);
  23864. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23865. }
  23866. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23867. {
  23868. return head.queryInput(idx);
  23869. }
  23870. virtual void processRow(const void *_rhs)
  23871. {
  23872. // called from puller thread
  23873. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23874. CJoinGroup *jg = rhs->thisGroup;
  23875. if (rhs->partNo != (unsigned short) -1)
  23876. {
  23877. unsigned partNo = map->mapOffset(rhs->fpos);
  23878. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23879. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23880. if (fetchInputFields.isVariableSize())
  23881. {
  23882. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23883. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23884. ReleaseRoxieRow(rhs);
  23885. jg->notePending();
  23886. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23887. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23888. }
  23889. else
  23890. {
  23891. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23892. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23893. ReleaseRoxieRow(rhs);
  23894. jg->notePending();
  23895. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23896. }
  23897. }
  23898. else
  23899. {
  23900. unsigned candidateCount = (unsigned) rhs->fpos;
  23901. // CTXLOG("Full keyed join - all results back from index");
  23902. ReleaseRoxieRow(rhs);
  23903. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23904. }
  23905. }
  23906. virtual void processEOG()
  23907. {
  23908. // called from front puller thread
  23909. if (preserveGroups)
  23910. endGroup();
  23911. }
  23912. void processGroup(const ConstPointerArray &)
  23913. {
  23914. throwUnexpected();
  23915. }
  23916. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23917. {
  23918. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23919. if (fetchInputAllocator)
  23920. fetchInputAllocator->gatherStats(merged);
  23921. }
  23922. };
  23923. #ifdef _MSC_VER
  23924. #pragma warning ( pop )
  23925. #endif
  23926. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23927. {
  23928. IOutputMetaData *indexReadMeta;
  23929. Owned<IEngineRowAllocator> indexReadAllocator;
  23930. Owned<IKeyManager> tlk;
  23931. bool variableIndexFileName;
  23932. bool indexReadInputRecordVariable;
  23933. Owned<const IResolvedFile> varFileInfo;
  23934. Linked<ITranslatorSet> translators;
  23935. Linked<IKeyArray> keySet;
  23936. Owned<IOutputMetaData> joinPrefixedMeta;
  23937. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23938. public:
  23939. CRoxieServerHalfKeyedJoinActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators,
  23940. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23941. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23942. indexReadMeta(_indexReadMeta),
  23943. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors(), !isBlind())),
  23944. translators(_translators),
  23945. keySet(_keySet)
  23946. {
  23947. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23948. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23949. }
  23950. virtual void serializeExtra(MemoryBuffer &out)
  23951. {
  23952. if (helper.getJoinFlags() & JFindexfromactivity)
  23953. {
  23954. assertex(rootIndex);
  23955. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23956. indexId.serialize(out);
  23957. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23958. MemoryBuffer tmp;
  23959. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23960. if (rootIndex->queryActivity()->queryVarFileInfo())
  23961. {
  23962. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23963. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23964. }
  23965. unsigned ctxlen = tmp.length();
  23966. out.append(ctxlen).append(tmp);
  23967. }
  23968. }
  23969. virtual void onCreate(IHThorArg *_colocalParent)
  23970. {
  23971. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23972. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23973. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23974. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23975. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23976. }
  23977. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23978. {
  23979. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23980. if (rootIndex)
  23981. {
  23982. varFileInfo.setown(rootIndex->getVarFileInfo());
  23983. translators.setown(rootIndex->getTranslators());
  23984. keySet.setown(rootIndex->getKeySet());
  23985. }
  23986. else if (variableIndexFileName)
  23987. {
  23988. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23989. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0, factory->isActivityCodeSigned()));
  23990. if (varFileInfo)
  23991. {
  23992. unsigned expectedCrc = helper.getIndexFormatCrc();
  23993. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23994. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), FileFormatMode::index, factory->queryQueryFactory().queryQueryName()));
  23995. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23996. }
  23997. }
  23998. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23999. }
  24000. virtual const IResolvedFile *queryVarFileInfo() const
  24001. {
  24002. return varFileInfo;
  24003. }
  24004. virtual void reset()
  24005. {
  24006. CRoxieServerKeyedJoinBase::reset();
  24007. if (varFileInfo)
  24008. {
  24009. keySet.clear();
  24010. varFileInfo.clear();
  24011. }
  24012. }
  24013. virtual void processRow(const void *row)
  24014. {
  24015. // called from front puller thread
  24016. // buffer up an IndexRead request
  24017. if (keySet && helper.leftCanMatch(row))
  24018. {
  24019. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  24020. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  24021. OwnedConstRoxieRow extracted;
  24022. if (indexReadRecordSize)
  24023. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  24024. CJoinGroup *jg = createJoinGroup(row);
  24025. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  24026. {
  24027. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  24028. if (thisBase)
  24029. {
  24030. unsigned fileNo = 0;
  24031. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  24032. tlk->setKey(thisKey);
  24033. if (thisKey && !thisKey->isTopLevelKey())
  24034. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  24035. else
  24036. tlk->setLayoutTranslator(nullptr);
  24037. helper.createSegmentMonitors(tlk, extracted);
  24038. if (rootIndex)
  24039. rootIndex->mergeSegmentMonitors(tlk);
  24040. tlk->finishSegmentMonitors();
  24041. try
  24042. {
  24043. tlk->reset();
  24044. for (;;)
  24045. {
  24046. typedef const void * cvp;
  24047. if (thisKey && thisKey->isTopLevelKey())
  24048. {
  24049. bool locallySorted = (!thisKey->isFullySorted());
  24050. while (locallySorted || tlk->lookup(false))
  24051. {
  24052. unsigned agentPart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  24053. if (locallySorted || agentPart)
  24054. {
  24055. cvp *outputBuffer = (cvp *) remote.getMem(agentPart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  24056. *outputBuffer++ = jg;
  24057. if (indexReadInputRecordVariable)
  24058. {
  24059. *(unsigned *) outputBuffer = indexReadRecordSize;
  24060. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  24061. }
  24062. jg->notePending();
  24063. memcpy(outputBuffer, extracted, indexReadRecordSize);
  24064. if (!agentPart)
  24065. {
  24066. for (unsigned i = 1; i < numChannels; i++)
  24067. jg->notePending();
  24068. }
  24069. if (locallySorted)
  24070. break;
  24071. }
  24072. }
  24073. }
  24074. else
  24075. {
  24076. unsigned accepted = 0;
  24077. unsigned rejected = 0;
  24078. Owned<CRowArrayMessageResult> result;
  24079. if (!isSimple)
  24080. result.setown(new CRowArrayMessageResult());
  24081. // MORE - This code seems to be duplicated in keyedJoinHead
  24082. jg->notePending();
  24083. unsigned candidateCount = 0;
  24084. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  24085. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  24086. while (tlk->lookup(true))
  24087. {
  24088. candidateCount++;
  24089. indexRecordsRead++;
  24090. KLBlobProviderAdapter adapter(tlk);
  24091. const byte *indexRow = tlk->queryKeyBuffer();
  24092. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  24093. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  24094. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  24095. {
  24096. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  24097. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  24098. accepted++;
  24099. KLBlobProviderAdapter adapter(tlk);
  24100. helper.extractJoinFields(pb, indexRow, &adapter);
  24101. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  24102. rec->fpos = fpos;
  24103. rec->thisGroup = jg;
  24104. rec->partNo = partNo;
  24105. if (isSimple)
  24106. remote.injected.enqueue(rec);
  24107. else
  24108. result->append(rec);
  24109. }
  24110. else
  24111. {
  24112. rejected++;
  24113. postFiltered++;
  24114. }
  24115. }
  24116. // output an end marker for the matches to this group
  24117. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  24118. rec->fpos = (offset_t) candidateCount;
  24119. rec->thisGroup = jg;
  24120. rec->partNo = (unsigned short) -1;
  24121. if (isSimple)
  24122. remote.injected.enqueue(rec);
  24123. else
  24124. {
  24125. result->append(rec);
  24126. remote.injectResult(result.getClear());
  24127. }
  24128. if (accepted)
  24129. noteStatistic(StNumIndexAccepted, accepted);
  24130. if (rejected)
  24131. noteStatistic(StNumIndexRejected, rejected);
  24132. }
  24133. if (++fileNo < thisBase->numParts())
  24134. {
  24135. thisKey = thisBase->queryPart(fileNo);
  24136. tlk->setKey(thisKey);
  24137. if (thisKey && !thisKey->isTopLevelKey())
  24138. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  24139. else
  24140. tlk->setLayoutTranslator(nullptr);
  24141. tlk->reset();
  24142. }
  24143. else
  24144. break;
  24145. }
  24146. tlk->releaseSegmentMonitors();
  24147. tlk->setKey(NULL);
  24148. }
  24149. catch (...)
  24150. {
  24151. tlk->releaseSegmentMonitors();
  24152. tlk->setKey(NULL);
  24153. throw;
  24154. }
  24155. }
  24156. }
  24157. noteEndReceived(jg, 0);
  24158. }
  24159. else
  24160. {
  24161. noteEndReceived(createJoinGroup(row), 0);
  24162. }
  24163. }
  24164. virtual void processEOG()
  24165. {
  24166. // called from front puller thread
  24167. if (preserveGroups)
  24168. endGroup();
  24169. }
  24170. void processGroup(const ConstPointerArray &)
  24171. {
  24172. throwUnexpected();
  24173. }
  24174. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  24175. {
  24176. CRoxieServerKeyedJoinBase::gatherStats(merged);
  24177. if (indexReadAllocator)
  24178. indexReadAllocator->gatherStats(merged);
  24179. if (joinFieldsAllocator)
  24180. joinFieldsAllocator->gatherStats(merged);
  24181. }
  24182. };
  24183. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  24184. {
  24185. Owned<const IResolvedFile> indexfile;
  24186. Owned<const IResolvedFile> datafile;
  24187. Owned<IKeyArray> keySet;
  24188. Owned<ITranslatorSet> keyTranslators; // For the indexes
  24189. RemoteActivityId headId;
  24190. RemoteActivityId tailId;
  24191. IOutputMetaData *indexReadMeta;
  24192. Owned<IFilePartMap> map;
  24193. Owned<ITranslatorSet> translators; // for the disk files on local full keyed joins
  24194. Owned<IFileIOArray> files;
  24195. unsigned joinFlags;
  24196. bool isHalfKeyed;
  24197. bool isLocal;
  24198. bool variableFetchFileName;
  24199. bool variableIndexFileName;
  24200. bool isSimple;
  24201. public:
  24202. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  24203. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  24204. {
  24205. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  24206. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  24207. isSimple = isLocal;
  24208. rtlDataAttr indexLayoutMeta;
  24209. size32_t indexLayoutSize = 0;
  24210. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  24211. assertex(indexLayoutSize== 0);
  24212. joinFlags = helper->getJoinFlags();
  24213. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  24214. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  24215. if (!variableIndexFileName)
  24216. {
  24217. bool isOpt = (joinFlags & JFindexoptional) != 0;
  24218. OwnedRoxieString indexFileName(helper->getIndexFileName());
  24219. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  24220. if (indexfile)
  24221. {
  24222. unsigned expectedCrc = helper->getIndexFormatCrc();
  24223. unsigned projectedCrc = helper->getProjectedIndexFormatCrc();
  24224. keyTranslators.setown(indexfile->getTranslators(projectedCrc, helper->queryProjectedIndexRecordSize(), expectedCrc, helper->queryIndexRecordSize(), getEnableFieldTranslation(), FileFormatMode::index, queryFactory.queryQueryName()));
  24225. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  24226. }
  24227. }
  24228. if (keySet && keySet->length()==1 && !isSimple)
  24229. {
  24230. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  24231. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  24232. isSimple = true;
  24233. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  24234. }
  24235. if (!simpleLocalKeyedJoins)
  24236. isSimple = false;
  24237. isHalfKeyed = !helper->diskAccessRequired();
  24238. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  24239. if (!isHalfKeyed && !variableFetchFileName)
  24240. {
  24241. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  24242. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true, isActivityCodeSigned()));
  24243. if (datafile)
  24244. {
  24245. if (isLocal) // Not sure this works
  24246. {
  24247. unsigned expectedCrc = helper->getDiskFormatCrc();
  24248. unsigned projectedCrc = helper->getProjectedFormatCrc();
  24249. translators.setown(datafile->getTranslators(expectedCrc, helper->queryProjectedDiskRecordSize(), projectedCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), FileFormatMode::flat, queryFactory.queryQueryName()));
  24250. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  24251. }
  24252. else
  24253. map.setown(datafile->getFileMap());
  24254. }
  24255. }
  24256. }
  24257. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  24258. {
  24259. if (isHalfKeyed)
  24260. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  24261. headId, keySet, keyTranslators, indexReadMeta, joinFlags, isSimple, isLocal);
  24262. else
  24263. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  24264. headId, keySet, keyTranslators, indexReadMeta,
  24265. tailId, map, joinFlags, isLocal); // MORE - not sure local variant actually works - should be using files not map, for example?
  24266. }
  24267. virtual const StatisticsMapping &queryStatsMapping() const
  24268. {
  24269. return keyedJoinStatistics;
  24270. }
  24271. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  24272. {
  24273. if (datafile)
  24274. addXrefFileInfo(reply, datafile);
  24275. if (indexfile)
  24276. addXrefFileInfo(reply, indexfile);
  24277. }
  24278. };
  24279. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  24280. {
  24281. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  24282. }
  24283. //=================================================================================
  24284. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  24285. {
  24286. protected:
  24287. Owned<ISoapCallHelper> soaphelper;
  24288. IHThorSoapActionArg & helper;
  24289. StringBuffer authToken;
  24290. bool eof;
  24291. CriticalSection crit;
  24292. ClientCertificate *pClientCert;
  24293. public:
  24294. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  24295. CRoxieServerSoapActivityBase(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24296. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  24297. {
  24298. eof = false;
  24299. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  24300. pClientCert = &clientCert;
  24301. else
  24302. pClientCert = NULL;
  24303. }
  24304. // ISoapCallRowProvider
  24305. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  24306. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  24307. virtual const void * getNextRow() { return NULL; };
  24308. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  24309. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24310. {
  24311. eof = false;
  24312. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  24313. authToken.append(ctx->queryAuthToken());
  24314. }
  24315. virtual void reset()
  24316. {
  24317. // MORE - Shouldn't we make sure thread is stopped etc???
  24318. soaphelper.clear();
  24319. CRoxieServerActivity::reset();
  24320. }
  24321. // IRoxieAbortMonitor
  24322. virtual void checkForAbort() { checkAbort(); }
  24323. };
  24324. class CRoxieServerSoapActionBase : public CRoxieServerSoapActivityBase
  24325. {
  24326. public:
  24327. CRoxieServerSoapActionBase(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24328. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24329. {
  24330. }
  24331. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24332. {
  24333. CriticalBlock b(ecrit);
  24334. if (exception)
  24335. throw(exception.getLink());
  24336. if (!executed)
  24337. {
  24338. try
  24339. {
  24340. executed = true;
  24341. start(parentExtractSize, parentExtract, false);
  24342. {
  24343. ActivityTimer t(activityStats, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  24344. onExecute();
  24345. }
  24346. stop();
  24347. }
  24348. catch (IException *E)
  24349. {
  24350. ctx->notifyAbort(E);
  24351. exception.set(E);
  24352. abort();
  24353. throw E;
  24354. }
  24355. }
  24356. }
  24357. virtual void onExecute() = 0;
  24358. virtual void reset() override
  24359. {
  24360. executed = false;
  24361. exception.clear();
  24362. CRoxieServerSoapActivityBase::reset();
  24363. }
  24364. protected:
  24365. bool executed = false;
  24366. Linked<IException> exception;
  24367. CriticalSection ecrit;
  24368. };
  24369. //---------------------------------------------------------------------------
  24370. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  24371. {
  24372. IHThorSoapCallArg & callHelper;
  24373. public:
  24374. CRoxieServerSoapRowCallActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24375. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24376. {
  24377. }
  24378. virtual IHThorSoapCallArg * queryCallHelper()
  24379. {
  24380. return &callHelper;
  24381. }
  24382. virtual bool needsAllocator() const { return true; }
  24383. virtual const void *nextRow()
  24384. {
  24385. ActivityTimer t(activityStats, timeActivities);
  24386. if(eof) return NULL;
  24387. if (soaphelper == NULL)
  24388. {
  24389. if (factory->getKind()==TAKhttp_rowdataset)
  24390. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24391. else
  24392. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24393. soaphelper->start();
  24394. }
  24395. OwnedConstRoxieRow ret = soaphelper->getRow();
  24396. if (!ret)
  24397. {
  24398. eof = true;
  24399. return NULL;
  24400. }
  24401. ++processed;
  24402. return ret.getClear();
  24403. }
  24404. };
  24405. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  24406. {
  24407. public:
  24408. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24409. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24410. {
  24411. }
  24412. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  24413. {
  24414. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24415. }
  24416. virtual const StatisticsMapping &queryStatsMapping() const
  24417. {
  24418. return soapStatistics;
  24419. }
  24420. };
  24421. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24422. {
  24423. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24424. }
  24425. //---------------------------------------------------------------------------
  24426. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActionBase
  24427. {
  24428. public:
  24429. CRoxieServerSoapRowActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24430. : CRoxieServerSoapActionBase(_ctx, _factory, _probeManager)
  24431. {}
  24432. virtual void onExecute() override
  24433. {
  24434. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24435. soaphelper->start();
  24436. soaphelper->waitUntilDone();
  24437. IException *e = soaphelper->getError();
  24438. soaphelper.clear();
  24439. if (e)
  24440. throw e;
  24441. }
  24442. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24443. {
  24444. return NULL;
  24445. }
  24446. virtual const void *nextRow()
  24447. {
  24448. throwUnexpected(); // I am nobody's input
  24449. }
  24450. };
  24451. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24452. {
  24453. bool isRoot;
  24454. public:
  24455. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24456. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24457. {
  24458. }
  24459. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  24460. {
  24461. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24462. }
  24463. virtual bool isSink() const
  24464. {
  24465. return isRoot;
  24466. }
  24467. virtual const StatisticsMapping &queryStatsMapping() const
  24468. {
  24469. return soapStatistics;
  24470. }
  24471. };
  24472. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24473. {
  24474. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24475. }
  24476. //---------------------------------------------------------------------------
  24477. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24478. {
  24479. IHThorSoapCallArg & callHelper;
  24480. public:
  24481. CRoxieServerSoapDatasetCallActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24482. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24483. {
  24484. }
  24485. virtual IHThorSoapCallArg * queryCallHelper()
  24486. {
  24487. return &callHelper;
  24488. }
  24489. virtual const void *getNextRow()
  24490. {
  24491. CriticalBlock b(crit); // MORE - why ?
  24492. return inputStream->ungroupedNextRow();
  24493. }
  24494. virtual bool needsAllocator() const { return true; }
  24495. virtual const void *nextRow()
  24496. {
  24497. ActivityTimer t(activityStats, timeActivities);
  24498. if(eof) return NULL;
  24499. if (soaphelper == NULL)
  24500. {
  24501. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24502. soaphelper->start();
  24503. }
  24504. OwnedConstRoxieRow ret = soaphelper->getRow();
  24505. if (!ret)
  24506. {
  24507. eof = true;
  24508. return NULL;
  24509. }
  24510. ++processed;
  24511. return ret.getClear();
  24512. }
  24513. };
  24514. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24515. {
  24516. public:
  24517. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24518. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24519. {
  24520. }
  24521. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  24522. {
  24523. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24524. }
  24525. virtual const StatisticsMapping &queryStatsMapping() const
  24526. {
  24527. return soapStatistics;
  24528. }
  24529. };
  24530. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24531. {
  24532. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24533. }
  24534. //---------------------------------------------------------------------------
  24535. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActionBase
  24536. {
  24537. public:
  24538. CRoxieServerSoapDatasetActionActivity(IRoxieAgentContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24539. : CRoxieServerSoapActionBase(_ctx, _factory, _probeManager)
  24540. {}
  24541. virtual const void *getNextRow()
  24542. {
  24543. CriticalBlock b(crit); // MORE - Why?
  24544. const void *nextrec = inputStream->ungroupedNextRow();
  24545. if (nextrec)
  24546. processed++;
  24547. return nextrec;
  24548. }
  24549. virtual void onExecute() override
  24550. {
  24551. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24552. soaphelper->start();
  24553. soaphelper->waitUntilDone();
  24554. IException *e = soaphelper->getError();
  24555. soaphelper.clear();
  24556. if (e)
  24557. throw e;
  24558. }
  24559. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24560. {
  24561. return NULL;
  24562. }
  24563. virtual const void *nextRow()
  24564. {
  24565. throwUnexpected(); // I am nobody's input
  24566. }
  24567. };
  24568. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24569. {
  24570. bool isRoot;
  24571. public:
  24572. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24573. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24574. {
  24575. }
  24576. virtual IRoxieServerActivity *createActivity(IRoxieAgentContext *_ctx, IProbeManager *_probeManager) const
  24577. {
  24578. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24579. }
  24580. virtual bool isSink() const
  24581. {
  24582. return isRoot;
  24583. }
  24584. virtual const StatisticsMapping &queryStatsMapping() const
  24585. {
  24586. return soapStatistics;
  24587. }
  24588. };
  24589. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24590. {
  24591. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24592. }
  24593. //=====================================================================================================
  24594. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24595. {
  24596. IArrayOf<IGraphResult> results;
  24597. CriticalSection cs;
  24598. IGraphResult & select(unsigned idx)
  24599. {
  24600. CriticalBlock procedure(cs);
  24601. if (idx >= results.ordinality())
  24602. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24603. return results.item(idx);
  24604. }
  24605. public:
  24606. IMPLEMENT_IINTERFACE
  24607. void clear()
  24608. {
  24609. CriticalBlock procedure(cs);
  24610. results.kill();
  24611. }
  24612. virtual IEngineRowStream * createIterator(unsigned id)
  24613. {
  24614. return select(id).createIterator();
  24615. }
  24616. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24617. {
  24618. select(id).getLinkedResult(count, ret);
  24619. }
  24620. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24621. {
  24622. select(id).getLinkedResult(count, ret);
  24623. }
  24624. virtual const void * getLinkedRowResult(unsigned id)
  24625. {
  24626. return select(id).getLinkedRowResult();
  24627. }
  24628. void setResult(unsigned id, IGraphResult * result)
  24629. {
  24630. CriticalBlock procedure(cs);
  24631. if (results.ordinality() <= id)
  24632. {
  24633. while (results.ordinality() < id)
  24634. results.append(*new CGraphResult);
  24635. results.append(*LINK(result));
  24636. }
  24637. else
  24638. results.replace(*LINK(result), id);
  24639. }
  24640. void appendResult(IGraphResult * result)
  24641. {
  24642. CriticalBlock procedure(cs);
  24643. results.append(*LINK(result));
  24644. }
  24645. };
  24646. //===================================================================================================================
  24647. class CPseudoArg : implements CThorSinkArgOf<IHThorArg>
  24648. {
  24649. };
  24650. class CPseudoActivity : public CRoxieServerActivity
  24651. {
  24652. public:
  24653. CPseudoActivity(IRoxieAgentContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24654. virtual const void *nextRow()
  24655. {
  24656. throwUnexpected(); // I am nobody's input
  24657. }
  24658. };
  24659. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24660. {
  24661. protected:
  24662. class ActivityGraphAgentContext : public IndirectAgentContext
  24663. {
  24664. SpinLock abortLock;
  24665. bool aborted;
  24666. Owned<IException> exception;
  24667. public:
  24668. ActivityGraphAgentContext(IRoxieAgentContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectAgentContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24669. {
  24670. aborted = false;
  24671. }
  24672. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24673. virtual void notifyAbort(IException *E)
  24674. {
  24675. if (QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24676. {
  24677. SpinBlock b(abortLock);
  24678. if (!aborted)
  24679. {
  24680. aborted = true;
  24681. exception.set(E);
  24682. }
  24683. }
  24684. }
  24685. virtual void checkAbort()
  24686. {
  24687. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24688. {
  24689. SpinBlock b(abortLock);
  24690. if (!exception)
  24691. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24692. throw exception.getLink();
  24693. }
  24694. IndirectAgentContext::checkAbort();
  24695. }
  24696. virtual ICodeContext *queryCodeContext()
  24697. {
  24698. return codeContext;
  24699. }
  24700. void setCodeContext(ICodeContext * _codeContext)
  24701. {
  24702. codeContext = _codeContext;
  24703. }
  24704. void setLoopCounter(unsigned _loopCounter)
  24705. {
  24706. loopCounter = _loopCounter;
  24707. }
  24708. void setPrefix(const char *name)
  24709. {
  24710. prefix.set(name);
  24711. }
  24712. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24713. {
  24714. childGraphs.setValue(id, childGraph);
  24715. }
  24716. virtual IActivityGraph * queryChildGraph(unsigned id)
  24717. {
  24718. if (queryTraceLevel() > 10)
  24719. CTXLOG("resolveChildGraph %d", id);
  24720. IActivityGraph *childGraph = childGraphs.getValue(id);
  24721. assertex(childGraph);
  24722. return childGraph;
  24723. }
  24724. // MORE should really redirect the other log context ones too (though mostly doesn't matter). Really should refactor to have a queryLogContext() method in IRoxieAgentContext I think
  24725. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24726. {
  24727. IndirectAgentContext::getLogPrefix(ret);
  24728. if (prefix)
  24729. ret.appendf(":%s", prefix.str());
  24730. if (loopCounter)
  24731. ret.appendf("{%u}", loopCounter);
  24732. return ret;
  24733. }
  24734. protected:
  24735. const IRoxieContextLogger &logctx;
  24736. unsigned loopCounter;
  24737. StringAttr prefix;
  24738. ICodeContext * codeContext;
  24739. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24740. } graphAgentContext;
  24741. class ActivityGraphCodeContext : public IndirectCodeContext
  24742. {
  24743. public:
  24744. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24745. {
  24746. if ((unsigned) activityId == container->queryId())
  24747. return container;
  24748. IActivityGraph * match = agentContext->queryChildGraph((unsigned) activityId);
  24749. if (match)
  24750. return match->queryLocalGraph();
  24751. return IndirectCodeContext::resolveLocalQuery(activityId);
  24752. }
  24753. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24754. {
  24755. IActivityGraph * match = agentContext->queryChildGraph((unsigned) activityId);
  24756. return LINK(match->queryChildGraph());
  24757. }
  24758. virtual unsigned getGraphLoopCounter() const
  24759. {
  24760. return container->queryLoopCounter(); // only called if value is valid
  24761. }
  24762. void setContainer(IRoxieAgentContext * _agentContext, CActivityGraph * _container)
  24763. {
  24764. agentContext = _agentContext;
  24765. container = _container;
  24766. }
  24767. protected:
  24768. IRoxieAgentContext * agentContext;
  24769. CActivityGraph * container;
  24770. } graphCodeContext;
  24771. class SinkThread : public CInterface, implements IThreaded
  24772. {
  24773. public:
  24774. SinkThread(IActivityGraph &_parent, IRoxieServerActivity &_sink)
  24775. : thread("SinkThread", this), parent(_parent), sink(_sink)
  24776. {}
  24777. virtual void threadmain() override
  24778. {
  24779. try
  24780. {
  24781. sink.execute(parentExtractSize, parentExtract);
  24782. }
  24783. catch (IException *E)
  24784. {
  24785. parent.noteException(E);
  24786. throw;
  24787. }
  24788. }
  24789. void start(unsigned _parentExtractSize, const byte * _parentExtract)
  24790. {
  24791. parentExtract = _parentExtract;
  24792. parentExtractSize = _parentExtractSize;
  24793. thread.start();
  24794. }
  24795. inline void join()
  24796. {
  24797. thread.join(INFINITE);
  24798. }
  24799. private:
  24800. CThreadedPersistent thread;
  24801. IActivityGraph &parent;
  24802. IRoxieServerActivity &sink;
  24803. const byte * parentExtract = nullptr;
  24804. unsigned parentExtractSize = 0;
  24805. };
  24806. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphAgentContext last
  24807. IArrayOf<IRoxieServerActivity> activities;
  24808. IArrayOf<IRoxieProbe> probes;
  24809. CIArrayOf<SinkThread> threads;
  24810. IRoxieServerActivityCopyArray sinks;
  24811. StringAttr graphName;
  24812. Owned<CGraphResults> results;
  24813. CGraphResults graphLoopResults;
  24814. const ActivityArray & graphDefinition;
  24815. CriticalSection evaluateCrit;
  24816. IProbeManager *probeManager;
  24817. IRoxieServerActivity *parentActivity;
  24818. unsigned id;
  24819. unsigned loopCounter;
  24820. public:
  24821. IMPLEMENT_IINTERFACE;
  24822. CActivityGraph(IRoxieAgentContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24823. : graphAgentContext(_ctx, _logctx), graphName(_graphName), graphDefinition(x), probeManager(_probeManager), parentActivity(_parentActivity)
  24824. {
  24825. id = x.getLibraryGraphId();
  24826. if (!id)
  24827. id = _id;
  24828. loopCounter = 0;
  24829. graphAgentContext.setCodeContext(&graphCodeContext);
  24830. graphCodeContext.setContainer(&graphAgentContext, this);
  24831. }
  24832. ~CActivityGraph()
  24833. {
  24834. if (probeManager)
  24835. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24836. }
  24837. virtual const char *queryName() const
  24838. {
  24839. return graphName.get();
  24840. }
  24841. virtual void setPrefix(const char *name) override
  24842. {
  24843. graphAgentContext.setPrefix(name);
  24844. }
  24845. void createGraph(IRoxieAgentContext *_ctx)
  24846. {
  24847. if (graphDefinition.isMultiInstance())
  24848. {
  24849. graphCodeContext.set(_ctx->queryCodeContext());
  24850. _ctx = &graphAgentContext;
  24851. }
  24852. ForEachItemIn(idx, graphDefinition)
  24853. {
  24854. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24855. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24856. activities.append(activity);
  24857. if (donor.isSink())
  24858. {
  24859. sinks.append(activity);
  24860. if (probeManager)
  24861. probeManager->noteSink(&activity);
  24862. }
  24863. }
  24864. ForEachItemIn(idx1, graphDefinition)
  24865. {
  24866. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24867. IRoxieServerActivity &activity = activities.item(idx1);
  24868. unsigned inputidx = 0;
  24869. for (;;)
  24870. {
  24871. unsigned outputidx;
  24872. unsigned source = donor.getInput(inputidx, outputidx);
  24873. if (source==(unsigned) -1)
  24874. break;
  24875. connectInput(idx1, inputidx, source, outputidx, 0);
  24876. inputidx++;
  24877. }
  24878. IntArray &dependencies = donor.queryDependencies();
  24879. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24880. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24881. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24882. ForEachItemIn(idx2, dependencies)
  24883. {
  24884. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24885. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24886. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24887. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24888. if (probeManager)
  24889. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24890. }
  24891. }
  24892. ForEachItemIn(idx2, sinks)
  24893. {
  24894. IRoxieServerActivity &sink = sinks.item(idx2);
  24895. sink.connectInputStreams(true);
  24896. }
  24897. }
  24898. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24899. {
  24900. IRoxieServerActivity &targetActivity = activities.item(target);
  24901. IRoxieServerActivity &sourceActivity = activities.item(source);
  24902. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24903. if (probeManager)
  24904. {
  24905. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24906. probes.append(*LINK(inputProbe));
  24907. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24908. }
  24909. targetActivity.setInput(targetIdx, sourceIdx, output);
  24910. }
  24911. virtual void onCreate(IHThorArg *_colocalParent)
  24912. {
  24913. ForEachItemIn(idx, activities)
  24914. {
  24915. IRoxieServerActivity *activity = &activities.item(idx);
  24916. if (activity)
  24917. activity->onCreate(_colocalParent);
  24918. }
  24919. }
  24920. virtual void abort()
  24921. {
  24922. ForEachItemIn(idx, sinks)
  24923. {
  24924. IRoxieServerActivity &sink = sinks.item(idx);
  24925. sink.abort();
  24926. }
  24927. }
  24928. virtual void reset()
  24929. {
  24930. ForEachItemIn(idx, sinks)
  24931. {
  24932. IRoxieServerActivity &sink = sinks.item(idx);
  24933. sink.reset();
  24934. }
  24935. }
  24936. Linked<IException> exception;
  24937. CriticalSection eCrit;
  24938. virtual void noteException(IException *E)
  24939. {
  24940. CriticalBlock b(eCrit);
  24941. if (!exception)
  24942. {
  24943. if (graphAgentContext.queryDebugContext())
  24944. {
  24945. graphAgentContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24946. }
  24947. exception.set(E);
  24948. }
  24949. }
  24950. virtual void checkAbort()
  24951. {
  24952. CriticalBlock b(eCrit);
  24953. if (exception)
  24954. throw exception.getLink();
  24955. }
  24956. unsigned queryWorkflowId() const
  24957. {
  24958. return graphDefinition.queryWorkflowId();
  24959. }
  24960. virtual void execute()
  24961. {
  24962. results.setown(new CGraphResults);
  24963. doExecute(0, NULL);
  24964. }
  24965. //New child query code...
  24966. virtual IThorChildGraph * queryChildGraph()
  24967. {
  24968. return this;
  24969. }
  24970. virtual IEclGraphResults * queryLocalGraph()
  24971. {
  24972. return this;
  24973. }
  24974. virtual IRoxieServerChildGraph * queryLoopGraph()
  24975. {
  24976. return this;
  24977. }
  24978. inline unsigned queryId() const
  24979. {
  24980. return id;
  24981. }
  24982. inline unsigned queryLoopCounter() const
  24983. {
  24984. return loopCounter;
  24985. }
  24986. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24987. {
  24988. if (sinks.ordinality()==1)
  24989. sinks.item(0).execute(parentExtractSize, parentExtract);
  24990. #ifdef PARALLEL_EXECUTE
  24991. else if (!probeManager && !graphDefinition.isSequential())
  24992. {
  24993. #ifdef PARALLEL_PERSISTANT_THREADS
  24994. if (!threads.ordinality())
  24995. {
  24996. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24997. {
  24998. threads.append(*new SinkThread(*this, sinks.item(i)));
  24999. }
  25000. }
  25001. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  25002. threads.item(i).start(parentExtractSize, parentExtract);
  25003. try
  25004. {
  25005. sinks.item(sinks.ordinality()-1).execute(parentExtractSize, parentExtract);
  25006. }
  25007. catch (IException *E)
  25008. {
  25009. noteException(E);
  25010. E->Release();
  25011. }
  25012. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  25013. {
  25014. try
  25015. {
  25016. threads.item(i).join();
  25017. }
  25018. catch (IException *E)
  25019. {
  25020. noteException(E);
  25021. E->Release();
  25022. }
  25023. }
  25024. checkAbort();
  25025. #else
  25026. class casyncfor: public CAsyncFor
  25027. {
  25028. public:
  25029. IActivityGraph &parent;
  25030. unsigned parentExtractSize;
  25031. const byte * parentExtract;
  25032. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  25033. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  25034. void Do(unsigned i)
  25035. {
  25036. try
  25037. {
  25038. sinks.item(i).execute(parentExtractSize, parentExtract);
  25039. }
  25040. catch (IException *E)
  25041. {
  25042. parent.noteException(E);
  25043. throw;
  25044. }
  25045. }
  25046. private:
  25047. IRoxieServerActivityCopyArray &sinks;
  25048. } afor(sinks, *this, parentExtractSize, parentExtract);
  25049. afor.For(sinks.ordinality(), sinks.ordinality());
  25050. #endif
  25051. }
  25052. #endif
  25053. else
  25054. {
  25055. ForEachItemIn(idx, sinks)
  25056. {
  25057. IRoxieServerActivity &sink = sinks.item(idx);
  25058. sink.execute(parentExtractSize, parentExtract);
  25059. }
  25060. }
  25061. }
  25062. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  25063. {
  25064. CriticalBlock block(evaluateCrit);
  25065. results.setown(new CGraphResults);
  25066. try
  25067. {
  25068. doExecute(parentExtractSize, parentExtract);
  25069. }
  25070. catch (...)
  25071. {
  25072. DBGLOG("Exception thrown in child query - cleaning up");
  25073. reset();
  25074. throw;
  25075. }
  25076. reset();
  25077. return results.getClear();
  25078. }
  25079. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  25080. {
  25081. if (id && statsBuilder)
  25082. {
  25083. statsBuilder->beginSubGraphScope(parentActivity->querySubgraphId());
  25084. statsBuilder->beginActivityScope(parentActivity->queryId());
  25085. statsBuilder->beginChildGraphScope(id);
  25086. }
  25087. ForEachItemIn(i, activities)
  25088. activities.item(i).gatherStatistics(statsBuilder);
  25089. if (id && statsBuilder)
  25090. {
  25091. statsBuilder->endScope();
  25092. statsBuilder->endScope();
  25093. statsBuilder->endScope();
  25094. }
  25095. }
  25096. //interface IRoxieServerChildGraph
  25097. virtual void beforeExecute()
  25098. {
  25099. results.setown(new CGraphResults);
  25100. }
  25101. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25102. {
  25103. IFinalRoxieInput * ret = selectOutput(id);
  25104. ret->start(parentExtractSize, parentExtract, paused);
  25105. return ret;
  25106. }
  25107. virtual IFinalRoxieInput * selectOutput(unsigned id)
  25108. {
  25109. ForEachItemIn(i, sinks)
  25110. {
  25111. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  25112. if (ret)
  25113. return ret;
  25114. }
  25115. throwUnexpected();
  25116. return NULL;
  25117. }
  25118. virtual void setInputResult(unsigned id, IGraphResult * result)
  25119. {
  25120. results->setResult(id, result);
  25121. }
  25122. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  25123. {
  25124. ForEachItemIn(i, activities)
  25125. {
  25126. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  25127. return true;
  25128. }
  25129. return false;
  25130. }
  25131. virtual void stopUnusedOutputs()
  25132. {
  25133. //Hmm not sure how to do this...
  25134. }
  25135. virtual void afterExecute()
  25136. {
  25137. ForEachItemIn(i, sinks)
  25138. {
  25139. sinks.item(i).stop();
  25140. }
  25141. if (graphAgentContext.queryDebugContext())
  25142. {
  25143. graphAgentContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  25144. }
  25145. reset();
  25146. }
  25147. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  25148. {
  25149. doExecute(parentExtractSize, parentExtract);
  25150. return LINK(results);
  25151. }
  25152. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  25153. {
  25154. results->getLinkedResult(count, ret, id);
  25155. }
  25156. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  25157. {
  25158. results->getLinkedResult(count, ret, id);
  25159. }
  25160. virtual const void * getLinkedRowResult(unsigned id)
  25161. {
  25162. return results->getLinkedRowResult(id);
  25163. }
  25164. virtual void setResult(unsigned id, IGraphResult * result)
  25165. {
  25166. results->setResult(id, result);
  25167. }
  25168. virtual IEngineRowStream * createResultIterator(unsigned id)
  25169. {
  25170. return results->createIterator(id);
  25171. }
  25172. virtual void setGraphLoopResult(IGraphResult * result)
  25173. {
  25174. graphLoopResults.appendResult(result);
  25175. }
  25176. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  25177. {
  25178. try
  25179. {
  25180. return graphLoopResults.createIterator(id);
  25181. }
  25182. catch (IException * e)
  25183. {
  25184. e->Release();
  25185. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  25186. }
  25187. }
  25188. virtual void clearGraphLoopResults()
  25189. {
  25190. graphLoopResults.clear();
  25191. }
  25192. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  25193. {
  25194. doExecute(parentExtractSize, parentExtract);
  25195. }
  25196. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  25197. {
  25198. graphLoopResults.setResult(id, result);
  25199. }
  25200. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  25201. {
  25202. return graphLoopResults.createIterator(id);
  25203. }
  25204. virtual void getProbeResponse(IPropertyTree *query)
  25205. {
  25206. if (probeManager)
  25207. probeManager->getProbeResponse(query);
  25208. }
  25209. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieAgentContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  25210. {
  25211. throwUnexpected();
  25212. }
  25213. virtual CGraphIterationInfo *selectGraphLoopOutput()
  25214. {
  25215. return NULL;
  25216. }
  25217. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  25218. {
  25219. throwUnexpected();
  25220. }
  25221. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  25222. {
  25223. throwUnexpected();
  25224. }
  25225. };
  25226. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  25227. {
  25228. public:
  25229. IMPLEMENT_IINTERFACE;
  25230. CProxyActivityGraph(IRoxieAgentContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  25231. : ctx(_ctx), parentActivity(_parentActivity), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  25232. {
  25233. }
  25234. virtual void abort() override { throwUnexpected(); }
  25235. virtual void reset() override { throwUnexpected(); }
  25236. virtual void execute() override { throwUnexpected(); }
  25237. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  25238. virtual void onCreate(IHThorArg *_colocalArg) override
  25239. {
  25240. colocalArg = _colocalArg;
  25241. }
  25242. virtual void noteException(IException *E) override { throwUnexpected(); }
  25243. virtual void checkAbort() override { throwUnexpected(); }
  25244. virtual IThorChildGraph * queryChildGraph() override { return this; }
  25245. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25246. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25247. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieAgentContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override { throwUnexpected(); }
  25248. virtual const char *queryName() const override { throwUnexpected(); }
  25249. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  25250. {
  25251. CriticalBlock b(graphCrit);
  25252. ForEachItemIn(i, stack)
  25253. stack.item(i).gatherStatistics(statsBuilder);
  25254. }
  25255. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract) override
  25256. {
  25257. Owned<CActivityGraph> realGraph;
  25258. {
  25259. CriticalBlock b(graphCrit);
  25260. if (stack.length())
  25261. realGraph.setown(&stack.popGet());
  25262. }
  25263. if (!realGraph)
  25264. {
  25265. realGraph.setown(new CActivityGraph(ctx, graphName, id, parentActivity, graphDefinition, NULL, logctx));
  25266. realGraph->createGraph(ctx);
  25267. realGraph->onCreate(colocalArg);
  25268. }
  25269. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  25270. {
  25271. CriticalBlock b(graphCrit);
  25272. stack.append(*realGraph.getClear());
  25273. }
  25274. return results.getClear();
  25275. }
  25276. virtual void setPrefix(const char *) override
  25277. {
  25278. }
  25279. virtual unsigned queryWorkflowId() const override
  25280. {
  25281. return graphDefinition.queryWorkflowId();
  25282. }
  25283. protected:
  25284. IRoxieAgentContext *ctx;
  25285. IRoxieServerActivity *parentActivity;
  25286. StringAttr graphName;
  25287. unsigned id;
  25288. ActivityArray &graphDefinition;
  25289. const IRoxieContextLogger &logctx;
  25290. unsigned numParallel;
  25291. IHThorArg *colocalArg = nullptr;
  25292. mutable CriticalSection graphCrit;
  25293. CIArrayOf<CActivityGraph> stack;
  25294. };
  25295. class CIterationActivityGraph : public CActivityGraph
  25296. {
  25297. IHThorArg * colocalParent;
  25298. unsigned fixedParentExtractSize;
  25299. const byte * fixedParentExtract;
  25300. unsigned graphOutputActivityIndex;
  25301. public:
  25302. CIterationActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager,
  25303. unsigned _loopCounter, IRoxieAgentContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  25304. : CActivityGraph(_ctx, _graphName, _id, _parentActivity, x, _probeManager, _logctx)
  25305. {
  25306. graphOutputActivityIndex = 0;
  25307. loopCounter = _loopCounter;
  25308. colocalParent = _colocalParent;
  25309. graphAgentContext.setLoopCounter(loopCounter);
  25310. graphCodeContext.set(_ctx->queryCodeContext());
  25311. fixedParentExtractSize = parentExtractSize;
  25312. fixedParentExtract = parentExtract;
  25313. }
  25314. void createIterationGraph(IRoxieAgentContext *_ctx)
  25315. {
  25316. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  25317. ForEachItemIn(idx1, graphDefinition)
  25318. activities.append(*LINK(pseudoActivity));
  25319. graphOutputActivityIndex = queryGraphOutputIndex();
  25320. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  25321. }
  25322. unsigned queryGraphOutputIndex() const
  25323. {
  25324. ForEachItemIn(i, graphDefinition)
  25325. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  25326. return i;
  25327. throwUnexpected();
  25328. }
  25329. void recursiveCreateGraph(IRoxieAgentContext *_ctx, unsigned whichActivity)
  25330. {
  25331. //Check to see if already created
  25332. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  25333. if (prevActivity.queryId() != 0)
  25334. {
  25335. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  25336. return;
  25337. }
  25338. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  25339. IRoxieServerActivity * activity = NULL;
  25340. if (donor.isGraphInvariant())
  25341. {
  25342. ThorActivityKind kind = donor.getKind();
  25343. switch (kind)
  25344. {
  25345. case TAKif:
  25346. case TAKchildif:
  25347. case TAKcase:
  25348. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  25349. {
  25350. Owned<IHThorArg> helper = &donor.getHelper();
  25351. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  25352. helper->onStart(fixedParentExtract, NULL);
  25353. unsigned branch;
  25354. switch (kind)
  25355. {
  25356. case TAKif: case TAKchildif:
  25357. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  25358. break;
  25359. case TAKcase: case TAKchildcase:
  25360. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  25361. if (branch >= donor.numInputs())
  25362. branch = donor.numInputs() - 1;
  25363. break;
  25364. default:
  25365. throwUnexpected();
  25366. }
  25367. helper.clear();
  25368. unsigned outputidx;
  25369. unsigned source = donor.getInput(branch, outputidx);
  25370. if (source ==(unsigned) -1)
  25371. activity = createRoxieServerNullActivity(&graphAgentContext, &donor, probeManager);
  25372. else
  25373. activity = createRoxieServerPassThroughActivity(&graphAgentContext, &donor, probeManager);
  25374. activities.replace(*activity, whichActivity);
  25375. activity->onCreate(colocalParent);
  25376. if (source ==(unsigned) -1)
  25377. return;
  25378. recursiveCreateGraph(_ctx, source);
  25379. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  25380. break;
  25381. }
  25382. }
  25383. }
  25384. if (!activity)
  25385. {
  25386. activity = donor.createActivity(&graphAgentContext, probeManager);
  25387. activities.replace(*activity, whichActivity);
  25388. activity->onCreate(colocalParent);
  25389. activity->resetOutputsUsed();
  25390. unsigned inputidx = 0;
  25391. for (;;)
  25392. {
  25393. unsigned outputidx;
  25394. unsigned source = donor.getInput(inputidx, outputidx);
  25395. if (source==(unsigned) -1)
  25396. break;
  25397. recursiveCreateGraph(_ctx, source);
  25398. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  25399. inputidx++;
  25400. }
  25401. }
  25402. IntArray &dependencies = donor.queryDependencies();
  25403. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  25404. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  25405. ForEachItemIn(idx2, dependencies)
  25406. {
  25407. unsigned input = dependencies.item(idx2);
  25408. recursiveCreateGraph(_ctx, input);
  25409. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  25410. }
  25411. }
  25412. virtual CGraphIterationInfo *selectGraphLoopOutput()
  25413. {
  25414. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  25415. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  25416. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  25417. }
  25418. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  25419. {
  25420. ForEachItemIn(i, activities)
  25421. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  25422. }
  25423. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  25424. {
  25425. ForEachItemIn(i, activities)
  25426. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  25427. }
  25428. };
  25429. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  25430. {
  25431. StringAttr graphName;
  25432. StringAttr prefix;
  25433. ActivityArray & graphDefinition;
  25434. IProbeManager *probeManager;
  25435. unsigned id;
  25436. IRoxieAgentContext * ctx;
  25437. IHThorArg * colocalParent;
  25438. IRoxieServerActivity *parentActivity;
  25439. public:
  25440. IMPLEMENT_IINTERFACE;
  25441. CDelayedActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager)
  25442. : graphDefinition(x), probeManager(_probeManager), parentActivity(_parentActivity)
  25443. {
  25444. graphName.set(_graphName);
  25445. id = _id;
  25446. ctx = NULL;
  25447. colocalParent = NULL;
  25448. }
  25449. virtual const char *queryName() const override { return graphName.get(); }
  25450. virtual void abort() override { throwUnexpected(); }
  25451. virtual void reset() override { }
  25452. virtual void execute() override { throwUnexpected(); }
  25453. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  25454. virtual void noteException(IException *E) override { throwUnexpected(); }
  25455. virtual void checkAbort() override { throwUnexpected(); }
  25456. virtual IThorChildGraph * queryChildGraph() override { throwUnexpected(); }
  25457. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25458. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25459. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override { }
  25460. virtual void onCreate(IHThorArg *_colocalParent) override
  25461. {
  25462. colocalParent = _colocalParent;
  25463. }
  25464. virtual void setPrefix(const char *pfx) override
  25465. {
  25466. prefix.set(pfx);
  25467. }
  25468. virtual unsigned queryWorkflowId() const override
  25469. {
  25470. return graphDefinition.queryWorkflowId();
  25471. }
  25472. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieAgentContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override
  25473. {
  25474. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, parentActivity, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  25475. ret->createIterationGraph(ctx);
  25476. if (prefix)
  25477. ret->setPrefix(prefix);
  25478. return ret.getClear();
  25479. }
  25480. };
  25481. IActivityGraph *createActivityGraph(IRoxieAgentContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  25482. {
  25483. if (childFactories.isDelayed())
  25484. {
  25485. assertex(numParallel==1);
  25486. return new CDelayedActivityGraph(_graphName, id, parentActivity, childFactories, _probeManager);
  25487. }
  25488. else
  25489. {
  25490. if (numParallel==1 || _probeManager != nullptr)
  25491. {
  25492. Owned<IProbeManager> childProbe;
  25493. if (_probeManager)
  25494. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  25495. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, parentActivity, childFactories, childProbe, _logctx);
  25496. ret->createGraph(ctx);
  25497. if (_probeManager)
  25498. _probeManager->endChildGraph(childProbe, parentActivity);
  25499. return ret.getClear();
  25500. }
  25501. else
  25502. return new CProxyActivityGraph(ctx, _graphName, id, parentActivity, childFactories, _logctx, numParallel);
  25503. }
  25504. }
  25505. //================================================================================================================
  25506. #ifdef _USE_CPPUNIT
  25507. #include "unittests.hpp"
  25508. // 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...
  25509. #if _MSC_VER==1200
  25510. #undef protected
  25511. #endif
  25512. static const char *sortAlgorithm;
  25513. class TestMetaData : public CInterface, implements IOutputMetaData
  25514. {
  25515. public:
  25516. IMPLEMENT_IINTERFACE;
  25517. virtual size32_t getRecordSize(const void *) { return 10; }
  25518. virtual size32_t getMinRecordSize() const { return 10; }
  25519. virtual size32_t getFixedSize() const { return 10; }
  25520. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25521. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25522. virtual unsigned getMetaFlags() { return 0; }
  25523. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  25524. virtual void destruct(byte * self) {}
  25525. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25526. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25527. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  25528. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25529. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25530. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25531. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  25532. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25533. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25534. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); }
  25535. } testMeta;
  25536. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25537. {
  25538. char const * const *input;
  25539. IRoxieAgentContext *ctx;
  25540. unsigned endSeen;
  25541. bool eof;
  25542. unsigned count;
  25543. ActivityTimeAccumulator activityStats;
  25544. size32_t recordSize;
  25545. unsigned activityId;
  25546. public:
  25547. enum { STATEreset, STATEstarted, STATEstopped } state;
  25548. bool allRead;
  25549. unsigned repeat;
  25550. IMPLEMENT_IINTERFACE;
  25551. TestInput(IRoxieAgentContext *_ctx, char const * const *_input)
  25552. {
  25553. ctx = _ctx;
  25554. input = _input;
  25555. count = 0;
  25556. eof = false;
  25557. allRead = false;
  25558. endSeen = 0;
  25559. recordSize = testMeta.getFixedSize();
  25560. state = STATEreset;
  25561. activityId = 1;
  25562. repeat = 0;
  25563. }
  25564. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25565. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25566. {
  25567. ASSERT(state == STATEreset);
  25568. }
  25569. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25570. {
  25571. ASSERT(state == STATEreset);
  25572. state = STATEstarted;
  25573. }
  25574. virtual IStrandJunction *getOutputStreams(IRoxieAgentContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25575. {
  25576. streams.append(this);
  25577. return NULL;
  25578. }
  25579. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25580. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25581. virtual IRoxieServerActivity *queryActivity()
  25582. {
  25583. throwUnexpected();
  25584. }
  25585. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25586. {
  25587. throwUnexpected();
  25588. }
  25589. virtual void stop()
  25590. {
  25591. state = STATEstopped;
  25592. }
  25593. virtual void reset()
  25594. {
  25595. ASSERT(state == STATEstopped);
  25596. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25597. }
  25598. virtual void resetEOF()
  25599. {
  25600. throwUnexpected();
  25601. }
  25602. virtual void checkAbort() {}
  25603. virtual unsigned queryId() const { return activityId; };
  25604. virtual const void *nextRow()
  25605. {
  25606. ActivityTimer t(activityStats, ctx->queryOptions().timeActivities);
  25607. ASSERT(state == STATEstarted);
  25608. ASSERT(allRead || !eof);
  25609. if (eof)
  25610. return NULL;
  25611. again:
  25612. const char *nextSource = input[count++];
  25613. if (nextSource)
  25614. {
  25615. endSeen = 0;
  25616. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25617. memset(ret, 0, recordSize);
  25618. strncpy((char *) ret, nextSource, recordSize);
  25619. return ret;
  25620. }
  25621. else if (repeat)
  25622. {
  25623. repeat--;
  25624. count = 0;
  25625. goto again;
  25626. }
  25627. else
  25628. {
  25629. endSeen++;
  25630. if (endSeen==2)
  25631. eof = true;
  25632. return NULL;
  25633. }
  25634. }
  25635. virtual bool nextGroup(ConstPointerArray & group)
  25636. {
  25637. const void * next;
  25638. while ((next = nextRow()) != NULL)
  25639. group.append(next);
  25640. if (group.ordinality())
  25641. return true;
  25642. return false;
  25643. }
  25644. virtual unsigned __int64 queryTotalCycles() const { return activityStats.totalCycles; }
  25645. virtual unsigned __int64 queryLocalCycles() const { return activityStats.totalCycles; }
  25646. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25647. {
  25648. return NULL;
  25649. }
  25650. };
  25651. struct SortActivityTest : public CThorSortArg {
  25652. public:
  25653. struct CompareClass : public ICompare {
  25654. virtual int docompare(const void * _left, const void * _right) const {
  25655. return memcmp(_left, _right, 5);
  25656. }
  25657. } compare;
  25658. virtual ICompare * queryCompare() { return &compare; }
  25659. virtual IOutputMetaData * queryOutputMeta()
  25660. {
  25661. return &testMeta;
  25662. }
  25663. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25664. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25665. };
  25666. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25667. struct MergeActivityTest : public CThorMergeArg {
  25668. static bool isDedup;
  25669. public:
  25670. struct CompareClass : public ICompare {
  25671. virtual int docompare(const void * _left, const void * _right) const {
  25672. return memcmp(_left, _right, 5);
  25673. }
  25674. } compare;
  25675. virtual ICompare * queryCompare() { return &compare; }
  25676. virtual IOutputMetaData * queryOutputMeta()
  25677. {
  25678. return &testMeta;
  25679. }
  25680. virtual bool dedup() { return isDedup; }
  25681. };
  25682. bool MergeActivityTest::isDedup = false;
  25683. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25684. struct SplitActivityTest : public CThorSplitArg {
  25685. public:
  25686. virtual unsigned numBranches() { return 2; }
  25687. virtual IOutputMetaData * queryOutputMeta()
  25688. {
  25689. return &testMeta;
  25690. }
  25691. };
  25692. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25693. class CcdServerTest : public CppUnit::TestFixture
  25694. {
  25695. CPPUNIT_TEST_SUITE(CcdServerTest);
  25696. CPPUNIT_TEST(testSetup);
  25697. CPPUNIT_TEST(testHeapSort);
  25698. CPPUNIT_TEST(testQuickSort);
  25699. CPPUNIT_TEST(testMerge);
  25700. CPPUNIT_TEST(testMergeDedup);
  25701. CPPUNIT_TEST(testMiscellaneous);
  25702. CPPUNIT_TEST(testSplitter);
  25703. CPPUNIT_TEST(testCleanup);
  25704. CPPUNIT_TEST_SUITE_END();
  25705. protected:
  25706. AgentContextLogger logctx;
  25707. Owned<const IQueryDll> queryDll;
  25708. Owned<IRoxiePackage> package;
  25709. Owned<IPropertyTree> stateInfo;
  25710. Owned<IQueryFactory> queryFactory;
  25711. Owned<IRoxieAgentContext> ctx;
  25712. void testSetup()
  25713. {
  25714. selfTestMode = true;
  25715. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25716. }
  25717. void testCleanup()
  25718. {
  25719. roxiemem::releaseRoxieHeap();
  25720. }
  25721. void init()
  25722. {
  25723. package.setown(createRoxiePackage(NULL, NULL));
  25724. queryDll.setown(createExeQueryDll("roxie"));
  25725. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25726. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25727. ctx.setown(createAgentContext(queryFactory, logctx, NULL, false));
  25728. queryActiveTimer()->reset();
  25729. }
  25730. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25731. {
  25732. testActivity(activity, input, NULL, output);
  25733. }
  25734. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25735. {
  25736. TestInput in(ctx, input);
  25737. TestInput in2(ctx, input2);
  25738. activity->setInput(0, 0, &in);
  25739. if (input2)
  25740. activity->setInput(1, 0, &in2);
  25741. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25742. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25743. IOutputMetaData *meta = out->queryOutputMeta();
  25744. void *buf = alloca(meta->getFixedSize());
  25745. for (unsigned iteration = 0; iteration < 8; iteration++)
  25746. {
  25747. // 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)
  25748. // This should be true whether we read all, some, or none of the data.
  25749. // Should not matter if an activity is not started
  25750. if (iteration % 4 == 0)
  25751. activity->onCreate(NULL);
  25752. unsigned count = 0;
  25753. if (iteration % 4 != 3)
  25754. {
  25755. activity->start(0, NULL, false);
  25756. ASSERT(in.state == TestInput::STATEstarted);
  25757. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25758. for (;;)
  25759. {
  25760. const void *next = outStream->nextRow();
  25761. if (!next)
  25762. {
  25763. ASSERT(output[count++] == NULL);
  25764. next = outStream->nextRow();
  25765. if (!next)
  25766. {
  25767. ASSERT(output[count++] == NULL);
  25768. break;
  25769. }
  25770. }
  25771. ASSERT(output[count] != NULL);
  25772. unsigned outsize = meta->getRecordSize(next);
  25773. memset(buf, 0, outsize);
  25774. strncpy((char *) buf, output[count++], outsize);
  25775. ASSERT(memcmp(next, buf, outsize) == 0);
  25776. ReleaseRoxieRow(next);
  25777. if (iteration % 4 == 2)
  25778. break;
  25779. }
  25780. if (iteration % 4 != 2)
  25781. {
  25782. // Check that reading after end is harmless
  25783. in.allRead = true;
  25784. const void *next = outStream->nextRow();
  25785. ASSERT(next == NULL);
  25786. }
  25787. }
  25788. activity->stop();
  25789. ASSERT(in.state == TestInput::STATEstopped);
  25790. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25791. activity->reset();
  25792. ASSERT(in.state == TestInput::STATEreset);
  25793. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25794. ctx->queryRowManager().reportLeaks();
  25795. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25796. }
  25797. }
  25798. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25799. {
  25800. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25801. TestInput in(ctx, input);
  25802. in.repeat = repeat;
  25803. activity->setInput(0, 0, &in);
  25804. ArrayOf<IFinalRoxieInput *> out;
  25805. for (unsigned i = 0; i < numOutputs; i++)
  25806. {
  25807. out.append(activity->queryOutput(i));
  25808. }
  25809. activity->onCreate(NULL);
  25810. class casyncfor: public CAsyncFor
  25811. {
  25812. public:
  25813. casyncfor(ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_output, unsigned _repeat)
  25814. : outputs(_outputs), output(_output), repeat(_repeat)
  25815. {}
  25816. void Do(unsigned i)
  25817. {
  25818. IFinalRoxieInput *out = outputs.item(i);
  25819. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25820. out->start(0, NULL, false);
  25821. IOutputMetaData *meta = out->queryOutputMeta();
  25822. void *buf = alloca(meta->getFixedSize());
  25823. unsigned count = 0;
  25824. unsigned repeats = repeat;
  25825. for (;;)
  25826. {
  25827. const void *next = outStream->nextRow();
  25828. if (!next)
  25829. {
  25830. ASSERT(repeats==0);
  25831. ASSERT(output[count] == NULL);
  25832. count++;
  25833. next = outStream->nextRow();
  25834. if (!next)
  25835. {
  25836. ASSERT(output[count] == NULL);
  25837. count++;
  25838. break;
  25839. }
  25840. }
  25841. if (output[count] == NULL && repeats)
  25842. {
  25843. repeats--;
  25844. count = 0;
  25845. }
  25846. ASSERT(output[count] != NULL);
  25847. unsigned outsize = meta->getRecordSize(next);
  25848. memset(buf, 0, outsize);
  25849. strncpy((char *) buf, output[count++], outsize);
  25850. ASSERT(memcmp(next, buf, outsize) == 0);
  25851. ReleaseRoxieRow(next);
  25852. }
  25853. outStream->stop();
  25854. }
  25855. private:
  25856. ArrayOf<IFinalRoxieInput *> &outputs;
  25857. char const * const *output;
  25858. unsigned repeat;
  25859. } afor(out, output, repeat);
  25860. afor.For(numOutputs, numOutputs);
  25861. ASSERT(in.state == TestInput::STATEstopped);
  25862. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25863. {
  25864. out.item(i2)->reset();
  25865. }
  25866. ASSERT(in.state == TestInput::STATEreset);
  25867. ctx->queryRowManager().reportLeaks();
  25868. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25869. }
  25870. static int compareFunc(const void *l, const void *r)
  25871. {
  25872. return strcmp(*(char **) l, *(char **) r);
  25873. }
  25874. void testSort(unsigned type)
  25875. {
  25876. init();
  25877. sortAlgorithm = NULL;
  25878. if (type==2)
  25879. sortAlgorithm = "heapSort";
  25880. else
  25881. sortAlgorithm = "quickSort";
  25882. DBGLOG("Testing %s activity", sortAlgorithm);
  25883. Owned<IPropertyTree> dummyNode = createPTree("node");
  25884. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25885. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25886. const char * test[] = { NULL, NULL };
  25887. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25888. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25889. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25890. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25891. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25892. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25893. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25894. testActivity(activity, test, test);
  25895. testActivity(activity, test12345, test12345);
  25896. testActivity(activity, test54321, test12345);
  25897. testActivity(activity, test11111, test11111);
  25898. testActivity(activity, test11111_12345, test11111_12345);
  25899. testActivity(activity, test11111_54321, test11111_12345);
  25900. testActivity(activity, test54321_54321, test12345_12345);
  25901. // A few larger tests
  25902. char *input[2002];
  25903. char *output[2002];
  25904. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25905. unsigned i;
  25906. // identical
  25907. for (i=0; i<2000; i++)
  25908. {
  25909. input[i] = new char[11];
  25910. output[i] = new char[11];
  25911. sprintf(input[i], "1");
  25912. sprintf(output[i], "1");
  25913. }
  25914. testActivity(activity, input, output);
  25915. // Ascending
  25916. for (i=0; i<2000; i++)
  25917. {
  25918. sprintf(input[i], "%04d", i);
  25919. sprintf(output[i], "%04d", i);
  25920. }
  25921. testActivity(activity, input, output);
  25922. // Almost sorted
  25923. for (i=0; i<20; i++)
  25924. {
  25925. unsigned h = i*100;
  25926. sprintf(input[h], "%04d", 1900-h);
  25927. }
  25928. testActivity(activity, input, output);
  25929. // Descending
  25930. for (i=0; i<2000; i++)
  25931. {
  25932. sprintf(input[i], "%04d", 1999-i);
  25933. sprintf(output[i], "%04d", i);
  25934. }
  25935. testActivity(activity, input, output);
  25936. // Random
  25937. for (i=0; i<2000; i++)
  25938. {
  25939. unsigned r = fastRand() % 1500;
  25940. sprintf(input[i], "%04d", r);
  25941. sprintf(output[i], "%04d", r);
  25942. }
  25943. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25944. testActivity(activity, input, output);
  25945. unsigned __int64 us = factory->queryLocalTimeNs();
  25946. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25947. factory->resetNodeProgressInfo();
  25948. if (type)
  25949. {
  25950. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25951. // All sort identical
  25952. for (i=0; i<2000; i++)
  25953. {
  25954. sprintf(input[i], "1 %d", i);
  25955. sprintf(output[i], "1 %d", i);
  25956. }
  25957. testActivity(activity, input, output);
  25958. // Already sorted
  25959. for (i=0; i<2000; i++)
  25960. {
  25961. sprintf(input[i], "%04d %d", i / 10, i);
  25962. sprintf(output[i], "%04d %d", i / 10, i);
  25963. }
  25964. testActivity(activity, input, output);
  25965. // Reverse order
  25966. for (i=0; i<2000; i++)
  25967. {
  25968. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25969. sprintf(output[i], "%04d %d", i / 10, i%10);
  25970. }
  25971. testActivity(activity, input, output);
  25972. }
  25973. for (i=0; i<2000; i++)
  25974. {
  25975. delete [] input[i];
  25976. delete [] output[i];
  25977. }
  25978. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25979. }
  25980. void testQuickSort()
  25981. {
  25982. testSort(0);
  25983. }
  25984. void testHeapSort()
  25985. {
  25986. testSort(2);
  25987. }
  25988. void testMerge()
  25989. {
  25990. DBGLOG("testMerge");
  25991. init();
  25992. Owned<IPropertyTree> splitterNode = createPTree();
  25993. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25994. factory->setInput(0,0,0);
  25995. factory->setInput(1,0,0);
  25996. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25997. const char * test[] = { NULL, NULL };
  25998. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25999. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  26000. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  26001. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  26002. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  26003. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  26004. 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 };
  26005. testActivity(activity, test, test, test);
  26006. testActivity(activity, test12345, test, test12345);
  26007. testActivity(activity, test, test12345, test12345);
  26008. testActivity(activity, test12345, test12345, test1122334455);
  26009. testActivity(activity, test11111, test, test11111);
  26010. testActivity(activity, test, test11111, test11111);
  26011. testActivity(activity, test11111, test11111, test1111111111);
  26012. testActivity(activity, test11111_12345, test, test1111112345);
  26013. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  26014. // Should really test WHICH side gets kept...
  26015. // Should test with more than 2 inputs...
  26016. DBGLOG("testMerge done");
  26017. }
  26018. void testMergeDedup()
  26019. {
  26020. DBGLOG("testMergeDedup");
  26021. init();
  26022. MergeActivityTest::isDedup = true;
  26023. Owned<IPropertyTree> splitterNode = createPTree();
  26024. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  26025. factory->setInput(0,0,0);
  26026. factory->setInput(1,0,0);
  26027. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  26028. const char * test[] = { NULL, NULL };
  26029. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  26030. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  26031. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  26032. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  26033. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  26034. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  26035. testActivity(activity, test, test11111, test11111);
  26036. testActivity(activity, test, test, test);
  26037. testActivity(activity, test12345, test, test12345);
  26038. testActivity(activity, test, test12345, test12345);
  26039. testActivity(activity, test12345, test12345, test12345);
  26040. testActivity(activity, test11111_12345, test, test1111112345);
  26041. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  26042. // Should really test WHICH side gets kept...
  26043. // Should test with more than 2 inputs...
  26044. DBGLOG("testMergeDedup done");
  26045. }
  26046. void doTestSplitter(unsigned numOutputs)
  26047. {
  26048. DBGLOG("testSplit %d", numOutputs);
  26049. init();
  26050. Owned<IPropertyTree> splitterNode = createPTree();
  26051. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  26052. factory->setInput(0,0,0);
  26053. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  26054. const char * test[] = { NULL, NULL };
  26055. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  26056. unsigned start = msTick();
  26057. testSplitActivity(factory, test, test, numOutputs, 0);
  26058. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  26059. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  26060. unsigned elapsed = msTick() - start;
  26061. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  26062. }
  26063. void testSplitter()
  26064. {
  26065. doTestSplitter(1);
  26066. doTestSplitter(2);
  26067. doTestSplitter(3);
  26068. doTestSplitter(10);
  26069. }
  26070. void testMiscellaneous()
  26071. {
  26072. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  26073. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  26074. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  26075. ASSERT(sizeof(CJoinGroup) <= 120);
  26076. }
  26077. };
  26078. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  26079. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  26080. #endif