ccdserver.cpp 1005 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629
  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. #pragma warning(disable : 4355)
  69. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  70. #define PROBE
  71. #ifdef _DEBUG
  72. //#define FAKE_EXCEPTIONS
  73. //#define TRACE_JOINGROUPS
  74. //#define TRACE_SPLIT
  75. //#define _CHECK_HEAPSORT
  76. //#undef PARALLEL_EXECUTE
  77. //#define TRACE_SEEK_REQUESTS
  78. #endif
  79. using roxiemem::OwnedRoxieRow;
  80. using roxiemem::OwnedRoxieString;
  81. using roxiemem::OwnedConstRoxieRow;
  82. using roxiemem::IRowManager;
  83. using roxiemem::ReleaseRoxieRows;
  84. // 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...
  85. #if _MSC_VER==1200
  86. #define protected public
  87. #endif
  88. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  89. #define TRACE_STRANDS
  90. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  91. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  92. //=================================================================================
  93. class RestartableThread : public CInterface
  94. {
  95. class MyThread : public Thread
  96. {
  97. Linked<RestartableThread> owner;
  98. public:
  99. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  100. {
  101. }
  102. virtual int run()
  103. {
  104. owner->started.signal();
  105. return owner->run();
  106. }
  107. };
  108. friend class MyThread;
  109. Semaphore started;
  110. Owned<MyThread> thread;
  111. CriticalSection crit;
  112. StringAttr name;
  113. public:
  114. RestartableThread(const char *_name) : name(_name)
  115. {
  116. }
  117. virtual void start(const char *namePrefix)
  118. {
  119. StringBuffer s(namePrefix);
  120. s.append(name);
  121. {
  122. CriticalBlock b(crit);
  123. assertex(!thread);
  124. thread.setown(new MyThread(this, s));
  125. thread->start();
  126. }
  127. started.wait();
  128. }
  129. virtual void join()
  130. {
  131. {
  132. Owned<Thread> tthread;
  133. {
  134. CriticalBlock b(crit);
  135. tthread.setown(thread.getClear());
  136. }
  137. if (tthread)
  138. tthread->join();
  139. }
  140. }
  141. virtual int run() = 0;
  142. };
  143. //================================================================================
  144. //The following don't link their arguments because that creates a circular reference
  145. //But I wish there was a better way
  146. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  147. {
  148. public:
  149. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  150. IMPLEMENT_IINTERFACE
  151. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  152. virtual ICodeContext *queryCodeContext()
  153. {
  154. return ctx->queryCodeContext();
  155. }
  156. virtual void checkAbort()
  157. {
  158. ctx->checkAbort();
  159. }
  160. virtual void notifyAbort(IException *E)
  161. {
  162. ctx->notifyAbort(E);
  163. }
  164. virtual IActivityGraph * queryChildGraph(unsigned id)
  165. {
  166. return ctx->queryChildGraph(id);
  167. }
  168. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  169. {
  170. ctx->noteChildGraph(id, childGraph) ;
  171. }
  172. virtual IRowManager &queryRowManager()
  173. {
  174. return ctx->queryRowManager();
  175. }
  176. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  177. {
  178. ctx->noteStatistic(kind, value);
  179. }
  180. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  181. {
  182. ctx->mergeStats(from);
  183. }
  184. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  185. {
  186. ctx->gatherStats(merged);
  187. }
  188. virtual bool collectingDetailedStatistics() const
  189. {
  190. return ctx->collectingDetailedStatistics();
  191. }
  192. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  193. {
  194. ctx->CTXLOGva(format, args);
  195. }
  196. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  197. {
  198. ctx->CTXLOGa(category, prefix, text);
  199. }
  200. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  201. {
  202. ctx->logOperatorExceptionVA(E, file, line, format, args);
  203. }
  204. 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)))
  205. {
  206. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  207. }
  208. virtual void CTXLOGl(LogItem *log) const
  209. {
  210. ctx->CTXLOGl(log);
  211. }
  212. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  213. {
  214. return ctx->getLogPrefix(ret);
  215. }
  216. virtual unsigned queryTraceLevel() const
  217. {
  218. return ctx->queryTraceLevel();
  219. }
  220. virtual bool isIntercepted() const
  221. {
  222. return ctx->isIntercepted();
  223. }
  224. virtual bool isBlind() const
  225. {
  226. return ctx->isBlind();
  227. }
  228. virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid)
  229. {
  230. ctx->setGlobalId(id, ep, pid);
  231. }
  232. virtual const char *queryGlobalId() const
  233. {
  234. return ctx->queryGlobalId();
  235. }
  236. virtual const char *queryLocalId() const
  237. {
  238. return ctx->queryLocalId();
  239. }
  240. virtual void setHttpIdHeaders(const char *global, const char *caller)
  241. {
  242. ctx->setHttpIdHeaders(global, caller);
  243. }
  244. virtual const char *queryGlobalIdHttpHeader() const
  245. {
  246. return ctx->queryGlobalIdHttpHeader();
  247. }
  248. virtual const char *queryCallerIdHttpHeader() const
  249. {
  250. return ctx->queryCallerIdHttpHeader();
  251. }
  252. virtual const QueryOptions &queryOptions() const
  253. {
  254. return ctx->queryOptions();
  255. }
  256. virtual void addSlavesReplyLen(unsigned len)
  257. {
  258. ctx->addSlavesReplyLen(len);
  259. }
  260. virtual const char *queryAuthToken()
  261. {
  262. return ctx->queryAuthToken();
  263. }
  264. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  265. {
  266. return ctx->resolveLFN(filename, isOpt);
  267. }
  268. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  269. {
  270. return ctx->createLFN(filename, overwrite, extend, clusters);
  271. }
  272. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  273. {
  274. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  275. }
  276. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  277. {
  278. return ctx->getLibraryGraph(extra, parentActivity);
  279. }
  280. virtual IProbeManager *queryProbeManager() const
  281. {
  282. return ctx->queryProbeManager();
  283. }
  284. virtual IDebuggableContext *queryDebugContext() const
  285. {
  286. return ctx->queryDebugContext();
  287. }
  288. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  289. {
  290. ctx->printResults(output, name, sequence);
  291. }
  292. virtual void setWUState(WUState state)
  293. {
  294. ctx->setWUState(state);
  295. }
  296. virtual bool checkWuAborted()
  297. {
  298. return ctx->checkWuAborted();
  299. }
  300. virtual IWorkUnit *updateWorkUnit() const
  301. {
  302. return ctx->updateWorkUnit();
  303. }
  304. virtual IConstWorkUnit *queryWorkUnit() const
  305. {
  306. return ctx->queryWorkUnit();
  307. }
  308. virtual IRoxieServerContext *queryServerContext()
  309. {
  310. return ctx->queryServerContext();
  311. }
  312. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  313. {
  314. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  315. }
  316. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  317. {
  318. return ctx->getRowAllocatorEx(meta, activityId, flags);
  319. }
  320. protected:
  321. IRoxieSlaveContext * ctx;
  322. };
  323. //=================================================================================
  324. #define RESULT_FLUSH_THRESHOLD 10000u
  325. #ifdef _DEBUG
  326. #define SOAP_SPLIT_THRESHOLD 100u
  327. #define SOAP_SPLIT_RESERVE 200u
  328. #else
  329. #define SOAP_SPLIT_THRESHOLD 64000u
  330. #define SOAP_SPLIT_RESERVE 65535u
  331. #endif
  332. //=================================================================================
  333. // General activity statistics
  334. static const StatisticsMapping actStatistics({StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  335. StNumRowsProcessed, StNumSlaves, StNumStarts, StNumStops, StNumStrands,
  336. StNumScansPerRow, StNumAllocations, StNumAllocationScans,
  337. StTimeFirstExecute, StCycleLocalExecuteCycles, StCycleTotalExecuteCycles});
  338. static const StatisticsMapping joinStatistics(&actStatistics, {StNumAtmostTriggered});
  339. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, { StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  340. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  341. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  342. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  343. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  344. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  345. StNumDiskRejected});
  346. static const StatisticsMapping indexStatistics(&actStatistics, {StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  347. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  348. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  349. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  350. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  351. StNumIndexRowsRead});
  352. static const StatisticsMapping diskStatistics(&actStatistics, {StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  353. StNumDiskRejected });
  354. static const StatisticsMapping soapStatistics(&actStatistics, { StTimeSoapcall });
  355. static const StatisticsMapping groupStatistics(&actStatistics, { StNumGroups, StNumGroupMax });
  356. static const StatisticsMapping sortStatistics(&actStatistics, { StTimeSortElapsed });
  357. static const StatisticsMapping indexWriteStatistics(&actStatistics, { StNumDuplicateKeys });
  358. //=================================================================================
  359. const static unsigned minus1U = (0U-1U);
  360. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  361. {
  362. protected:
  363. IntArray dependencies; // things I am dependent on
  364. IntArray dependencyIndexes; // things I am dependent on
  365. IntArray dependencyControlIds; // things I am dependent on
  366. StringArray dependencyEdgeIds; // How to describe them to the debugger
  367. unsigned dependentCount; // things dependent on me
  368. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  369. bool optStableInput = true; // is the input forced to ordered?
  370. bool optUnstableInput = false; // is the input forced to unordered?
  371. bool optUnordered = false; // is the output specified as unordered?
  372. unsigned heapFlags;
  373. mutable RelaxedAtomic<__int64> processed = {0};
  374. mutable RelaxedAtomic<__int64> started = {0};
  375. public:
  376. IMPLEMENT_IINTERFACE;
  377. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  378. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  379. {
  380. dependentCount = 0;
  381. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  382. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  383. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  384. }
  385. ~CRoxieServerActivityFactoryBase()
  386. {
  387. }
  388. StringBuffer &toString(StringBuffer &ret) const
  389. {
  390. return ret.appendf("%p", this);
  391. }
  392. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  393. {
  394. dependencies.append(_source);
  395. dependencyIndexes.append(_sourceIdx);
  396. dependencyControlIds.append(controlId);
  397. dependencyEdgeIds.append(edgeId);
  398. }
  399. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  400. {
  401. if (optStableInput)
  402. return true;
  403. if (optUnstableInput)
  404. return false;
  405. if (optUnordered)
  406. return false;
  407. return consumerOrdered;
  408. }
  409. virtual void noteDependent(unsigned target)
  410. {
  411. dependentCount++;
  412. }
  413. virtual IntArray &queryDependencies() { return dependencies; }
  414. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  415. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  416. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  417. virtual unsigned queryId() const { return id; }
  418. virtual unsigned querySubgraphId() const { return subgraphId; }
  419. virtual ThorActivityKind getKind() const { return kind; }
  420. virtual IOutputMetaData * queryOutputMeta() const
  421. {
  422. return meta;
  423. }
  424. virtual bool isSink() const
  425. {
  426. return false;
  427. }
  428. virtual bool isFunction() const
  429. {
  430. return false;
  431. }
  432. virtual bool isGraphInvariant() const
  433. {
  434. return false;
  435. }
  436. virtual IHThorArg &getHelper() const
  437. {
  438. return *helperFactory();
  439. }
  440. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  441. {
  442. arg.Release();
  443. throwUnexpected();
  444. }
  445. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  446. {
  447. CActivityFactory::mergeStats(from);
  448. }
  449. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  450. {
  451. dbgassertex(!_idx);
  452. if (likely(_processed))
  453. processed += _processed;
  454. }
  455. virtual void noteStarted() const
  456. {
  457. started++;
  458. }
  459. virtual void noteStarted(unsigned idx) const
  460. {
  461. throwUnexpected(); // should be implemented/required by multiOutput cases only
  462. }
  463. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  464. {
  465. if (output == 0)
  466. {
  467. putStatsValue(&edge, "NumRowsProcessed", "sum", processed);
  468. auto _started = started.load();
  469. if (_started)
  470. putStatsValue(&edge, "NumStarts", "sum", _started);
  471. }
  472. else
  473. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  474. }
  475. virtual void getNodeProgressInfo(IPropertyTree &node) const
  476. {
  477. CActivityFactory::getNodeProgressInfo(node);
  478. auto _started = started.load();
  479. if (_started)
  480. putStatsValue(&node, "_roxieStarted", "sum", _started);
  481. }
  482. virtual void resetNodeProgressInfo()
  483. {
  484. CActivityFactory::resetNodeProgressInfo();
  485. processed = 0;
  486. started = 0;
  487. }
  488. virtual void getActivityMetrics(StringBuffer &reply) const
  489. {
  490. CActivityFactory::getActivityMetrics(reply);
  491. putStatsValue(reply, "NumStarts", "sum", started);
  492. CriticalBlock b(statsCrit);
  493. putStatsValue(reply, "TimeTotalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeTotalExecute)/1000));
  494. putStatsValue(reply, "TimeLocalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeLocalExecute)/1000));
  495. }
  496. virtual unsigned __int64 queryLocalTimeNs() const
  497. {
  498. return mystats.getSerialStatisticValue(StTimeLocalExecute);
  499. }
  500. virtual IQueryFactory &queryQueryFactory() const
  501. {
  502. return CActivityFactory::queryQueryFactory();
  503. }
  504. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  505. {
  506. return CActivityFactory::queryChildQuery(idx, id);
  507. }
  508. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  509. {
  510. CActivityFactory::addChildQuery(id, childQuery);
  511. }
  512. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  513. {
  514. ForEachItemIn(idx, childQueries)
  515. {
  516. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  517. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  518. childGraphs.item(idx).onCreate(colocalArg);
  519. }
  520. }
  521. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  522. {
  523. unsigned match = childQueryIndexes.find(childId);
  524. assertex(match != NotFound);
  525. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  526. graph->onCreate(colocalArg);
  527. return graph.getClear();
  528. }
  529. virtual IRoxieServerSideCache *queryServerSideCache() const
  530. {
  531. return NULL; // Activities that wish to support server-side caching will need to do better....
  532. }
  533. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  534. {
  535. // Most activities have nothing to say...
  536. }
  537. virtual const StatisticsMapping &queryStatsMapping() const
  538. {
  539. return actStatistics; // Overridden by anyone that needs more
  540. }
  541. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  542. {
  543. return (roxiemem::RoxieHeapFlags)heapFlags;
  544. }
  545. };
  546. class CRoxieServerMultiInputInfo
  547. {
  548. private:
  549. UnsignedArray inputs;
  550. UnsignedArray inputIndexes;
  551. public:
  552. void set(unsigned idx, unsigned source, unsigned sourceidx)
  553. {
  554. if (idx==inputs.length())
  555. {
  556. inputs.append(source);
  557. inputIndexes.append(sourceidx);
  558. }
  559. else
  560. {
  561. while (!inputs.isItem(idx))
  562. {
  563. inputs.append(0);
  564. inputIndexes.append(0);
  565. }
  566. inputs.replace(source, idx);
  567. inputIndexes.replace(sourceidx, idx);
  568. }
  569. }
  570. unsigned get(unsigned idx, unsigned &sourceidx) const
  571. {
  572. if (inputs.isItem(idx))
  573. {
  574. sourceidx = inputIndexes.item(idx);
  575. return inputs.item(idx);
  576. }
  577. else
  578. return (unsigned) -1;
  579. }
  580. inline unsigned ordinality() const { return inputs.ordinality(); }
  581. };
  582. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  583. {
  584. private:
  585. CRoxieServerMultiInputInfo inputs;
  586. public:
  587. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  588. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  589. {
  590. }
  591. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  592. {
  593. inputs.set(idx, source, sourceidx);
  594. }
  595. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  596. {
  597. return inputs.get(idx, sourceidx);
  598. }
  599. virtual unsigned numInputs() const { return inputs.ordinality(); }
  600. };
  601. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  602. {
  603. Owned<IException> wrapped;
  604. ThorActivityKind kind;
  605. unsigned queryId;
  606. public:
  607. IMPLEMENT_IINTERFACE;
  608. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  609. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  610. {
  611. }
  612. virtual int errorCode() const { return wrapped->errorCode(); }
  613. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  614. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  615. };
  616. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  617. {
  618. protected:
  619. unsigned input;
  620. unsigned inputidx;
  621. public:
  622. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  623. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  624. {
  625. input = (unsigned) -1;
  626. inputidx = 0;
  627. }
  628. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  629. {
  630. if (idx != 0)
  631. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  632. if (input != -1)
  633. 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__);
  634. input = source;
  635. inputidx = sourceidx;
  636. }
  637. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  638. {
  639. if (!idx)
  640. {
  641. sourceidx = inputidx;
  642. return input;
  643. }
  644. return (unsigned) -1;
  645. }
  646. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  647. };
  648. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  649. {
  650. protected:
  651. unsigned numOutputs = 0;
  652. RelaxedAtomic<__int64> *processedArray = nullptr;
  653. RelaxedAtomic<__int64> *startedArray = nullptr;
  654. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  655. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  656. {
  657. }
  658. ~CRoxieServerMultiOutputFactory()
  659. {
  660. delete [] processedArray;
  661. delete [] startedArray;
  662. }
  663. void setNumOutputs(unsigned num)
  664. {
  665. numOutputs = num;
  666. if (!num)
  667. num = 1; // Even sink activities like to track how many records they process
  668. processedArray = new RelaxedAtomic<__int64>[num];
  669. startedArray = new RelaxedAtomic<__int64>[num];
  670. for (unsigned i = 0; i < num; i++)
  671. {
  672. processedArray[i] = 0;
  673. startedArray[i] = 0;
  674. }
  675. }
  676. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  677. {
  678. assertex(numOutputs ? idx < numOutputs : idx==0);
  679. putStatsValue(&edge, "NumRowsProcessed", "sum", processedArray[idx]);
  680. putStatsValue(&edge, "NumStarts", "sum", startedArray[idx]);
  681. }
  682. virtual void resetNodeProgressInfo()
  683. {
  684. CRoxieServerActivityFactory::resetNodeProgressInfo();
  685. for (unsigned i = 0; i < numOutputs; i++)
  686. {
  687. processedArray[i] = 0;
  688. startedArray[i] = 0;
  689. }
  690. }
  691. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  692. {
  693. assertex(numOutputs ? idx < numOutputs : idx==0);
  694. processedArray[idx] += _processed;
  695. }
  696. virtual void noteStarted(unsigned idx) const
  697. {
  698. assertex(numOutputs ? idx < numOutputs : idx==0);
  699. startedArray[idx]++;
  700. }
  701. };
  702. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  703. {
  704. protected:
  705. bool isInternal;
  706. bool isRoot;
  707. unsigned usageCount;
  708. public:
  709. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  710. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  711. {
  712. usageCount = _usageCount;
  713. isRoot = _isRoot;
  714. isInternal = false; // filled in by derived class constructor
  715. }
  716. virtual bool isSink() const
  717. {
  718. //only a sink if a root activity
  719. return isRoot && !(isInternal && dependentCount && dependentCount==usageCount); // MORE - it's possible for this to get the answer wrong still, since usageCount does not include references from main procedure. Gavin?
  720. }
  721. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  722. {
  723. // 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
  724. // Just leave it blank is safest.
  725. }
  726. };
  727. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  728. const char *queryStateText(activityState state)
  729. {
  730. switch (state)
  731. {
  732. case STATEreset: return "reset";
  733. case STATEstarted: return "started";
  734. case STATEstopped: return "stopped";
  735. case STATEstarting: return "starting";
  736. default: return "unknown";
  737. }
  738. }
  739. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  740. class CParallelActivityExecutor : public CAsyncFor
  741. {
  742. public:
  743. unsigned parentExtractSize;
  744. const byte * parentExtract;
  745. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  746. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  747. void Do(unsigned i)
  748. {
  749. activities.item(i).execute(parentExtractSize, parentExtract);
  750. }
  751. private:
  752. IRoxieServerActivityCopyArray & activities;
  753. };
  754. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  755. {
  756. if (instreams.length() != 1)
  757. {
  758. assertex(instreams.length());
  759. if (!junction)
  760. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  761. ForEachItemIn(stream, instreams)
  762. {
  763. junction->setInput(stream, instreams.item(stream));
  764. }
  765. return junction->queryOutput(0);
  766. }
  767. else
  768. return instreams.item(0);
  769. }
  770. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  771. {
  772. if (input)
  773. {
  774. PointerArrayOf<IEngineRowStream> instreams;
  775. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  776. return ensureSingleStream(ctx, instreams, junction);
  777. }
  778. else
  779. return NULL;
  780. }
  781. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  782. {
  783. Owned<IStrandJunction> junction;
  784. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  785. assertex(!junction);
  786. return result;
  787. }
  788. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  789. {
  790. friend class StrandProcessor;
  791. protected:
  792. IFinalRoxieInput *input;
  793. unsigned sourceIdx;
  794. IEngineRowStream *inputStream;
  795. Owned<IStrandJunction> junction;
  796. IHThorArg &basehelper;
  797. IRoxieSlaveContext *ctx;
  798. class InterceptRegisterTimer : public IndirectCodeContext
  799. {
  800. public:
  801. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  802. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  803. {
  804. if (activityId == activity.queryId())
  805. return activity.registerTimer(activityId, name);
  806. else
  807. return ctx->registerTimer(activityId, name);
  808. }
  809. private:
  810. CRoxieServerActivity &activity;
  811. } interceptedCtx;
  812. const IRoxieServerActivityFactory *factory;
  813. IRoxieServerActivityCopyArray dependencies;
  814. IntArray dependencyIndexes;
  815. IntArray dependencyControlIds;
  816. IArrayOf<IActivityGraph> childGraphs;
  817. CachedOutputMetaData meta;
  818. IHThorArg *colocalParent;
  819. IEngineRowAllocator *rowAllocator;
  820. CriticalSection statecrit;
  821. CriticalSection statscrit;
  822. mutable CRuntimeStatisticCollection stats;
  823. MapStringToMyClass<ThorSectionTimer> functionTimers;
  824. ActivityTimeAccumulator totalCycles;
  825. IProbeManager *probeManager = NULL;
  826. unsigned processed;
  827. unsigned numStarts = 0;
  828. unsigned activityId;
  829. activityState state;
  830. bool createPending;
  831. bool debugging;
  832. bool timeActivities;
  833. bool aborted;
  834. bool connected = false;
  835. bool collectFactoryStatistics = false;
  836. public:
  837. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  838. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  839. : ctx(_ctx),
  840. interceptedCtx(*this),
  841. factory(_factory),
  842. basehelper(_factory->getHelper()),
  843. activityId(_factory->queryId()),
  844. stats(_factory->queryStatsMapping()),
  845. probeManager(_probeManager)
  846. {
  847. input = NULL;
  848. sourceIdx = 0;
  849. inputStream = NULL;
  850. meta.set(basehelper.queryOutputMeta());
  851. processed = 0;
  852. state=STATEreset;
  853. rowAllocator = NULL;
  854. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  855. colocalParent = NULL;
  856. createPending = true;
  857. timeActivities = defaultTimeActivities;
  858. collectFactoryStatistics = defaultCollectFactoryStatistics && !debugging && factory;
  859. aborted = false;
  860. }
  861. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper)
  862. : ctx(_ctx),
  863. interceptedCtx(*this),
  864. factory(NULL), basehelper(_helper), stats(allStatistics)
  865. {
  866. activityId = 0;
  867. input = NULL;
  868. sourceIdx = 0;
  869. inputStream = NULL;
  870. ctx = NULL;
  871. meta.set(basehelper.queryOutputMeta());
  872. processed = 0;
  873. state=STATEreset;
  874. rowAllocator = NULL;
  875. debugging = false;
  876. colocalParent = NULL;
  877. createPending = true;
  878. timeActivities = defaultTimeActivities;
  879. collectFactoryStatistics = false; // since no factory
  880. aborted = false;
  881. }
  882. ~CRoxieServerActivity()
  883. {
  884. basehelper.Release();
  885. ::Release(rowAllocator);
  886. }
  887. virtual void beforeDispose() override
  888. {
  889. if (traceStartStop)
  890. {
  891. // There was an old comment here stating // Note- CTXLOG may not be safe
  892. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  893. // was released while activities still referenced it.
  894. // However these should now all be fixed
  895. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  896. if (watchActivityId && watchActivityId==activityId)
  897. {
  898. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  899. }
  900. }
  901. if (state!=STATEreset)
  902. {
  903. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  904. state = STATEreset; // bit pointless but there you go...
  905. }
  906. }
  907. const IResolvedFile *resolveLFNIndex(const char *filename, bool isOpt)
  908. {
  909. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  910. if (ret && !ret->isKey())
  911. throw MakeStringException(0, "Attempting to read flat file as an index: %s", filename);
  912. return ret;
  913. }
  914. const IResolvedFile *resolveLFNFlat(const char *filename, bool isOpt)
  915. {
  916. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  917. if (ret && ret->isKey())
  918. throw MakeStringException(0, "Attempting to read index as a flat file: %s", filename);
  919. return ret;
  920. }
  921. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  922. {
  923. if (!factory)
  924. return;
  925. //Collate the stats for this activity from various different sources.
  926. CRuntimeStatisticCollection mergedStats(stats.queryMapping());
  927. gatherStats(mergedStats);
  928. //Because subgraphs are flattened in roxie the subgraph needs to be selected for each activity
  929. if (statsBuilder)
  930. statsBuilder->beginSubGraphScope(factory->querySubgraphId());
  931. //Still needed even if statsBuilder is null to update values in the factory
  932. updateEdgeStats(statsBuilder);
  933. if (statsBuilder)
  934. {
  935. StatsActivityScope ac(*statsBuilder, activityId);
  936. mergedStats.recordStatistics(*statsBuilder);
  937. //close the subgraph scope from the previous if()
  938. statsBuilder->endScope();
  939. }
  940. //Update the statistics accumulated over all the queries
  941. if (collectFactoryStatistics)
  942. factory->mergeStats(mergedStats);
  943. //Updates the query summary statistics
  944. if (ctx)
  945. ctx->queryCodeContext()->queryContextLogger().mergeStats(mergedStats);
  946. ForEachItemIn(i, childGraphs)
  947. childGraphs.item(i).gatherStatistics(statsBuilder);
  948. }
  949. virtual const IRoxieContextLogger &queryLogCtx()const
  950. {
  951. return *this;
  952. }
  953. inline const StatisticsMapping & queryStatsMapping() const
  954. {
  955. return factory ? factory->queryStatsMapping() : actStatistics;
  956. }
  957. virtual bool collectingDetailedStatistics() const
  958. {
  959. return ctx && ctx->collectingDetailedStatistics();
  960. }
  961. virtual void mergeStats(MemoryBuffer &buf)
  962. {
  963. stats.deserializeMerge(buf);
  964. }
  965. virtual void mergeStats(const CRuntimeStatisticCollection & childStats)
  966. {
  967. CriticalBlock b(statscrit);
  968. stats.merge(childStats);
  969. }
  970. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  971. {
  972. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  973. ISectionTimer *timer = functionTimers.getValue(name);
  974. if (!timer)
  975. {
  976. timer = ThorSectionTimer::createTimer(stats, name);
  977. functionTimers.setValue(name, timer);
  978. timer->Release(); // Value returned is not linked
  979. }
  980. return timer;
  981. }
  982. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles)
  983. {
  984. CriticalBlock cb(statscrit);
  985. processed += strandProcessed;
  986. totalCycles.merge(strandCycles);
  987. }
  988. inline void ensureRowAllocator()
  989. {
  990. if (!rowAllocator)
  991. rowAllocator = createRowAllocator(meta.queryOriginal());
  992. }
  993. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  994. {
  995. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  996. }
  997. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  998. {
  999. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  1000. }
  1001. inline ICodeContext *queryCodeContext()
  1002. {
  1003. return ctx->queryCodeContext();
  1004. }
  1005. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  1006. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  1007. {
  1008. if (ctx)
  1009. ctx->CTXLOGa(category, prefix, text);
  1010. else
  1011. DBGLOG("[%s] %s", prefix, text);
  1012. }
  1013. 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)))
  1014. {
  1015. if (ctx)
  1016. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  1017. else
  1018. {
  1019. StringBuffer ss;
  1020. ss.appendf("[%s] ERROR", prefix);
  1021. if (E)
  1022. ss.append(": ").append(E->errorCode());
  1023. if (file)
  1024. ss.appendf(": %s(%d) ", file, line);
  1025. if (E)
  1026. E->errorMessage(ss.append(": "));
  1027. if (format)
  1028. {
  1029. ss.append(": ").valist_appendf(format, args);
  1030. }
  1031. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1032. }
  1033. }
  1034. virtual void CTXLOGl(LogItem *log) const
  1035. {
  1036. if (ctx)
  1037. ctx->CTXLOGl(log);
  1038. else
  1039. {
  1040. assert(ctx);
  1041. log->Release(); // Should never happen
  1042. }
  1043. }
  1044. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1045. {
  1046. stats.addStatistic(kind, value);
  1047. }
  1048. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1049. {
  1050. stats.merge(from);
  1051. }
  1052. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1053. {
  1054. merged.merge(stats);
  1055. if (rowAllocator)
  1056. rowAllocator->gatherStats(merged);
  1057. totalCycles.addStatistics(merged);
  1058. merged.mergeStatistic(StCycleLocalExecuteCycles, queryLocalCycles());
  1059. }
  1060. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1061. {
  1062. if (ctx)
  1063. ctx->getLogPrefix(ret);
  1064. return ret.append('@').append(activityId);
  1065. }
  1066. virtual bool isIntercepted() const
  1067. {
  1068. return ctx ? ctx->isIntercepted() : false;
  1069. }
  1070. virtual bool isBlind() const
  1071. {
  1072. return ctx ? ctx->isBlind() : blindLogging;
  1073. }
  1074. virtual unsigned queryTraceLevel() const
  1075. {
  1076. if (ctx)
  1077. return ctx->queryTraceLevel();
  1078. else
  1079. return traceLevel;
  1080. }
  1081. virtual void setGlobalId(const char *id, SocketEndpoint&ep, unsigned pid)
  1082. {
  1083. if (ctx)
  1084. ctx->setGlobalId(id, ep, pid);
  1085. }
  1086. virtual const char *queryGlobalId() const
  1087. {
  1088. return ctx ? ctx->queryGlobalId() : nullptr;
  1089. }
  1090. virtual const char *queryLocalId() const
  1091. {
  1092. return ctx ? ctx->queryLocalId() : nullptr;
  1093. }
  1094. virtual void setHttpIdHeaders(const char *global, const char *caller)
  1095. {
  1096. if (ctx)
  1097. ctx->setHttpIdHeaders(global, caller);
  1098. }
  1099. virtual const char *queryGlobalIdHttpHeader() const
  1100. {
  1101. return ctx ? ctx->queryGlobalIdHttpHeader() : "HPCC-Global-Id";
  1102. }
  1103. virtual const char *queryCallerIdHttpHeader() const
  1104. {
  1105. return ctx ? ctx->queryCallerIdHttpHeader() : "HPCC-Caller-Id";
  1106. }
  1107. virtual bool isPassThrough()
  1108. {
  1109. return false;
  1110. }
  1111. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1112. {
  1113. return ctx->resolveLFN(filename, isOpt);
  1114. }
  1115. virtual const IResolvedFile *queryVarFileInfo() const
  1116. {
  1117. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1118. return NULL;
  1119. }
  1120. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1121. {
  1122. throwUnexpected(); // should be implemented in more derived class wherever needed
  1123. }
  1124. virtual IRoxieSlaveContext *queryContext()
  1125. {
  1126. return ctx;
  1127. }
  1128. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1129. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1130. virtual IRoxieServerActivity *queryActivity() { return this; }
  1131. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1132. virtual bool needsAllocator() const { return false; }
  1133. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1134. {
  1135. colocalParent = _colocalParent;
  1136. createPending = true;
  1137. if (needsAllocator())
  1138. ensureRowAllocator();
  1139. processed = 0;
  1140. if (factory)
  1141. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1142. if (ctx)
  1143. {
  1144. timeActivities = ctx->queryOptions().timeActivities;
  1145. collectFactoryStatistics = ctx->queryOptions().collectFactoryStatistics && !debugging && factory;
  1146. }
  1147. }
  1148. virtual void onCreate(IHThorArg *_colocalParent)
  1149. {
  1150. _onCreate(_colocalParent, 1);
  1151. }
  1152. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1153. {
  1154. //This should only be called after onStart has been called on the helper
  1155. assertex(!createPending);
  1156. assertex(state==STATEstarted);
  1157. unsigned startlen = out.length();
  1158. basehelper.serializeCreateContext(out);
  1159. basehelper.serializeStartContext(out);
  1160. if (queryTraceLevel() > 10)
  1161. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1162. }
  1163. virtual void serializeExtra(MemoryBuffer &out) {}
  1164. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1165. {
  1166. CriticalBlock cb(statecrit);
  1167. if (state != STATEreset && state != STATEstarting)
  1168. {
  1169. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1170. }
  1171. state=STATEstarted;
  1172. numStarts++;
  1173. #ifdef TRACE_STARTSTOP
  1174. if (traceStartStop)
  1175. {
  1176. CTXLOG("start %p %d", this, activityId);
  1177. if (watchActivityId && watchActivityId==activityId)
  1178. {
  1179. CTXLOG("WATCH: start %p %d", this, activityId);
  1180. }
  1181. }
  1182. #endif
  1183. executeDependencies(parentExtractSize, parentExtract, 0);
  1184. if (input)
  1185. input->start(parentExtractSize, parentExtract, paused);
  1186. ensureCreated();
  1187. basehelper.onStart(parentExtract, NULL);
  1188. if (collectFactoryStatistics)
  1189. factory->noteStarted();
  1190. startJunction(junction);
  1191. }
  1192. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1193. {
  1194. //MORE: Create a filtered list and then use asyncfor
  1195. ForEachItemIn(idx, dependencies)
  1196. {
  1197. if (dependencyControlIds.item(idx) == controlId)
  1198. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1199. }
  1200. }
  1201. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1202. {
  1203. ForEachItemIn(idx, dependencies)
  1204. {
  1205. if (dependencyControlIds.item(idx) == controlId)
  1206. dependencies.item(idx).stop();
  1207. }
  1208. }
  1209. virtual unsigned __int64 queryTotalCycles() const
  1210. {
  1211. return totalCycles.totalCycles;
  1212. }
  1213. virtual unsigned __int64 queryLocalCycles() const
  1214. {
  1215. __int64 ret = totalCycles.totalCycles;
  1216. if (input) ret -= input->queryTotalCycles();
  1217. if (ret < 0)
  1218. ret = 0;
  1219. return ret;
  1220. }
  1221. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1222. {
  1223. if (idx==0)
  1224. return input;
  1225. else
  1226. return NULL;
  1227. }
  1228. inline void ensureCreated()
  1229. {
  1230. if (createPending)
  1231. {
  1232. createPending = false;
  1233. interceptedCtx.set(ctx->queryCodeContext());
  1234. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1235. }
  1236. }
  1237. virtual void stop()
  1238. {
  1239. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1240. if (state != STATEstopped)
  1241. {
  1242. CriticalBlock cb(statecrit);
  1243. if (state != STATEstopped)
  1244. {
  1245. #ifdef TRACE_STARTSTOP
  1246. if (traceStartStop)
  1247. {
  1248. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1249. if (watchActivityId && watchActivityId==activityId)
  1250. {
  1251. CTXLOG("WATCH: stop %p %d", this, activityId);
  1252. }
  1253. }
  1254. #endif
  1255. state=STATEstopped;
  1256. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1257. ForEachItemIn(idx, dependencies)
  1258. {
  1259. if (dependencyControlIds.item(idx) == 0)
  1260. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1261. }
  1262. if (inputStream)
  1263. inputStream->stop();
  1264. }
  1265. }
  1266. }
  1267. virtual void abort()
  1268. {
  1269. aborted = true;
  1270. // MORE - should abort dependencies here?
  1271. stop();
  1272. }
  1273. inline void reset()
  1274. {
  1275. if (state != STATEreset)
  1276. {
  1277. CriticalBlock cb(statecrit);
  1278. if (state != STATEreset)
  1279. {
  1280. if (state==STATEstarted || state==STATEstarting)
  1281. {
  1282. if (ctx->queryOptions().failOnLeaks)
  1283. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1284. if (traceStartStop || traceLevel > 2)
  1285. CTXLOG("STATE: activity %d reset without stop", activityId);
  1286. stop();
  1287. }
  1288. state = STATEreset;
  1289. #ifdef TRACE_STARTSTOP
  1290. if (traceStartStop)
  1291. {
  1292. CTXLOG("reset %p %d", this, activityId);
  1293. if (watchActivityId && watchActivityId==activityId)
  1294. {
  1295. CTXLOG("WATCH: reset %p %d", this, activityId);
  1296. }
  1297. }
  1298. #endif
  1299. resetJunction(junction);
  1300. ForEachItemIn(idx, dependencies)
  1301. dependencies.item(idx).reset();
  1302. if (input)
  1303. input->reset();
  1304. }
  1305. }
  1306. aborted = false;
  1307. }
  1308. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1309. {
  1310. dependencies.append(source);
  1311. dependencyIndexes.append(sourceIdx);
  1312. dependencyControlIds.append(controlId);
  1313. }
  1314. virtual void resetEOF()
  1315. {
  1316. //would make more sense if the default implementation (and eof member) were in the base class
  1317. }
  1318. // Sink activities should override this....
  1319. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1320. {
  1321. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1322. }
  1323. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1324. {
  1325. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1326. }
  1327. virtual void stopSink(unsigned idx)
  1328. {
  1329. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1330. }
  1331. virtual void connectInputStreams(bool consumerOrdered)
  1332. {
  1333. if (input && !inputStream)
  1334. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1335. if (!connected)
  1336. {
  1337. connectDependencies();
  1338. connected = true;
  1339. }
  1340. }
  1341. void connectDependencies()
  1342. {
  1343. ForEachItemIn(i, dependencies)
  1344. dependencies.item(i).connectInputStreams(true);
  1345. }
  1346. virtual __int64 evaluate()
  1347. {
  1348. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1349. }
  1350. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1351. {
  1352. return NULL;
  1353. }
  1354. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1355. {
  1356. return false;
  1357. }
  1358. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1359. {
  1360. assertex(!idx);
  1361. input = _in;
  1362. sourceIdx = _sourceIdx;
  1363. inputStream = NULL;
  1364. }
  1365. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1366. {
  1367. if (!factory)
  1368. return true;
  1369. //Grouping implies the stream processing must be ordered - I think this always applies
  1370. IFinalRoxieInput * curInput = queryInput(idx);
  1371. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1372. return true;
  1373. return factory->isInputOrdered(consumerOrdered, idx);
  1374. }
  1375. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1376. {
  1377. assertex(!idx);
  1378. // By default, activities are assumed NOT to support streams
  1379. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1380. connectInputStreams(inputOrdered);
  1381. // Return a single stream
  1382. streams.append(this);
  1383. return NULL;
  1384. }
  1385. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1386. {
  1387. if (idx == (unsigned) -1)
  1388. idx = 0;
  1389. return idx ? NULL : this;
  1390. }
  1391. virtual IOutputMetaData *queryOutputMeta() const
  1392. {
  1393. return meta.queryOriginal();
  1394. }
  1395. virtual unsigned queryId() const
  1396. {
  1397. return activityId;
  1398. }
  1399. virtual unsigned querySubgraphId() const
  1400. {
  1401. return factory->querySubgraphId();
  1402. }
  1403. virtual void checkAbort()
  1404. {
  1405. ctx->checkAbort();
  1406. }
  1407. IException *makeWrappedException(IException *e)
  1408. {
  1409. StringBuffer msg;
  1410. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1411. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1412. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1413. return e;
  1414. else
  1415. return new CWrappedException(e, activityKind, activityId);
  1416. }
  1417. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1418. {
  1419. }
  1420. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1421. {
  1422. }
  1423. virtual void resetOutputsUsed()
  1424. {
  1425. }
  1426. virtual void noteOutputUsed()
  1427. {
  1428. }
  1429. virtual IRoxieServerSideCache *queryServerSideCache() const
  1430. {
  1431. return factory->queryServerSideCache();
  1432. }
  1433. virtual const IRoxieServerActivityFactory *queryFactory() const
  1434. {
  1435. return factory;
  1436. }
  1437. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1438. {
  1439. addEdgeStats(statsBuilder, 0, numStarts, processed, 1);
  1440. }
  1441. inline ThorActivityKind getKind() const
  1442. {
  1443. return factory->getKind();
  1444. }
  1445. inline bool isSink() const
  1446. {
  1447. return (factory != NULL) && factory->isSink();
  1448. }
  1449. void addEdgeStats(IStatisticGatherer * statsBuilder, unsigned oid, unsigned starts, unsigned _processed, unsigned _strands) const
  1450. {
  1451. if (statsBuilder)
  1452. {
  1453. StatsEdgeScope scope(*statsBuilder, activityId, oid);
  1454. if (_strands)
  1455. statsBuilder->addStatistic(StNumStrands, _strands);
  1456. if (starts != 0)
  1457. {
  1458. statsBuilder->addStatistic(StNumRowsProcessed, _processed);
  1459. statsBuilder->addStatistic(StNumStarts, starts);
  1460. // Assume number of starts = number of stops since stats only ever gathered when a query is complete
  1461. statsBuilder->addStatistic(StNumStops, starts);
  1462. statsBuilder->addStatistic(StNumSlaves, 1); // Arguable
  1463. }
  1464. }
  1465. if (collectFactoryStatistics)
  1466. factory->noteProcessed(oid, processed);
  1467. }
  1468. protected:
  1469. RecordTranslationMode getEnableFieldTranslation() const
  1470. {
  1471. return factory->queryQueryFactory().queryOptions().enableFieldTranslation;
  1472. }
  1473. };
  1474. //=====================================================================================================
  1475. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1476. {
  1477. protected:
  1478. bool prefiltered;
  1479. bool eof;
  1480. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1481. {
  1482. prefiltered = !any;
  1483. eof = prefiltered;
  1484. if (!prefiltered)
  1485. {
  1486. input->start(parentExtractSize, parentExtract, false);
  1487. startJunction(junction);
  1488. }
  1489. else
  1490. {
  1491. if (traceStartStop)
  1492. CTXLOG("lateStart activity stopping input early as prefiltered");
  1493. inputStream->stop();
  1494. }
  1495. }
  1496. public:
  1497. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1498. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1499. {
  1500. prefiltered = false;
  1501. eof = false;
  1502. }
  1503. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1504. {
  1505. IFinalRoxieInput *saveInput = input;
  1506. Owned<IStrandJunction> saveJunction = junction.getClear();
  1507. input = NULL; // Make sure parent does not start the chain yet
  1508. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1509. input = saveInput;
  1510. junction.setown(saveJunction.getClear());
  1511. }
  1512. virtual void stop()
  1513. {
  1514. if (!prefiltered)
  1515. {
  1516. inputStream->stop();
  1517. }
  1518. else if (traceStartStop)
  1519. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1520. IEngineRowStream *save = inputStream;
  1521. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1522. CRoxieServerActivity::stop();
  1523. inputStream = save;
  1524. }
  1525. virtual void reset()
  1526. {
  1527. CRoxieServerActivity::reset();
  1528. prefiltered = false;
  1529. }
  1530. };
  1531. //=================================================================================
  1532. class StrandOptions
  1533. {
  1534. // Typically set from hints, common to many stranded activities
  1535. public:
  1536. explicit StrandOptions(IPropertyTree &_graphNode)
  1537. {
  1538. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1539. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1540. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1541. numStrands = getAffinityCpus();
  1542. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1543. }
  1544. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1545. {
  1546. numStrands = from.numStrands;
  1547. blockSize = from.blockSize;
  1548. if (!blockSize)
  1549. blockSize = ctx->queryOptions().strandBlockSize;
  1550. if (numStrands == 0)
  1551. numStrands = ctx->queryOptions().forceNumStrands;
  1552. }
  1553. public:
  1554. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1555. unsigned blockSize = 0;
  1556. };
  1557. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1558. {
  1559. protected:
  1560. CRoxieServerActivity &parent;
  1561. IEngineRowAllocator *rowAllocator;
  1562. IEngineRowStream *inputStream;
  1563. ActivityTimeAccumulator totalCycles;
  1564. mutable CRuntimeStatisticCollection stats;
  1565. unsigned processed = 0;
  1566. unsigned numProcessedLastGroup = 0;
  1567. const bool timeActivities;
  1568. bool stopped = false;
  1569. std::atomic<bool> abortRequested;
  1570. public:
  1571. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1572. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1573. {
  1574. if (needsAllocator)
  1575. {
  1576. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1577. }
  1578. else
  1579. rowAllocator = NULL;
  1580. }
  1581. ~StrandProcessor()
  1582. {
  1583. ::Release(rowAllocator);
  1584. }
  1585. virtual void start()
  1586. {
  1587. processed = 0;
  1588. numProcessedLastGroup = 0;
  1589. totalCycles.reset();
  1590. }
  1591. virtual void stop()
  1592. {
  1593. if (!stopped)
  1594. {
  1595. if (inputStream)
  1596. inputStream->stop();
  1597. parent.stop();
  1598. //It would be preferrable to move totalCycles (+processed?) to gatherStats(), but because of
  1599. //the way firstRow is associated with startCycles it would require an extra parameter
  1600. //which is not consistent with the other gatherStats() calls, or extra logic in the stats classes.
  1601. parent.mergeStrandStats(processed, totalCycles);
  1602. }
  1603. stopped = true;
  1604. }
  1605. virtual void reset()
  1606. {
  1607. stopped = false;
  1608. abortRequested.store(false, std::memory_order_relaxed);
  1609. }
  1610. virtual void resetEOF()
  1611. {
  1612. inputStream->resetEOF();
  1613. }
  1614. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1615. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1616. void gatherStats(CRuntimeStatisticCollection & mergedStats) const
  1617. {
  1618. mergedStats.merge(stats);
  1619. if (rowAllocator)
  1620. rowAllocator->gatherStats(mergedStats);
  1621. }
  1622. const ActivityTimeAccumulator& queryTimings() const { return totalCycles; }
  1623. };
  1624. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1625. {
  1626. protected:
  1627. StrandOptions strandOptions;
  1628. IArrayOf<StrandProcessor> strands;
  1629. Owned<IStrandBranch> branch;
  1630. Owned<IStrandJunction> splitter;
  1631. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1632. std::atomic<unsigned> active;
  1633. public:
  1634. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1635. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1636. strandOptions(_strandOptions, ctx)
  1637. {
  1638. active = 0;
  1639. }
  1640. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1641. {
  1642. CRoxieServerActivity::gatherStats(merged);
  1643. ForEachItemIn(i, strands)
  1644. strands.item(i).gatherStats(merged);
  1645. }
  1646. virtual void onCreate(IHThorArg *_colocalArg)
  1647. {
  1648. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1649. }
  1650. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1651. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1652. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1653. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1654. virtual void reset()
  1655. {
  1656. assertex(active==0);
  1657. totalCycles.reset();
  1658. ForEachItemIn(idx, strands)
  1659. {
  1660. strands.item(idx).reset();
  1661. totalCycles.merge(strands.item(idx).queryTimings());
  1662. }
  1663. resetJunction(splitter);
  1664. CRoxieServerActivity::reset();
  1665. resetJunction(sourceJunction);
  1666. }
  1667. virtual void stop()
  1668. {
  1669. // Called from the strands... which should ensure that stop is not called more than once per strand
  1670. //The first strand to call
  1671. if (active)
  1672. --active;
  1673. if (!active)
  1674. CRoxieServerActivity::stop();
  1675. }
  1676. void requestAbort()
  1677. {
  1678. ForEachItemIn(idx, strands)
  1679. strands.item(idx).requestAbort();
  1680. }
  1681. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1682. {
  1683. assertex(idx == 0);
  1684. assertex(strands.empty());
  1685. CRoxieServerActivity::connectDependencies();
  1686. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1687. //Note, numStrands == 1 is an explicit request to disable threading
  1688. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1689. {
  1690. //Check to see if the consumer's settings should override
  1691. if (strandOptions.numStrands == 0)
  1692. {
  1693. strandOptions.numStrands = consumerOptions->numStrands;
  1694. strandOptions.blockSize = consumerOptions->blockSize;
  1695. }
  1696. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1697. {
  1698. strandOptions.numStrands = consumerOptions->numStrands;
  1699. }
  1700. }
  1701. Owned <IStrandJunction> recombiner;
  1702. if (input)
  1703. {
  1704. if (strandOptions.numStrands == 1)
  1705. {
  1706. // 1 means explicitly requested single-strand.
  1707. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1708. strands.append(*createStrandProcessor(instream));
  1709. }
  1710. else
  1711. {
  1712. PointerArrayOf<IEngineRowStream> instreams;
  1713. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1714. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1715. {
  1716. assertex(recombiner == NULL);
  1717. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1718. if (inputOrdered)
  1719. {
  1720. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1721. splitter.set(branch->queryInputJunction());
  1722. recombiner.set(branch->queryOutputJunction());
  1723. }
  1724. else
  1725. {
  1726. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1727. }
  1728. splitter->setInput(0, instreams.item(0));
  1729. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1730. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1731. }
  1732. else
  1733. {
  1734. // Ignore my hint and just use the width already split into...
  1735. ForEachItemIn(strandNo, instreams)
  1736. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1737. }
  1738. }
  1739. }
  1740. else
  1741. {
  1742. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1743. for (unsigned i=0; i < numStrands; i++)
  1744. strands.append(*createStrandSourceProcessor(inputOrdered));
  1745. if (inputOrdered && (numStrands > 1))
  1746. {
  1747. if (consumerOptions)
  1748. {
  1749. //If the output activities are also stranded then need to create a version of the branch
  1750. bool isGrouped = queryOutputMeta()->isGrouped();
  1751. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1752. sourceJunction.set(branch->queryInputJunction());
  1753. recombiner.set(branch->queryOutputJunction());
  1754. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1755. //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
  1756. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1757. {
  1758. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1759. streams.append(sourceJunction->queryOutput(strandNo));
  1760. }
  1761. #ifdef TRACE_STRANDS
  1762. if (traceLevel > 2)
  1763. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1764. #endif
  1765. return recombiner.getClear();
  1766. }
  1767. else
  1768. {
  1769. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1770. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1771. }
  1772. }
  1773. }
  1774. ForEachItemIn(i, strands)
  1775. streams.append(&strands.item(i));
  1776. #ifdef TRACE_STRANDS
  1777. if (traceLevel > 2)
  1778. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1779. #endif
  1780. return recombiner.getClear();
  1781. }
  1782. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1783. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1784. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1785. virtual const void * nextRow()
  1786. {
  1787. throwUnexpected();
  1788. }
  1789. inline unsigned numStrands() const { return strands.ordinality(); }
  1790. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1791. {
  1792. addEdgeStats(statsBuilder, 0, numStarts, processed, strands.ordinality());
  1793. }
  1794. protected:
  1795. void onStartStrands()
  1796. {
  1797. ForEachItemIn(idx, strands)
  1798. {
  1799. strands.item(idx).start();
  1800. active++;
  1801. }
  1802. }
  1803. };
  1804. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1805. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1806. {
  1807. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1808. startJunction(splitter);
  1809. }
  1810. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1811. {
  1812. protected:
  1813. bool prefiltered;
  1814. bool eof;
  1815. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1816. {
  1817. prefiltered = !any;
  1818. eof = prefiltered;
  1819. if (!prefiltered)
  1820. {
  1821. //At this point
  1822. input->start(parentExtractSize, parentExtract, false);
  1823. startJunction(splitter);
  1824. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1825. startJunction(sourceJunction);
  1826. }
  1827. else
  1828. {
  1829. if (traceStartStop)
  1830. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1831. ForEachItemIn(idx, strands)
  1832. strands.item(idx).stop();
  1833. }
  1834. }
  1835. public:
  1836. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1837. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1838. {
  1839. prefiltered = false;
  1840. eof = false;
  1841. }
  1842. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1843. {
  1844. IFinalRoxieInput *save = input;
  1845. 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)
  1846. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1847. input = save;
  1848. }
  1849. virtual void reset()
  1850. {
  1851. CRoxieServerStrandedActivity::reset();
  1852. prefiltered = false;
  1853. }
  1854. };
  1855. //=====================================================================================================
  1856. atomic_t nextInstanceId;
  1857. extern unsigned getNextInstanceId()
  1858. {
  1859. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1860. }
  1861. atomic_t nextRuid;
  1862. ruid_t getNextRuid()
  1863. {
  1864. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1865. while (ret < RUID_FIRST)
  1866. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1867. return ret;
  1868. }
  1869. void setStartRuid(unsigned restarts)
  1870. {
  1871. atomic_set(&nextRuid, restarts * 0x10000);
  1872. atomic_set(&nextInstanceId, restarts * 10000);
  1873. }
  1874. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1875. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1876. {
  1877. int code;
  1878. public:
  1879. LimitSkipException(int _code) { code = _code; }
  1880. IMPLEMENT_IINTERFACE;
  1881. virtual int errorCode() const { return code; }
  1882. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1883. virtual MessageAudience errorAudience() const { return MSGAUD_programmer; }
  1884. };
  1885. IException *makeLimitSkipException(bool isKeyed)
  1886. {
  1887. // We need to make sure what we throw is IException not something derived from it....
  1888. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1889. }
  1890. //=================================================================================
  1891. interface IRecordPullerCallback : extends IExceptionHandler
  1892. {
  1893. virtual void processRow(const void *row) = 0;
  1894. virtual void processEOG() = 0;
  1895. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1896. virtual void processDone() = 0;
  1897. };
  1898. class RecordPullerThread : public RestartableThread
  1899. {
  1900. protected:
  1901. IFinalRoxieInput *input;
  1902. Owned<IStrandJunction> junction;
  1903. unsigned sourceIdx = 0;
  1904. IEngineRowStream *inputStream;
  1905. IRecordPullerCallback *helper;
  1906. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1907. bool groupAtOnce, eof, eog;
  1908. CriticalSection crit;
  1909. public:
  1910. RecordPullerThread(bool _groupAtOnce)
  1911. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1912. {
  1913. input = NULL;
  1914. inputStream = NULL;
  1915. helper = NULL;
  1916. eof = eog = FALSE;
  1917. }
  1918. inline unsigned __int64 queryTotalCycles() const
  1919. {
  1920. return input->queryTotalCycles();
  1921. }
  1922. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1923. {
  1924. helper = _helper;
  1925. input = _input;
  1926. sourceIdx = _sourceIdx;
  1927. }
  1928. IFinalRoxieInput *queryInput() const
  1929. {
  1930. return input;
  1931. }
  1932. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1933. {
  1934. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1935. }
  1936. IEngineRowStream *queryStream() const
  1937. {
  1938. return inputStream;
  1939. }
  1940. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1941. {
  1942. eof = false;
  1943. eog = false;
  1944. input->start(parentExtractSize, parentExtract, paused);
  1945. startJunction(junction);
  1946. try
  1947. {
  1948. if (preload && !paused)
  1949. {
  1950. if (traceLevel > 4)
  1951. DBGLOG("Preload fetching first %d records", preload);
  1952. if (groupAtOnce)
  1953. pullGroups(preload);
  1954. else
  1955. pullRecords(preload);
  1956. }
  1957. if (eof)
  1958. {
  1959. if (traceLevel > 4)
  1960. DBGLOG("No need to start puller after preload");
  1961. helper->processDone();
  1962. }
  1963. else
  1964. {
  1965. if (!noThread)
  1966. {
  1967. StringBuffer logPrefix("[");
  1968. if (ctx) ctx->getLogPrefix(logPrefix);
  1969. logPrefix.append("] ");
  1970. RestartableThread::start(logPrefix);
  1971. started.wait();
  1972. }
  1973. }
  1974. }
  1975. catch (IException *e)
  1976. {
  1977. helper->fireException(e);
  1978. }
  1979. catch (...)
  1980. {
  1981. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1982. }
  1983. }
  1984. void stop()
  1985. {
  1986. if (traceStartStop)
  1987. DBGLOG("RecordPullerThread::stop");
  1988. {
  1989. 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.
  1990. if (inputStream)
  1991. inputStream->stop();
  1992. }
  1993. RestartableThread::join();
  1994. }
  1995. void reset()
  1996. {
  1997. input->reset();
  1998. resetJunction(junction);
  1999. }
  2000. virtual int run()
  2001. {
  2002. started.signal();
  2003. try
  2004. {
  2005. if (groupAtOnce)
  2006. pullGroups((unsigned) -1);
  2007. else
  2008. pullRecords((unsigned) -1);
  2009. helper->processDone();
  2010. }
  2011. catch (IException *e)
  2012. {
  2013. helper->fireException(e);
  2014. }
  2015. catch (...)
  2016. {
  2017. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  2018. }
  2019. return 0;
  2020. }
  2021. void done()
  2022. {
  2023. helper->processDone();
  2024. }
  2025. bool pullRecords(unsigned preload)
  2026. {
  2027. if (eof)
  2028. return false;
  2029. while (preload)
  2030. {
  2031. const void * row;
  2032. {
  2033. CriticalBlock c(crit); // See comments in stop for why this is needed
  2034. row = inputStream->nextRow();
  2035. }
  2036. if (row)
  2037. {
  2038. eog = false;
  2039. helper->processRow(row);
  2040. }
  2041. else if (!eog)
  2042. {
  2043. helper->processEOG();
  2044. eog = true;
  2045. }
  2046. else
  2047. {
  2048. eof = true;
  2049. return false;
  2050. }
  2051. if (preload != (unsigned) -1)
  2052. preload--;
  2053. }
  2054. return true;
  2055. }
  2056. void pullGroups(unsigned preload)
  2057. {
  2058. ConstPointerArray thisGroup;
  2059. unsigned rowsDone = 0;
  2060. while (preload && !eof)
  2061. {
  2062. const void *row;
  2063. {
  2064. CriticalBlock c(crit);
  2065. row = inputStream->nextRow();
  2066. }
  2067. if (row)
  2068. {
  2069. thisGroup.append(row);
  2070. rowsDone++;
  2071. }
  2072. else if (thisGroup.length())
  2073. {
  2074. helper->processGroup(thisGroup);
  2075. thisGroup.kill();
  2076. if (preload != (unsigned) -1)
  2077. {
  2078. if (preload > rowsDone)
  2079. preload -= rowsDone;
  2080. else
  2081. break;
  2082. }
  2083. rowsDone = 0;
  2084. }
  2085. else
  2086. {
  2087. eof = true;
  2088. break;
  2089. }
  2090. }
  2091. }
  2092. };
  2093. //=================================================================================
  2094. #define READAHEAD_SIZE 1000
  2095. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2096. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2097. {
  2098. QueueOf<const void, true> buffer;
  2099. InterruptableSemaphore ready;
  2100. InterruptableSemaphore space;
  2101. CriticalSection crit;
  2102. bool eof;
  2103. bool disabled;
  2104. IRoxieSlaveContext *ctx;
  2105. RecordPullerThread puller;
  2106. unsigned preload;
  2107. cycle_t totalCycles;
  2108. bool timeActivities;
  2109. public:
  2110. IMPLEMENT_IINTERFACE;
  2111. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2112. {
  2113. eof = false;
  2114. disabled = (ctx->queryDebugContext() != NULL);
  2115. totalCycles = 0;
  2116. timeActivities = ctx->queryOptions().timeActivities;
  2117. }
  2118. virtual IRoxieServerActivity *queryActivity()
  2119. {
  2120. return puller.queryInput()->queryActivity();
  2121. }
  2122. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2123. {
  2124. assertex(!idx);
  2125. puller.connectInputStreams(ctx, consumerOrdered);
  2126. streams.append(this);
  2127. return NULL;
  2128. }
  2129. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2130. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2131. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2132. {
  2133. return puller.queryInput()->queryIndexReadActivity();
  2134. }
  2135. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2136. {
  2137. eof = false;
  2138. if (disabled)
  2139. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2140. else
  2141. {
  2142. space.reinit(READAHEAD_SIZE);
  2143. ready.reinit();
  2144. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2145. }
  2146. }
  2147. virtual void stop()
  2148. {
  2149. if (disabled)
  2150. puller.queryStream()->stop();
  2151. else
  2152. {
  2153. space.interrupt();
  2154. ready.interrupt();
  2155. puller.stop();
  2156. }
  2157. }
  2158. virtual void reset()
  2159. {
  2160. if (disabled)
  2161. puller.queryInput()->reset();
  2162. else
  2163. {
  2164. puller.reset();
  2165. ForEachItemIn(idx1, buffer)
  2166. ReleaseRoxieRow(buffer.item(idx1));
  2167. buffer.clear();
  2168. }
  2169. }
  2170. virtual void resetEOF()
  2171. {
  2172. throwUnexpected();
  2173. }
  2174. virtual IOutputMetaData * queryOutputMeta() const
  2175. {
  2176. return puller.queryInput()->queryOutputMeta();
  2177. }
  2178. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2179. {
  2180. assertex(!idx);
  2181. puller.setInput(this, _sourceIdx, _in);
  2182. }
  2183. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2184. {
  2185. if (idx==0)
  2186. return puller.queryInput();
  2187. else
  2188. return NULL;
  2189. }
  2190. virtual unsigned __int64 queryTotalCycles() const
  2191. {
  2192. return totalCycles;
  2193. }
  2194. virtual const void * nextRow()
  2195. {
  2196. SimpleActivityTimer t(totalCycles, timeActivities);
  2197. if (disabled)
  2198. return puller.queryStream()->nextRow();
  2199. else
  2200. {
  2201. for (;;)
  2202. {
  2203. {
  2204. CriticalBlock b(crit);
  2205. if (eof && !buffer.ordinality())
  2206. return NULL; // eof
  2207. }
  2208. ready.wait();
  2209. const void *ret;
  2210. {
  2211. CriticalBlock b(crit);
  2212. ret = buffer.dequeue();
  2213. }
  2214. space.signal();
  2215. return ret;
  2216. }
  2217. }
  2218. }
  2219. virtual bool fireException(IException *e)
  2220. {
  2221. // called from puller thread on failure
  2222. ready.interrupt(LINK(e));
  2223. space.interrupt(e);
  2224. return true;
  2225. }
  2226. virtual void processRow(const void *row)
  2227. {
  2228. {
  2229. CriticalBlock b(crit);
  2230. buffer.enqueue(row);
  2231. }
  2232. ready.signal();
  2233. space.wait();
  2234. }
  2235. virtual void processGroup(const ConstPointerArray &rows)
  2236. {
  2237. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2238. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2239. // if group was larger than max(space)
  2240. {
  2241. CriticalBlock b(crit);
  2242. ForEachItemIn(idx, rows)
  2243. buffer.enqueue(rows.item(idx));
  2244. buffer.enqueue(NULL);
  2245. }
  2246. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2247. {
  2248. ready.signal();
  2249. space.wait();
  2250. }
  2251. }
  2252. virtual void processEOG()
  2253. {
  2254. // Used when output is not grouped - just ignore
  2255. }
  2256. virtual void processDone()
  2257. {
  2258. CriticalBlock b(crit);
  2259. eof = true;
  2260. ready.signal();
  2261. }
  2262. };
  2263. //=================================================================================
  2264. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2265. {
  2266. protected:
  2267. IFinalRoxieInput *input1;
  2268. IEngineRowStream *inputStream1;
  2269. Owned<IStrandJunction> junction1;
  2270. unsigned sourceIdx1 = 0;
  2271. Owned<CRoxieServerReadAheadInput> puller;
  2272. public:
  2273. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2274. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2275. {
  2276. input1 = NULL;
  2277. inputStream1 = NULL;
  2278. }
  2279. ~CRoxieServerTwoInputActivity()
  2280. {
  2281. }
  2282. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2283. {
  2284. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2285. input1->start(parentExtractSize, parentExtract, paused);
  2286. startJunction(junction1);
  2287. }
  2288. virtual void stop()
  2289. {
  2290. inputStream1->stop();
  2291. CRoxieServerActivity::stop();
  2292. }
  2293. virtual unsigned __int64 queryLocalCycles() const
  2294. {
  2295. __int64 ret;
  2296. __int64 inputCycles = input->queryTotalCycles();
  2297. __int64 input1Cycles = input1->queryTotalCycles();
  2298. if (puller)
  2299. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2300. else
  2301. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2302. if (ret < 0)
  2303. ret = 0;
  2304. return ret;
  2305. }
  2306. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2307. {
  2308. switch (idx)
  2309. {
  2310. case 0:
  2311. return input;
  2312. case 1:
  2313. return input1;
  2314. default:
  2315. return NULL;
  2316. }
  2317. }
  2318. virtual void reset()
  2319. {
  2320. CRoxieServerActivity::reset();
  2321. if (input1)
  2322. input1->reset();
  2323. resetJunction(junction1);
  2324. }
  2325. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2326. {
  2327. switch(idx)
  2328. {
  2329. case 0:
  2330. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2331. break;
  2332. case 1:
  2333. input1 = _in;
  2334. sourceIdx1 = _sourceIdx;
  2335. break;
  2336. default:
  2337. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2338. }
  2339. }
  2340. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2341. {
  2342. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2343. //Assumes input1 will be stranded if any.
  2344. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2345. }
  2346. };
  2347. //=================================================================================
  2348. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2349. {
  2350. protected:
  2351. unsigned numInputs;
  2352. unsigned numStreams;
  2353. IFinalRoxieInput **inputArray;
  2354. unsigned *sourceIdxArray;
  2355. IEngineRowStream **streamArray;
  2356. Owned<IStrandJunction> *junctionArray;
  2357. public:
  2358. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2359. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2360. {
  2361. numStreams = numInputs;
  2362. inputArray = new IFinalRoxieInput*[numInputs];
  2363. sourceIdxArray = new unsigned[numInputs];
  2364. streamArray = new IEngineRowStream*[numStreams];
  2365. junctionArray = new Owned<IStrandJunction>[numStreams];
  2366. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2367. {
  2368. inputArray[i1] = NULL;
  2369. sourceIdxArray[i1] = 0;
  2370. }
  2371. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2372. streamArray[i2] = NULL;
  2373. }
  2374. ~CRoxieServerMultiInputBaseActivity()
  2375. {
  2376. delete [] inputArray;
  2377. delete [] sourceIdxArray;
  2378. delete [] streamArray;
  2379. delete [] junctionArray;
  2380. }
  2381. virtual unsigned __int64 queryLocalCycles() const
  2382. {
  2383. __int64 localCycles = totalCycles.totalCycles;
  2384. for (unsigned i = 0; i < numInputs; i++)
  2385. localCycles -= inputArray[i]->queryTotalCycles();
  2386. if (localCycles < 0)
  2387. localCycles = 0;
  2388. return localCycles;
  2389. }
  2390. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2391. {
  2392. if (idx < numInputs)
  2393. return inputArray[idx];
  2394. else
  2395. return NULL;
  2396. }
  2397. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2398. {
  2399. return queryInput(idx);
  2400. }
  2401. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2402. {
  2403. if (whichInput < numInputs)
  2404. return streamArray[whichInput];
  2405. else
  2406. return NULL;
  2407. }
  2408. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2409. {
  2410. if (idx < numInputs)
  2411. return junctionArray[idx];
  2412. else
  2413. return NULL;
  2414. }
  2415. virtual void reset()
  2416. {
  2417. for (unsigned i = 0; i < numInputs; i++)
  2418. inputArray[i]->reset();
  2419. for (unsigned iS = 0; iS < numStreams; iS++)
  2420. {
  2421. resetJunction(junctionArray[iS]);
  2422. }
  2423. CRoxieServerActivity::reset();
  2424. }
  2425. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2426. {
  2427. assertex(idx < numInputs && idx < numStreams);
  2428. inputArray[idx] = _in;
  2429. sourceIdxArray[idx] = _sourceIdx;
  2430. }
  2431. virtual void connectInputStreams(bool consumerOrdered)
  2432. {
  2433. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2434. connectSingleInputStreams(consumerOrdered);
  2435. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  2436. }
  2437. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2438. {
  2439. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2440. }
  2441. protected:
  2442. void connectSingleInputStreams(bool consumerOrdered)
  2443. {
  2444. for (unsigned i = 0; i < numInputs; i++)
  2445. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2446. }
  2447. };
  2448. //=================================================================================
  2449. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2450. {
  2451. public:
  2452. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2453. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2454. {
  2455. }
  2456. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2457. {
  2458. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2459. for (unsigned i = 0; i < numInputs; i++)
  2460. {
  2461. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2462. }
  2463. for (unsigned iS = 0; iS < numStreams; iS++)
  2464. {
  2465. startJunction(junctionArray[iS]);
  2466. }
  2467. }
  2468. virtual void stop()
  2469. {
  2470. for (unsigned i = 0; i < numStreams; i++)
  2471. {
  2472. streamArray[i]->stop();
  2473. }
  2474. CRoxieServerMultiInputBaseActivity::stop();
  2475. }
  2476. };
  2477. //=====================================================================================================
  2478. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2479. {
  2480. protected:
  2481. unsigned numOutputs;
  2482. bool executed;
  2483. bool *stopped;
  2484. CriticalSection ecrit;
  2485. Owned<IException> exception;
  2486. public:
  2487. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2488. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2489. {
  2490. executed = false;
  2491. stopped = new bool[numOutputs];
  2492. for (unsigned s = 0; s < numOutputs; s++)
  2493. stopped[s] = false;
  2494. }
  2495. ~CRoxieServerInternalSinkActivity()
  2496. {
  2497. delete [] stopped;
  2498. }
  2499. virtual void reset()
  2500. {
  2501. for (unsigned s = 0; s < numOutputs; s++)
  2502. stopped[s] = false;
  2503. executed = false;
  2504. exception.clear();
  2505. CRoxieServerActivity::reset();
  2506. }
  2507. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2508. {
  2509. return NULL;
  2510. }
  2511. virtual void stopSink(unsigned outputIdx)
  2512. {
  2513. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2514. {
  2515. stopped[outputIdx] = true;
  2516. for (unsigned s = 0; s < numOutputs; s++)
  2517. if (!stopped[s])
  2518. return;
  2519. stop(); // all outputs stopped - stop parent.
  2520. }
  2521. }
  2522. virtual const void *nextRow()
  2523. {
  2524. throwUnexpected(); // I am nobody's input
  2525. }
  2526. virtual void onExecute() = 0;
  2527. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2528. {
  2529. CriticalBlock b(ecrit);
  2530. if (exception)
  2531. throw exception.getLink();
  2532. if (!executed)
  2533. {
  2534. try
  2535. {
  2536. start(parentExtractSize, parentExtract, false);
  2537. {
  2538. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2539. onExecute();
  2540. }
  2541. stop();
  2542. executed = true;
  2543. }
  2544. catch (IException *E)
  2545. {
  2546. exception.set(E); // (or maybe makeWrappedException?)
  2547. abort();
  2548. throw;
  2549. }
  2550. catch (...)
  2551. {
  2552. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2553. abort();
  2554. throw;
  2555. }
  2556. }
  2557. }
  2558. };
  2559. //=================================================================================
  2560. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2561. {
  2562. protected:
  2563. Owned<IMessageResult> result;
  2564. Owned<IRoxieQueryPacket> packet;
  2565. Linked<IRoxieServerQueryPacket> continuation;
  2566. unsigned hash;
  2567. unsigned seq;
  2568. unsigned lastDebugSequence;
  2569. Owned<IRoxieQueryPacket> lastDebugResponse;
  2570. ILRUChain *prev;
  2571. ILRUChain *next;
  2572. bool delayed;
  2573. public:
  2574. IMPLEMENT_IINTERFACE;
  2575. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2576. {
  2577. hash = 0;
  2578. seq = 0;
  2579. prev = NULL;
  2580. next = NULL;
  2581. delayed = false;
  2582. lastDebugSequence = 0;
  2583. }
  2584. virtual IRoxieQueryPacket *queryPacket() const
  2585. {
  2586. return packet;
  2587. }
  2588. virtual bool isContinuation() const
  2589. {
  2590. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2591. }
  2592. virtual bool isDelayed() const
  2593. {
  2594. return delayed;
  2595. }
  2596. virtual bool isEnd() const
  2597. {
  2598. return false;
  2599. }
  2600. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2601. {
  2602. return false;
  2603. }
  2604. virtual bool hasResult() const
  2605. {
  2606. return result != NULL;
  2607. }
  2608. virtual bool hasContinuation() const
  2609. {
  2610. return continuation != NULL;
  2611. }
  2612. virtual void setDelayed(bool _delayed)
  2613. {
  2614. delayed = _delayed;
  2615. }
  2616. virtual void setPacket(IRoxieQueryPacket *_packet)
  2617. {
  2618. packet.setown(_packet);
  2619. }
  2620. virtual void setSequence(unsigned _seq)
  2621. {
  2622. assertex(!IsShared());
  2623. seq = _seq;
  2624. }
  2625. virtual unsigned getSequence() const
  2626. {
  2627. return seq;
  2628. }
  2629. IMessageResult *getResult()
  2630. {
  2631. return result.getLink();
  2632. }
  2633. IMessageResult *queryResult()
  2634. {
  2635. return result;
  2636. }
  2637. void setResult(IMessageResult *r)
  2638. {
  2639. result.setown(r);
  2640. }
  2641. IRoxieServerQueryPacket *queryContinuation()
  2642. {
  2643. return continuation;
  2644. }
  2645. void setContinuation(IRoxieServerQueryPacket *c)
  2646. {
  2647. continuation.setown(c);
  2648. }
  2649. virtual unsigned queryHash() const
  2650. {
  2651. return hash;
  2652. }
  2653. virtual void setHash(unsigned _hash)
  2654. {
  2655. hash = _hash;
  2656. }
  2657. virtual ILRUChain *queryPrev() const { return prev; }
  2658. virtual ILRUChain *queryNext() const { return next; }
  2659. virtual void setPrev(ILRUChain *p) { prev = p; }
  2660. virtual void setNext(ILRUChain *n) { next = n; }
  2661. virtual void unchain()
  2662. {
  2663. if (prev && next)
  2664. {
  2665. prev->setNext(next);
  2666. next->setPrev(prev);
  2667. }
  2668. next = NULL;
  2669. prev = NULL;
  2670. }
  2671. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2672. {
  2673. if (sequence == lastDebugSequence)
  2674. return lastDebugResponse.getLink();
  2675. else if (sequence > lastDebugSequence)
  2676. {
  2677. lastDebugResponse.clear();
  2678. return NULL;
  2679. }
  2680. else
  2681. throwUnexpected();
  2682. }
  2683. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2684. {
  2685. lastDebugSequence = sequence;
  2686. lastDebugResponse.set(response);
  2687. }
  2688. };
  2689. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2690. {
  2691. public:
  2692. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2693. {
  2694. }
  2695. virtual bool isEnd() const
  2696. {
  2697. return true;
  2698. }
  2699. };
  2700. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2701. {
  2702. unsigned __int64 rowLimit;
  2703. unsigned __int64 keyedLimit;
  2704. unsigned __int64 stopAfter;
  2705. public:
  2706. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2707. {
  2708. rowLimit = _rowLimit;
  2709. keyedLimit = _keyedLimit;
  2710. stopAfter = _stopAfter;
  2711. }
  2712. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2713. {
  2714. _rowLimit = rowLimit;
  2715. _keyedLimit = keyedLimit;
  2716. _stopAfter = stopAfter;
  2717. return true;
  2718. }
  2719. };
  2720. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2721. {
  2722. protected:
  2723. unsigned cacheTableSize;
  2724. unsigned cacheTableSpace;
  2725. IRoxieServerQueryPacket **cacheTable;
  2726. mutable ILRUChain *prev;
  2727. mutable ILRUChain *next;
  2728. mutable CriticalSection crit;
  2729. virtual ILRUChain *queryPrev() const { return prev; }
  2730. virtual ILRUChain *queryNext() const { return next; }
  2731. virtual void setPrev(ILRUChain *p) { prev = p; }
  2732. virtual void setNext(ILRUChain *n) { next = n; }
  2733. virtual void unchain()
  2734. {
  2735. prev->setNext(next);
  2736. next->setPrev(prev);
  2737. next = NULL;
  2738. prev = NULL;
  2739. }
  2740. void moveToHead(IRoxieServerQueryPacket *mru)
  2741. {
  2742. mru->unchain();
  2743. mru->setNext(next);
  2744. next->setPrev(mru);
  2745. mru->setPrev(this);
  2746. next = mru;
  2747. }
  2748. IRoxieServerQueryPacket *removeLRU()
  2749. {
  2750. if (next==this)
  2751. assertex(next != this);
  2752. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2753. goer->unchain(); // NOTE - this will modify the value of next
  2754. return goer;
  2755. }
  2756. void removeEntry(IRoxieServerQueryPacket *goer)
  2757. {
  2758. unsigned v = goer->queryHash() % cacheTableSize;
  2759. for (;;)
  2760. {
  2761. IRoxieServerQueryPacket *found = cacheTable[v];
  2762. assertex(found);
  2763. if (found == goer)
  2764. {
  2765. cacheTable[v] = NULL;
  2766. unsigned vn = v;
  2767. for (;;)
  2768. {
  2769. vn++;
  2770. if (vn==cacheTableSize) vn = 0;
  2771. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2772. if (!found2)
  2773. break;
  2774. unsigned vm = found2->queryHash() % cacheTableSize;
  2775. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2776. {
  2777. cacheTable[v] = found2;
  2778. v = vn;
  2779. cacheTable[v] = NULL;
  2780. }
  2781. }
  2782. cacheTableSpace++;
  2783. break;
  2784. }
  2785. v++;
  2786. if (v==cacheTableSize)
  2787. v = 0;
  2788. }
  2789. goer->Release();
  2790. }
  2791. public:
  2792. CRoxieServerSideCache(unsigned _cacheSize)
  2793. {
  2794. cacheTableSize = (_cacheSize*4)/3;
  2795. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2796. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2797. cacheTableSpace = _cacheSize;
  2798. prev = this;
  2799. next = this;
  2800. }
  2801. ~CRoxieServerSideCache()
  2802. {
  2803. for (unsigned i = 0; i < cacheTableSize; i++)
  2804. {
  2805. ::Release(cacheTable[i]);
  2806. }
  2807. delete [] cacheTable;
  2808. }
  2809. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2810. {
  2811. unsigned hash = p->hash();
  2812. unsigned et = hash % cacheTableSize;
  2813. if (traceServerSideCache)
  2814. {
  2815. StringBuffer s;
  2816. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2817. }
  2818. CriticalBlock b(crit);
  2819. for (;;)
  2820. {
  2821. IRoxieServerQueryPacket *found = cacheTable[et];
  2822. if (!found)
  2823. return NULL;
  2824. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2825. {
  2826. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2827. if (traceServerSideCache)
  2828. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2829. logctx.noteStatistic(StNumServerCacheHits, 1);
  2830. return NULL;
  2831. // 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....
  2832. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2833. //ret->setResult(found->getResult());
  2834. //return ret;
  2835. }
  2836. et++;
  2837. if (et == cacheTableSize)
  2838. et = 0;
  2839. }
  2840. }
  2841. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2842. {
  2843. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2844. {
  2845. unsigned hash = out->queryPacket()->hash();
  2846. out->setHash(hash);
  2847. unsigned et = hash % cacheTableSize;
  2848. if (traceServerSideCache)
  2849. {
  2850. StringBuffer s;
  2851. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2852. }
  2853. CriticalBlock b(crit);
  2854. for (;;)
  2855. {
  2856. IRoxieServerQueryPacket *found = cacheTable[et];
  2857. if (!found)
  2858. {
  2859. if (cacheTableSpace)
  2860. {
  2861. out->setResult(LINK(in));
  2862. cacheTable[et] = LINK(out);
  2863. cacheTableSpace--;
  2864. moveToHead(out);
  2865. break;
  2866. }
  2867. else
  2868. {
  2869. IRoxieServerQueryPacket *goer = removeLRU();
  2870. removeEntry(goer);
  2871. et = hash % cacheTableSize;
  2872. continue;
  2873. }
  2874. }
  2875. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2876. {
  2877. moveToHead(found);
  2878. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2879. // multiple copies of a slave query are in-flight at once.
  2880. }
  2881. et++;
  2882. if (et == cacheTableSize)
  2883. et = 0;
  2884. }
  2885. }
  2886. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2887. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2888. }
  2889. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2890. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2891. // more than make up for it
  2892. };
  2893. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2894. {
  2895. ConstPointerArray &data;
  2896. Linked<IMessageResult> result;
  2897. public:
  2898. IMPLEMENT_IINTERFACE;
  2899. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2900. : data(_data), result(_result)
  2901. {
  2902. }
  2903. virtual bool atEOF() const
  2904. {
  2905. return data.length()==0;
  2906. }
  2907. virtual bool isSerialized() const
  2908. {
  2909. return false;
  2910. }
  2911. virtual const void * getNext(int length)
  2912. {
  2913. if (!data.length())
  2914. return NULL;
  2915. const void *ret = data.item(0);
  2916. data.remove(0);
  2917. return ret;
  2918. }
  2919. };
  2920. // MORE - should possibly move more over to the lazy version used in indexread?
  2921. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2922. {
  2923. ConstPointerArray data;
  2924. IRowManager &rowManager;
  2925. bool variableSize;
  2926. public:
  2927. IMPLEMENT_IINTERFACE;
  2928. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2929. {
  2930. }
  2931. ~CRowArrayMessageResult()
  2932. {
  2933. ReleaseRoxieRows(data);
  2934. }
  2935. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2936. {
  2937. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2938. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2939. }
  2940. virtual const void *getMessageHeader(unsigned &length) const
  2941. {
  2942. throwUnexpected(); // should never get called - I don't have a header available
  2943. }
  2944. virtual const void *getMessageMetadata(unsigned &length) const
  2945. {
  2946. length = 0;
  2947. return NULL;
  2948. }
  2949. virtual void discard() const
  2950. {
  2951. throwUnexpected();
  2952. }
  2953. void append(const void *row)
  2954. {
  2955. data.append(row);
  2956. }
  2957. };
  2958. void throwRemoteException(IMessageUnpackCursor *extra)
  2959. {
  2960. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2961. if (rowlen)
  2962. {
  2963. char *xml = (char *) extra->getNext(*rowlen);
  2964. ReleaseRoxieRow(rowlen);
  2965. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  2966. ReleaseRoxieRow(xml);
  2967. unsigned code = p->getPropInt("Code", 0);
  2968. const char *msg = p->queryProp("Message");
  2969. if (!msg)
  2970. msg = xml;
  2971. throw MakeStringException(code, "%s", msg);
  2972. }
  2973. throwUnexpected();
  2974. }
  2975. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2976. {
  2977. friend class CRemoteResultMerger;
  2978. class CRemoteResultMerger
  2979. {
  2980. class HeapEntry : public CInterface
  2981. {
  2982. private:
  2983. CRemoteResultAdaptor &adaptor;
  2984. IMessageUnpackCursor *cursor;
  2985. public:
  2986. const void *current;
  2987. bool isLast;
  2988. bool lastIsComplete;
  2989. IRoxieServerQueryPacket *packet;
  2990. unsigned seq;
  2991. public:
  2992. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2993. {
  2994. cursor = _cursor;
  2995. lastIsComplete = _lastIsComplete;
  2996. return next();
  2997. }
  2998. public:
  2999. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  3000. {
  3001. cursor = NULL;
  3002. current = NULL;
  3003. isLast = false;
  3004. lastIsComplete = true;
  3005. }
  3006. ~HeapEntry()
  3007. {
  3008. ::Release(packet);
  3009. ::Release(cursor);
  3010. ReleaseRoxieRow(current);
  3011. }
  3012. bool isCompleteMatch() const
  3013. {
  3014. if (!isLast || lastIsComplete)
  3015. return true;
  3016. else
  3017. return false;
  3018. }
  3019. const void *next()
  3020. {
  3021. if (cursor)
  3022. {
  3023. ReleaseClearRoxieRow(current);
  3024. current = adaptor.getRow(cursor);
  3025. isLast = cursor->atEOF();
  3026. if (!current)
  3027. {
  3028. cursor->Release();
  3029. cursor = NULL;
  3030. }
  3031. }
  3032. return current;
  3033. }
  3034. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  3035. {
  3036. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  3037. unsigned skipped = 0;
  3038. for (;;)
  3039. {
  3040. int c = compare->docompare(current, seek, numFields);
  3041. //If larger than the seek values, then we may be allowed to return an inexact match,
  3042. //if equal then it is required to be an exact match,
  3043. if (c > 0)
  3044. {
  3045. if (!requireExactMatch || isCompleteMatch())
  3046. break;
  3047. }
  3048. else if ((c == 0) && isCompleteMatch())
  3049. break;
  3050. skipped++;
  3051. if (!next())
  3052. break;
  3053. }
  3054. return skipped;
  3055. }
  3056. };
  3057. CRemoteResultAdaptor &adaptor;
  3058. CIArrayOf<HeapEntry> heapEntries;
  3059. UnsignedArray heap;
  3060. IRowManager *rowManager;
  3061. unsigned numPending;
  3062. unsigned numFields;
  3063. bool endSeen;
  3064. bool remakePending;
  3065. IRangeCompare *compare;
  3066. bool deferredContinuation;
  3067. inline int doCompare(unsigned l, unsigned r)
  3068. {
  3069. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  3070. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  3071. return ret;
  3072. }
  3073. void makeHeap()
  3074. {
  3075. /* Permute blocks to establish the heap property
  3076. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  3077. The children of p must both be greater than or equal to p
  3078. The parent of a child c is given by p = (c-1)/2
  3079. */
  3080. unsigned i;
  3081. unsigned n = heap.length();
  3082. unsigned *s = heap.getArray();
  3083. for (i=1; i<n; i++)
  3084. {
  3085. unsigned r = s[i];
  3086. int c = i; /* child */
  3087. while (c > 0)
  3088. {
  3089. int p = (c-1)/2; /* parent */
  3090. if ( doCompare( s[c], s[p] ) >= 0 )
  3091. break;
  3092. s[c] = s[p];
  3093. s[p] = r;
  3094. c = p;
  3095. }
  3096. }
  3097. remakePending = false;
  3098. }
  3099. void remakeHeap()
  3100. {
  3101. /* The row associated with block[0] will have changed
  3102. This code restores the heap property
  3103. */
  3104. unsigned p = 0; /* parent */
  3105. unsigned n = heap.length();
  3106. unsigned *s = heap.getArray();
  3107. while (1)
  3108. {
  3109. unsigned c = p*2 + 1; /* child */
  3110. if ( c >= n )
  3111. break;
  3112. /* Select smaller child */
  3113. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3114. /* If child is greater or equal than parent then we are done */
  3115. if ( doCompare( s[c], s[p] ) >= 0 )
  3116. break;
  3117. /* Swap parent and child */
  3118. unsigned r = s[c];
  3119. s[c] = s[p];
  3120. s[p] = r;
  3121. /* child becomes parent */
  3122. p = c;
  3123. }
  3124. remakePending = false;
  3125. }
  3126. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3127. {
  3128. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3129. IMessageResult *result = p->queryResult();
  3130. assertex(result);
  3131. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3132. {
  3133. heapEntries.append(h);
  3134. heap.append(heap.ordinality());
  3135. }
  3136. else
  3137. h.Release();
  3138. }
  3139. void removeHeap(unsigned idx)
  3140. {
  3141. heapEntries.remove(idx);
  3142. ForEachItemIn(i, heap)
  3143. {
  3144. unsigned v = heap.item(i);
  3145. assertex(v != idx);
  3146. if (v > idx)
  3147. heap.replace(v-1, i);
  3148. }
  3149. }
  3150. bool isCompleteMatchFlag(IMessageResult *result)
  3151. {
  3152. unsigned metaLen;
  3153. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3154. if (metaLen)
  3155. {
  3156. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3157. if (continuationLen >= sizeof(bool))
  3158. {
  3159. metaInfo += sizeof(unsigned short);
  3160. return *(bool *) metaInfo;
  3161. }
  3162. }
  3163. return true; // if no continuation info, last row was complete.
  3164. }
  3165. public:
  3166. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3167. {
  3168. init(NULL, NULL);
  3169. }
  3170. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3171. {
  3172. if (meta)
  3173. {
  3174. numFields = meta->getNumFields();
  3175. compare = meta->queryCompare();
  3176. }
  3177. else
  3178. {
  3179. numFields = 0;
  3180. compare = NULL;
  3181. }
  3182. rowManager = _rowManager;
  3183. numPending = 0;
  3184. endSeen = false;
  3185. remakePending = false;
  3186. deferredContinuation = false;
  3187. }
  3188. void reset()
  3189. {
  3190. heapEntries.kill();
  3191. heap.kill();
  3192. numPending = 0;
  3193. endSeen = false;
  3194. remakePending = false;
  3195. deferredContinuation = false;
  3196. }
  3197. inline bool noteEndSeen()
  3198. {
  3199. bool hadSeen = endSeen;
  3200. if (!endSeen)
  3201. makeHeap();
  3202. endSeen = true;
  3203. return !hadSeen;
  3204. }
  3205. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3206. {
  3207. if (!p->isContinuation())
  3208. append(p, seq);
  3209. else
  3210. {
  3211. ForEachItemIn(idx, heapEntries)
  3212. {
  3213. HeapEntry &h = heapEntries.item(idx);
  3214. if (h.packet == p)
  3215. {
  3216. IMessageResult *result = p->queryResult();
  3217. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3218. {
  3219. heap.zap(idx);
  3220. removeHeap(idx);
  3221. }
  3222. numPending--;
  3223. if (!numPending)
  3224. makeHeap();
  3225. return;
  3226. }
  3227. }
  3228. }
  3229. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3230. return;
  3231. }
  3232. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3233. {
  3234. HeapEntry &entry = heapEntries.item(idx);
  3235. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3236. if (!entry.current)
  3237. {
  3238. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3239. if (continuation)
  3240. {
  3241. continuation->Link();
  3242. entry.packet->Release();
  3243. entry.packet = continuation;
  3244. if (continuation->hasResult())
  3245. {
  3246. IMessageResult *result = continuation->queryResult();
  3247. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3248. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3249. }
  3250. else
  3251. {
  3252. if (continuation->isDelayed())
  3253. {
  3254. continuation->setDelayed(false);
  3255. MemoryBuffer serializedSkip;
  3256. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3257. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3258. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3259. adaptor.sentsome.signal();
  3260. }
  3261. numPending++;
  3262. }
  3263. }
  3264. else
  3265. {
  3266. heap.zap(idx);
  3267. removeHeap(idx);
  3268. idx--;
  3269. }
  3270. }
  3271. return skipped;
  3272. }
  3273. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3274. {
  3275. // We discard all rows < seekval from all entries in heap
  3276. // If this results in additional slave requests, we return NULL so that we can wait for them
  3277. // If not, we rebuild the heap (if any were skipped) and return the first row
  3278. deferredContinuation = false;
  3279. if (heap.length())
  3280. {
  3281. unsigned skipped = 0;
  3282. unsigned idx = 0;
  3283. while(heapEntries.isItem(idx))
  3284. {
  3285. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3286. idx++;
  3287. }
  3288. if (numPending)
  3289. return NULL; // can't answer yet, need more results from slaves
  3290. else
  3291. {
  3292. if (skipped)
  3293. makeHeap();
  3294. return next(wasCompleteMatch, stepExtra);
  3295. }
  3296. }
  3297. else
  3298. return NULL;
  3299. }
  3300. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3301. {
  3302. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3303. if (continuation)
  3304. {
  3305. if (continuation->isDelayed() && canDefer)
  3306. {
  3307. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3308. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3309. deferredContinuation = true;
  3310. }
  3311. else
  3312. {
  3313. deferredContinuation = false;
  3314. continuation->Link();
  3315. topEntry.packet->Release();
  3316. topEntry.packet = continuation;
  3317. if (continuation->hasResult())
  3318. {
  3319. IMessageResult *result = continuation->queryResult();
  3320. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3321. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3322. }
  3323. else
  3324. {
  3325. if (continuation->isDelayed()) // has the continuation been requested yet?
  3326. {
  3327. continuation->Link();
  3328. topEntry.packet->Release();
  3329. topEntry.packet = continuation;
  3330. continuation->setDelayed(false);
  3331. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3332. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3333. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3334. adaptor.sentsome.signal();
  3335. }
  3336. numPending++; // we are waiting for one that is already in flight
  3337. }
  3338. }
  3339. return true; // next not known yet
  3340. }
  3341. else
  3342. return false;
  3343. }
  3344. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3345. {
  3346. OwnedConstRoxieRow ret;
  3347. if (heap.length())
  3348. {
  3349. if (deferredContinuation)
  3350. {
  3351. unsigned top = heap.item(0);
  3352. HeapEntry &topEntry = heapEntries.item(top);
  3353. doContinuation(topEntry, false);
  3354. return NULL;
  3355. }
  3356. if (remakePending)
  3357. remakeHeap();
  3358. unsigned top = heap.item(0);
  3359. HeapEntry &topEntry = heapEntries.item(top);
  3360. ret.set(topEntry.current);
  3361. wasCompleteMatch = topEntry.isCompleteMatch();
  3362. const void *next = topEntry.next();
  3363. if (!next)
  3364. {
  3365. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3366. {
  3367. unsigned last = heap.popGet();
  3368. if (heap.length())
  3369. heap.replace(last, 0);
  3370. removeHeap(top);
  3371. }
  3372. }
  3373. remakePending = true;
  3374. }
  3375. return ret.getClear();
  3376. }
  3377. bool ready()
  3378. {
  3379. return endSeen && numPending == 0;
  3380. }
  3381. };
  3382. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3383. {
  3384. if (serverSideCache && !debugContext)
  3385. {
  3386. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3387. if (ret)
  3388. {
  3389. p->Release();
  3390. cached = true;
  3391. return ret;
  3392. }
  3393. }
  3394. cached = false;
  3395. return new CRoxieServerQueryPacket(p);
  3396. }
  3397. #ifdef _DEBUG
  3398. void dumpPending()
  3399. {
  3400. CriticalBlock b(pendingCrit);
  3401. ForEachItemIn(idx, pending)
  3402. {
  3403. IRoxieServerQueryPacket &p = pending.item(idx);
  3404. StringBuffer s;
  3405. unsigned __int64 dummy;
  3406. if (p.isEnd())
  3407. s.append("END");
  3408. else if (p.isLimit(dummy, dummy, dummy))
  3409. s.append("LIMIT");
  3410. else
  3411. {
  3412. IRoxieQueryPacket *i = p.queryPacket();
  3413. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3414. if (i)
  3415. {
  3416. RoxiePacketHeader &header = i->queryHeader();
  3417. header.toString(s);
  3418. }
  3419. }
  3420. DBGLOG("Pending %d %s", idx, s.str());
  3421. }
  3422. }
  3423. #endif
  3424. void abortPending()
  3425. {
  3426. CriticalBlock b(pendingCrit);
  3427. ForEachItemIn(idx, pending)
  3428. {
  3429. IRoxieServerQueryPacket &p = pending.item(idx);
  3430. if (!p.hasResult())
  3431. {
  3432. IRoxieQueryPacket *i = p.queryPacket();
  3433. if (i)
  3434. {
  3435. RoxiePacketHeader &header = i->queryHeader();
  3436. ROQ->sendAbort(header, activity.queryLogCtx());
  3437. }
  3438. }
  3439. }
  3440. pending.kill();
  3441. }
  3442. void checkDelayed()
  3443. {
  3444. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3445. {
  3446. bool allDelayed = true;
  3447. CriticalBlock b(pendingCrit);
  3448. unsigned sendIdx = (unsigned) -1;
  3449. ForEachItemIn(idx, pending)
  3450. {
  3451. IRoxieServerQueryPacket &p = pending.item(idx);
  3452. if (p.queryPacket())
  3453. {
  3454. if (p.isDelayed())
  3455. {
  3456. if (sendIdx == (unsigned) -1)
  3457. sendIdx = idx;
  3458. }
  3459. else if (!p.hasResult())
  3460. {
  3461. allDelayed = false;
  3462. break;
  3463. }
  3464. }
  3465. }
  3466. if (allDelayed && sendIdx != (unsigned) -1)
  3467. {
  3468. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3469. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3470. pending.item(sendIdx).setDelayed(false);
  3471. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3472. sentsome.signal();
  3473. }
  3474. }
  3475. else if (deferredStart)
  3476. {
  3477. CriticalBlock b(pendingCrit);
  3478. ForEachItemIn(idx, pending)
  3479. {
  3480. IRoxieServerQueryPacket &p = pending.item(idx);
  3481. if (p.isDelayed())
  3482. {
  3483. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3484. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3485. p.setDelayed(false);
  3486. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3487. sentsome.signal();
  3488. }
  3489. }
  3490. deferredStart = false;
  3491. }
  3492. }
  3493. void retryPending()
  3494. {
  3495. CriticalBlock b(pendingCrit);
  3496. checkDelayed();
  3497. ForEachItemIn(idx, pending)
  3498. {
  3499. IRoxieServerQueryPacket &p = pending.item(idx);
  3500. if (!p.hasResult() && !p.isDelayed())
  3501. {
  3502. IRoxieQueryPacket *i = p.queryPacket();
  3503. if (i)
  3504. {
  3505. if (!i->queryHeader().retry())
  3506. {
  3507. StringBuffer s;
  3508. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), activity.queryId());
  3509. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3510. throw E;
  3511. }
  3512. if (!localSlave)
  3513. {
  3514. ROQ->sendPacket(i, activity.queryLogCtx());
  3515. retriesSent++;
  3516. }
  3517. }
  3518. }
  3519. }
  3520. }
  3521. class ChannelBuffer
  3522. {
  3523. protected:
  3524. unsigned bufferLeft;
  3525. MemoryBuffer buffer;
  3526. char *nextBuf;
  3527. unsigned overflowSequence;
  3528. unsigned channel; // == bonded channel
  3529. bool needsFlush;
  3530. InterruptableSemaphore flowController;
  3531. const CRemoteResultAdaptor &owner;
  3532. CriticalSection crit;
  3533. public:
  3534. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  3535. {
  3536. overflowSequence = 0;
  3537. needsFlush = false;
  3538. bufferLeft = 0;
  3539. nextBuf = NULL;
  3540. }
  3541. void init(unsigned minSize)
  3542. {
  3543. assertex(!buffer.length());
  3544. if (minSize < MIN_PAYLOAD_SIZE)
  3545. minSize = MIN_PAYLOAD_SIZE;
  3546. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3547. unsigned bufferSize = headerSize+minSize;
  3548. if (bufferSize < mtu_size)
  3549. bufferSize = mtu_size;
  3550. buffer.reserveTruncate(bufferSize);
  3551. bufferLeft = bufferSize - headerSize;
  3552. assertex(buffer.toByteArray());
  3553. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3554. needsFlush = false;
  3555. }
  3556. inline IRoxieQueryPacket *flush()
  3557. {
  3558. CriticalBlock cb(crit);
  3559. Owned<IRoxieQueryPacket> ret;
  3560. if (needsFlush)
  3561. {
  3562. buffer.setLength(nextBuf - buffer.toByteArray());
  3563. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3564. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3565. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3566. byte * tgt = (byte*)(h+1);
  3567. owner.copyHeader(tgt, channel);
  3568. ret.setown(createRoxiePacket(buffer));
  3569. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3570. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3571. else
  3572. overflowSequence++;
  3573. needsFlush = false;
  3574. bufferLeft = 0;
  3575. if (owner.flowControlled)
  3576. {
  3577. CriticalUnblock cub(crit);
  3578. while (!flowController.wait(1000))
  3579. {
  3580. StringBuffer s;
  3581. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3582. }
  3583. }
  3584. }
  3585. return ret.getClear();
  3586. }
  3587. inline void signal()
  3588. {
  3589. if (owner.flowControlled)
  3590. flowController.signal();
  3591. }
  3592. inline void interrupt(IException *e)
  3593. {
  3594. flowController.interrupt(e);
  3595. }
  3596. inline void *getBuffer(unsigned size)
  3597. {
  3598. CriticalBlock cb(crit);
  3599. if (bufferLeft >= size)
  3600. {
  3601. needsFlush = true;
  3602. void * ret = nextBuf;
  3603. nextBuf += size;
  3604. bufferLeft -= size;
  3605. return ret;
  3606. }
  3607. else if (!needsFlush)
  3608. {
  3609. init(size);
  3610. return getBuffer(size);
  3611. }
  3612. else if (owner.mergeOrder)
  3613. {
  3614. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3615. }
  3616. else
  3617. return NULL; // will force it to flush and start a new packet
  3618. }
  3619. };
  3620. private:
  3621. friend class CRemoteResultMerger;
  3622. bool allread;
  3623. bool contextCached;
  3624. bool preserveOrder;
  3625. bool eogSent = false;
  3626. InterruptableSemaphore sentsome;
  3627. Owned <IMessageCollator> mc;
  3628. Owned<IMessageUnpackCursor> mu;
  3629. Owned<IMessageResult> mr;
  3630. ChannelBuffer **buffers;
  3631. IHThorArg &helper;
  3632. unsigned __int64 stopAfter;
  3633. unsigned resendSequence;
  3634. IHThorArg *colocalArg;
  3635. IArrayOf<IRoxieServerQueryPacket> pending;
  3636. CriticalSection pendingCrit;
  3637. IRoxieServerSideCache *serverSideCache;
  3638. unsigned sentSequence;
  3639. Owned<IOutputRowDeserializer> deserializer;
  3640. Owned<IEngineRowAllocator> rowAllocator;
  3641. CRemoteResultMerger merger;
  3642. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3643. MemoryBuffer tempRowBuffer;
  3644. Owned<ISerialStream> bufferStream;
  3645. CThorStreamDeserializerSource rowSource;
  3646. protected:
  3647. IRowManager *rowManager;
  3648. unsigned __int64 rowLimit;
  3649. unsigned __int64 keyedLimit;
  3650. IRoxieServerErrorHandler *errorHandler;
  3651. CachedOutputMetaData meta;
  3652. public:
  3653. ISteppingMeta *mergeOrder;
  3654. IRoxieSlaveContext *ctx;
  3655. IDebuggableContext *debugContext;
  3656. IRoxieServerActivity &activity;
  3657. unsigned parentExtractSize;
  3658. const byte * parentExtract;
  3659. bool flowControlled;
  3660. bool deferredStart;
  3661. MemoryBuffer logInfo;
  3662. MemoryBuffer cachedContext;
  3663. const RemoteActivityId &remoteId;
  3664. ruid_t ruid;
  3665. mutable CriticalSection buffersCrit;
  3666. unsigned processed;
  3667. cycle_t totalCycles;
  3668. bool timeActivities;
  3669. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3670. const void *getRow(IMessageUnpackCursor *mu)
  3671. {
  3672. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3673. return mu->getNext(meta.getFixedSize());
  3674. else
  3675. {
  3676. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3677. if (rowlen)
  3678. {
  3679. RecordLengthType len = *rowlen;
  3680. ReleaseRoxieRow(rowlen);
  3681. const void *slaveRec = mu->getNext(len);
  3682. if (deserializer && mu->isSerialized())
  3683. {
  3684. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3685. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3686. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3687. ReleaseRoxieRow(slaveRec);
  3688. return rowBuilder.finalizeRowClear(outsize);
  3689. }
  3690. else
  3691. return slaveRec;
  3692. }
  3693. else
  3694. return NULL;
  3695. }
  3696. }
  3697. private:
  3698. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3699. {
  3700. CriticalBlock cb(buffersCrit);
  3701. ChannelBuffer *b = buffers[channel];
  3702. if (!b && force)
  3703. {
  3704. if (!contextCached)
  3705. {
  3706. logInfo.clear();
  3707. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3708. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3709. const QueryOptions &options = ctx->queryOptions();
  3710. if (activity.queryLogCtx().isIntercepted())
  3711. loggingFlags |= LOGGING_INTERCEPTED;
  3712. if (options.timeActivities)
  3713. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3714. if (activity.queryLogCtx().isBlind())
  3715. loggingFlags |= LOGGING_BLIND;
  3716. if (options.checkingHeap)
  3717. loggingFlags |= LOGGING_CHECKINGHEAP;
  3718. if (ctx->queryWorkUnit())
  3719. loggingFlags |= LOGGING_WUID;
  3720. if (debugContext)
  3721. {
  3722. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3723. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3724. MemoryBuffer bpInfo;
  3725. debugContext->serialize(bpInfo);
  3726. bpInfo.append((__uint64)(memsize_t) &activity);
  3727. logInfo.append((unsigned short) bpInfo.length());
  3728. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3729. }
  3730. else
  3731. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3732. StringBuffer logPrefix;
  3733. activity.queryLogCtx().getLogPrefix(logPrefix);
  3734. logInfo.append(logPrefix);
  3735. activity.serializeCreateStartContext(cachedContext.clear());
  3736. activity.serializeExtra(cachedContext);
  3737. if (activity.queryVarFileInfo())
  3738. {
  3739. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3740. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3741. }
  3742. contextCached = true;
  3743. }
  3744. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3745. }
  3746. return b;
  3747. }
  3748. void processRow(const void *got)
  3749. {
  3750. processed++;
  3751. if (processed > rowLimit)
  3752. {
  3753. ReleaseRoxieRow(got);
  3754. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3755. throwUnexpected();
  3756. }
  3757. else if (processed > keyedLimit)
  3758. {
  3759. ReleaseRoxieRow(got);
  3760. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3761. throwUnexpected();
  3762. }
  3763. }
  3764. public:
  3765. IMPLEMENT_IINTERFACE;
  3766. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3767. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3768. {
  3769. ctx = _ctx;
  3770. errorHandler = _errorHandler;
  3771. colocalArg = NULL;
  3772. allread = false;
  3773. ruid = 0;
  3774. rowLimit = (unsigned __int64) -1;
  3775. keyedLimit = (unsigned __int64) -1;
  3776. contextCached = false;
  3777. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3778. buffers = new ChannelBuffer*[numChannels+1];
  3779. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3780. parentExtractSize = 0;
  3781. rowManager = NULL;
  3782. parentExtract = NULL;
  3783. debugContext = NULL;
  3784. mergeOrder = NULL;
  3785. deferredStart = false;
  3786. processed = 0;
  3787. sentSequence = 0;
  3788. resendSequence = 0;
  3789. totalCycles = 0;
  3790. serverSideCache = activity.queryServerSideCache();
  3791. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3792. rowSource.setStream(bufferStream);
  3793. timeActivities = defaultTimeActivities;
  3794. }
  3795. ~CRemoteResultAdaptor()
  3796. {
  3797. if (mc)
  3798. {
  3799. ROQ->queryReceiveManager()->detachCollator(mc);
  3800. mc.clear();
  3801. }
  3802. for (unsigned channel = 0; channel <= numChannels; channel++)
  3803. {
  3804. delete(buffers[channel]);
  3805. }
  3806. delete [] buffers;
  3807. }
  3808. void setMeta(IOutputMetaData *newmeta)
  3809. {
  3810. meta.set(newmeta);
  3811. }
  3812. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3813. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3814. virtual IRoxieServerActivity *queryActivity()
  3815. {
  3816. return &activity;
  3817. }
  3818. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3819. {
  3820. return NULL;
  3821. }
  3822. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3823. {
  3824. mergeOrder = _mergeOrder;
  3825. deferredStart = true;
  3826. }
  3827. void send(IRoxieQueryPacket *p)
  3828. {
  3829. if (p)
  3830. {
  3831. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3832. assertex(p->queryHeader().uid==ruid);
  3833. // MORE: Maybe we should base the fastlane flag on some other
  3834. // criteria !! (i.e A Roxie server prediction based on the
  3835. // activity type/activity behaviour/expected reply size .. etc).
  3836. //
  3837. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3838. // But this could still cause too many reply packets on the fatlane
  3839. // (higher priority output Q), which may cause the activities on the
  3840. // low priority output Q to not get service on time.
  3841. if ((colocalArg == 0) && // not a child query activity??
  3842. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3843. (p->queryHeader().overflowSequence == 0) &&
  3844. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3845. p->queryHeader().retries |= ROXIE_FASTLANE;
  3846. if (p->queryHeader().channel)
  3847. {
  3848. bool cached = false;
  3849. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3850. if (deferredStart)
  3851. rsqp->setDelayed(true);
  3852. rsqp->setSequence(sentSequence++);
  3853. {
  3854. CriticalBlock b(pendingCrit);
  3855. pending.append(*rsqp);
  3856. }
  3857. if (!deferredStart)
  3858. {
  3859. if (!cached)
  3860. ROQ->sendPacket(p, activity.queryLogCtx());
  3861. sentsome.signal();
  3862. }
  3863. }
  3864. else
  3865. {
  3866. // 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
  3867. // Need to add first, then send
  3868. unsigned i;
  3869. bool allCached = true;
  3870. for (i = 1; i <= numChannels; i++)
  3871. {
  3872. IRoxieQueryPacket *q = p->clonePacket(i);
  3873. bool thisChannelCached;
  3874. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3875. if (!thisChannelCached)
  3876. allCached = false;
  3877. rsqp->setSequence(sentSequence++);
  3878. if (deferredStart)
  3879. {
  3880. rsqp->setDelayed(true);
  3881. }
  3882. {
  3883. CriticalBlock b(pendingCrit);
  3884. pending.append(*rsqp);
  3885. }
  3886. if (!deferredStart)
  3887. sentsome.signal();
  3888. }
  3889. if (!allCached && !deferredStart)
  3890. ROQ->sendPacket(p, activity.queryLogCtx());
  3891. buffers[0]->signal(); // since replies won't come back on that channel...
  3892. p->Release();
  3893. }
  3894. }
  3895. }
  3896. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3897. {
  3898. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3899. size += sizeof(PartNoType);
  3900. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3901. char *buffer = (char *) b->getBuffer(size);
  3902. if (!buffer)
  3903. {
  3904. send(b->flush());
  3905. buffer = (char *) b->getBuffer(size);
  3906. }
  3907. PartNoType sp;
  3908. sp.partNo = partNo;
  3909. sp.fileNo = fileNo;
  3910. memcpy(buffer, &sp, sizeof(sp));
  3911. buffer += sizeof(sp);
  3912. return buffer;
  3913. }
  3914. void injectResult(IMessageResult *result)
  3915. {
  3916. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3917. f->setSequence(sentSequence++);
  3918. f->setResult(result);
  3919. CriticalBlock b(pendingCrit);
  3920. pending.append(*f);
  3921. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3922. }
  3923. void flush()
  3924. {
  3925. for (unsigned channel = 0; channel <= numChannels; channel++)
  3926. {
  3927. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3928. if (b)
  3929. send(b->flush());
  3930. }
  3931. }
  3932. void interruptBuffers(IException *e)
  3933. {
  3934. for (unsigned channel = 0; channel <= numChannels; channel++)
  3935. {
  3936. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3937. if (b)
  3938. b->interrupt(LINK(e));
  3939. }
  3940. }
  3941. void senddone()
  3942. {
  3943. CriticalBlock b(pendingCrit);
  3944. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3945. sentsome.signal();
  3946. }
  3947. bool fireException(IException *e)
  3948. {
  3949. {
  3950. CriticalBlock b(pendingCrit);
  3951. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3952. }
  3953. interruptBuffers(e);
  3954. if (mc)
  3955. mc->interrupt(LINK(e));
  3956. sentsome.interrupt(e);
  3957. return true;
  3958. }
  3959. virtual void onCreate(IHThorArg *_colocalArg)
  3960. {
  3961. debugContext = ctx->queryDebugContext();
  3962. colocalArg = _colocalArg;
  3963. if (meta.needsSerializeDisk())
  3964. {
  3965. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3966. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3967. }
  3968. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3969. deferredStart = true;
  3970. timeActivities = ctx->queryOptions().timeActivities;
  3971. }
  3972. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3973. {
  3974. #ifdef TRACE_STARTSTOP
  3975. if (traceStartStop)
  3976. activity.queryLogCtx().CTXLOG("RRAonstart");
  3977. #endif
  3978. sentsome.reinit();
  3979. ruid = getNextRuid();
  3980. rowManager = &ctx->queryRowManager();
  3981. if (mergeOrder)
  3982. merger.init(mergeOrder, rowManager);
  3983. if (mc)
  3984. {
  3985. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3986. }
  3987. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3988. allread = false;
  3989. mu.clear();
  3990. contextCached = false;
  3991. processed = 0;
  3992. resendSequence = 0;
  3993. sentSequence = 0;
  3994. for (unsigned channel = 0; channel <= numChannels; channel++)
  3995. {
  3996. delete(buffers[channel]);
  3997. buffers[channel] = NULL;
  3998. }
  3999. flush();
  4000. parentExtractSize = _parentExtractSize;
  4001. parentExtract = _parentExtract;
  4002. }
  4003. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4004. {
  4005. #ifdef TRACE_STARTSTOP
  4006. if (traceStartStop)
  4007. activity.queryLogCtx().CTXLOG("RRAstart");
  4008. #endif
  4009. activity.start(parentExtractSize, parentExtract, paused);
  4010. }
  4011. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  4012. {
  4013. if (ctx->queryProbeManager())
  4014. {
  4015. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  4016. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  4017. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  4018. }
  4019. {
  4020. CriticalBlock b(pendingCrit);
  4021. if (pending.length())
  4022. {
  4023. #ifdef _DEBUG
  4024. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  4025. #endif
  4026. assertex(pending.length()==0);
  4027. }
  4028. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  4029. }
  4030. sentsome.signal();
  4031. rowLimit = _rowLimit;
  4032. keyedLimit = _keyedLimit;
  4033. stopAfter = _stopAfter;
  4034. }
  4035. virtual void stop()
  4036. {
  4037. #ifdef TRACE_STARTSTOP
  4038. if (traceStartStop)
  4039. activity.queryLogCtx().CTXLOG("RRAstop");
  4040. #endif
  4041. onStop();
  4042. activity.stop();
  4043. }
  4044. void onStop()
  4045. {
  4046. #ifdef TRACE_STARTSTOP
  4047. if (traceStartStop)
  4048. activity.queryLogCtx().CTXLOG("RRAonstop");
  4049. #endif
  4050. abortPending();
  4051. interruptBuffers(NULL);
  4052. sentsome.interrupt();
  4053. if (mc) // May not be set if start() chain threw exception
  4054. mc->interrupt();
  4055. }
  4056. virtual void reset()
  4057. {
  4058. #ifdef TRACE_STARTSTOP
  4059. if (traceStartStop)
  4060. activity.queryLogCtx().CTXLOG("RRAreset");
  4061. #endif
  4062. activity.reset();
  4063. onReset();
  4064. }
  4065. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  4066. {
  4067. // Make sure parent activity calls up the tree
  4068. PointerArrayOf<IEngineRowStream> instreams;
  4069. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  4070. assertex (junction == NULL);
  4071. // I return a single strand (we could change that sometime I guess...)
  4072. streams.append(this);
  4073. return NULL;
  4074. }
  4075. virtual void resetEOF()
  4076. {
  4077. throwUnexpected();
  4078. }
  4079. virtual void onReset()
  4080. {
  4081. #ifdef TRACE_STARTSTOP
  4082. if (traceStartStop)
  4083. activity.queryLogCtx().CTXLOG("RRAonreset");
  4084. #endif
  4085. if (mc)
  4086. ROQ->queryReceiveManager()->detachCollator(mc);
  4087. merger.reset();
  4088. pending.kill();
  4089. if (mc && ctx)
  4090. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  4091. mc.clear(); // Or we won't free memory for graphs that get recreated
  4092. mu.clear(); //ditto
  4093. deferredStart = false;
  4094. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  4095. }
  4096. virtual IOutputMetaData * queryOutputMeta() const
  4097. {
  4098. return helper.queryOutputMeta();
  4099. }
  4100. virtual unsigned __int64 queryTotalCycles() const
  4101. {
  4102. return totalCycles;
  4103. }
  4104. void gatherStats(CRuntimeStatisticCollection & merged) const
  4105. {
  4106. if (rowAllocator)
  4107. rowAllocator->gatherStats(merged);
  4108. }
  4109. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4110. {
  4111. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4112. {
  4113. StringBuffer recstr;
  4114. unsigned i;
  4115. for (i = 0; i < seekLen; i++)
  4116. {
  4117. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4118. }
  4119. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4120. }
  4121. assertex(mergeOrder);
  4122. if (deferredStart)
  4123. {
  4124. CriticalBlock b(pendingCrit);
  4125. ForEachItemIn(idx, pending)
  4126. {
  4127. IRoxieServerQueryPacket &p = pending.item(idx);
  4128. if (p.isDelayed())
  4129. {
  4130. p.setDelayed(false);
  4131. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4132. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4133. MemoryBuffer serializedSkip;
  4134. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4135. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4136. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4137. sentsome.signal();
  4138. }
  4139. }
  4140. deferredStart = false;
  4141. }
  4142. SimpleActivityTimer t(totalCycles, timeActivities);
  4143. if (processed==stopAfter)
  4144. return NULL;
  4145. if (allread)
  4146. return NULL;
  4147. for (;;)
  4148. {
  4149. if (merger.ready())
  4150. {
  4151. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4152. if (got)
  4153. {
  4154. processRow(got);
  4155. return got;
  4156. }
  4157. }
  4158. if (!reload()) // MORE - should pass the seek info here...
  4159. return NULL;
  4160. }
  4161. }
  4162. virtual const void *nextRow()
  4163. {
  4164. // If we are merging then we need to do a heapsort on all
  4165. SimpleActivityTimer t(totalCycles, timeActivities);
  4166. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4167. {
  4168. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4169. }
  4170. for (;;)
  4171. {
  4172. checkDelayed();
  4173. if (processed==stopAfter)
  4174. return NULL;
  4175. if (allread)
  4176. return NULL;
  4177. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4178. const void *got = NULL;
  4179. if (mergeOrder && merger.ready())
  4180. {
  4181. bool matched = true;
  4182. got = merger.next(matched, dummySmartStepExtra);
  4183. }
  4184. else if (mu)
  4185. {
  4186. got = getRow(mu);
  4187. if (!got && meta.isGrouped() && !eogSent)
  4188. {
  4189. eogSent = true;
  4190. return NULL;
  4191. }
  4192. }
  4193. if (got)
  4194. {
  4195. processRow(got);
  4196. return got;
  4197. }
  4198. eogSent = false;
  4199. if (!reload())
  4200. return NULL;
  4201. }
  4202. }
  4203. bool reload()
  4204. {
  4205. // Wait for something to be returned from a slave....
  4206. mu.clear();
  4207. sentsome.wait();
  4208. // must be at least an endMarker on the queue since sentsome was signalled
  4209. {
  4210. CriticalBlock b(pendingCrit);
  4211. IRoxieServerQueryPacket &top = pending.item(0);
  4212. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4213. {
  4214. pending.remove(0);
  4215. return true;
  4216. }
  4217. else if (top.isEnd())
  4218. {
  4219. pending.remove(0);
  4220. allread = true;
  4221. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4222. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4223. return false;
  4224. }
  4225. else if (mergeOrder)
  4226. {
  4227. unsigned idx = 0;
  4228. bool added = false;
  4229. while (pending.isItem(idx))
  4230. {
  4231. IRoxieServerQueryPacket &item = pending.item(idx);
  4232. if (item.isEnd())
  4233. {
  4234. if (merger.noteEndSeen())
  4235. {
  4236. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4237. added = true;
  4238. }
  4239. break;
  4240. }
  4241. else if (item.hasResult())
  4242. {
  4243. merger.noteResult(&item, item.getSequence());
  4244. pending.remove(idx);
  4245. added = true;
  4246. }
  4247. else if (item.isContinuation())
  4248. idx++;
  4249. else
  4250. break;
  4251. }
  4252. if (added)
  4253. return true;
  4254. }
  4255. else if (top.hasResult())
  4256. {
  4257. mr.setown(pending.item(0).getResult());
  4258. mu.setown(mr->getCursor(rowManager));
  4259. pending.remove(0);
  4260. return true;
  4261. }
  4262. }
  4263. getNextUnpacker();
  4264. return true;
  4265. }
  4266. void getNextUnpacker()
  4267. {
  4268. mu.clear();
  4269. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4270. for (;;)
  4271. {
  4272. checkDelayed();
  4273. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4274. activity.queryContext()->checkAbort();
  4275. bool anyActivity;
  4276. if (ctxTraceLevel > 5)
  4277. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4278. mr.setown(mc->getNextResult(timeout, anyActivity));
  4279. if (ctxTraceLevel > 6)
  4280. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4281. activity.queryContext()->checkAbort();
  4282. if (mr)
  4283. {
  4284. unsigned roxieHeaderLen;
  4285. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4286. #ifdef _DEBUG
  4287. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4288. #endif
  4289. if (ctxTraceLevel > 5)
  4290. {
  4291. StringBuffer s;
  4292. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4293. }
  4294. CriticalBlock b(pendingCrit);
  4295. unsigned idx = 0;
  4296. IRoxieServerQueryPacket *original = NULL;
  4297. IRoxieQueryPacket *op;
  4298. while (pending.isItem(idx))
  4299. {
  4300. original = &pending.item(idx);
  4301. op = original->queryPacket();
  4302. if (op && header.matchPacket(op->queryHeader()))
  4303. break;
  4304. original = NULL;
  4305. idx++;
  4306. }
  4307. if (!original || original->hasResult())
  4308. {
  4309. switch (header.activityId)
  4310. {
  4311. case ROXIE_FILECALLBACK:
  4312. {
  4313. // tell slave to abort
  4314. //if (ctxTraceLevel > 5)
  4315. {
  4316. StringBuffer s;
  4317. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4318. }
  4319. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4320. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4321. if (len)
  4322. {
  4323. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4324. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4325. const char *rowdata = (const char *) row.get();
  4326. // bool isOpt = * (bool *) rowdata;
  4327. // bool isLocal = * (bool *) (rowdata+1);
  4328. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4329. }
  4330. else
  4331. throwUnexpected();
  4332. break;
  4333. }
  4334. // MORE - ROXIE_ALIVE perhaps should go here too
  4335. default:
  4336. if (ctxTraceLevel > 3)
  4337. activity.queryLogCtx().CTXLOG("Discarding packet %p %x - original %p is NULL or has result already", mr.get(), header.activityId, original);
  4338. mr->discard();
  4339. break;
  4340. }
  4341. mr.clear();
  4342. }
  4343. else
  4344. {
  4345. resultsReceived++;
  4346. switch (header.activityId)
  4347. {
  4348. case ROXIE_DEBUGCALLBACK:
  4349. {
  4350. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4351. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4352. if (len)
  4353. {
  4354. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4355. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4356. char *rowdata = (char *) row.get();
  4357. if (ctxTraceLevel > 5)
  4358. {
  4359. StringBuffer s;
  4360. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4361. }
  4362. MemoryBuffer slaveInfo;
  4363. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4364. unsigned debugSequence;
  4365. slaveInfo.read(debugSequence);
  4366. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4367. if (!reply)
  4368. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4369. if (reply)
  4370. {
  4371. original->setDebugResponse(debugSequence, reply);
  4372. ROQ->sendPacket(reply, activity.queryLogCtx());
  4373. }
  4374. }
  4375. else
  4376. throwUnexpected();
  4377. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4378. // Leave original message on pending queue in original location - this is not a reply to it.
  4379. break;
  4380. }
  4381. case ROXIE_FILECALLBACK:
  4382. {
  4383. // we need to send back to the slave a message containing the file info requested.
  4384. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4385. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4386. if (len)
  4387. {
  4388. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4389. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4390. const char *rowdata = (const char *) row.get();
  4391. bool isOpt = * (bool *) rowdata;
  4392. bool isLocal = * (bool *) (rowdata+1);
  4393. const char *lfn = rowdata+2;
  4394. if (ctxTraceLevel > 5)
  4395. {
  4396. StringBuffer s;
  4397. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4398. }
  4399. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4400. }
  4401. else
  4402. throwUnexpected();
  4403. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4404. // Leave original message on pending queue in original location - this is not a reply to it.
  4405. break;
  4406. }
  4407. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4408. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4409. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4410. throwUnexpected();
  4411. case ROXIE_LIMIT_EXCEEDED:
  4412. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4413. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4414. throwUnexpected();
  4415. case ROXIE_TRACEINFO:
  4416. {
  4417. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4418. for (;;)
  4419. {
  4420. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4421. if (rowlen)
  4422. {
  4423. char *logInfo = (char *) extra->getNext(*rowlen);
  4424. MemoryBuffer buf;
  4425. buf.setBuffer(*rowlen, logInfo, false);
  4426. switch ((TracingCategory) *logInfo)
  4427. {
  4428. case LOG_TRACING:
  4429. case LOG_ERROR:
  4430. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4431. break;
  4432. case LOG_STATVALUES:
  4433. buf.skip(1);
  4434. activity.mergeStats(buf);
  4435. break;
  4436. case LOG_CHILDCOUNT:
  4437. case LOG_CHILDSTATS:
  4438. //These need rethinking - all child stats should be serialized in a single block, and should be merged into
  4439. //the information for an activity, ready for reporting later
  4440. unsigned graphId, childId;
  4441. buf.skip(1);
  4442. buf.read(graphId);
  4443. buf.read(childId);
  4444. if (*logInfo == LOG_CHILDCOUNT)
  4445. {
  4446. unsigned idx;
  4447. unsigned childProcessed;
  4448. unsigned childStrands;
  4449. buf.read(idx);
  4450. buf.read(childProcessed);
  4451. buf.read(childStrands);
  4452. if (traceLevel > 5)
  4453. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4454. //activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4455. }
  4456. else
  4457. {
  4458. CRuntimeStatisticCollection childStats(allStatistics);
  4459. childStats.deserialize(buf);
  4460. if (traceLevel > 5)
  4461. {
  4462. StringBuffer s;
  4463. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4464. }
  4465. //activity.queryContext()->mergeActivityStats(childStats, graphId, childId);
  4466. activity.mergeStats(childStats);
  4467. }
  4468. }
  4469. ReleaseRoxieRow(rowlen);
  4470. ReleaseRoxieRow(logInfo);
  4471. }
  4472. else
  4473. break;
  4474. }
  4475. break;
  4476. }
  4477. case ROXIE_EXCEPTION:
  4478. if (ctxTraceLevel > 1)
  4479. {
  4480. StringBuffer s;
  4481. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4482. }
  4483. op->queryHeader().noteException(header.retries);
  4484. if (op->queryHeader().allChannelsFailed())
  4485. {
  4486. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4487. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4488. throwRemoteException(exceptionData);
  4489. }
  4490. // Leave it on pending queue in original location
  4491. break;
  4492. case ROXIE_ALIVE:
  4493. if (ctxTraceLevel > 4)
  4494. {
  4495. StringBuffer s;
  4496. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4497. }
  4498. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4499. // Leave it on pending queue in original location
  4500. break;
  4501. default:
  4502. if (header.retries & ROXIE_RETRIES_MASK)
  4503. retriesNeeded++;
  4504. unsigned metaLen;
  4505. const void *metaData = mr->getMessageMetadata(metaLen);
  4506. if (metaLen)
  4507. {
  4508. // We got back first chunk but there is more.
  4509. // resend the packet, with the cursor info provided.
  4510. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4511. if (ctxTraceLevel > 1)
  4512. {
  4513. StringBuffer s;
  4514. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4515. }
  4516. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4517. {
  4518. StringBuffer s;
  4519. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4520. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4521. throwUnexpected();
  4522. }
  4523. MemoryBuffer nextQuery;
  4524. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4525. nextQuery.append(metaLen, metaData);
  4526. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4527. nextQuery.append(op->getContextLength(), op->queryContextData());
  4528. if (resendSequence == CONTINUESEQUENCE_MAX)
  4529. {
  4530. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4531. resendSequence = 1;
  4532. }
  4533. else
  4534. resendSequence++;
  4535. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4536. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4537. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4538. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4539. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4540. fqp->setSequence(original->getSequence());
  4541. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4542. original->setContinuation(LINK(fqp));
  4543. if (mergeOrder)
  4544. fqp->setDelayed(true);
  4545. else
  4546. {
  4547. ROQ->sendPacket(resend, activity.queryLogCtx());
  4548. sentsome.signal();
  4549. }
  4550. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4551. }
  4552. else
  4553. {
  4554. if (serverSideCache)
  4555. serverSideCache->noteCachedResult(original, mr);
  4556. }
  4557. unsigned channel = header.channel;
  4558. {
  4559. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4560. if (b)
  4561. b->signal();
  4562. }
  4563. original->setResult(mr.getClear());
  4564. sentsome.signal();
  4565. return;
  4566. }
  4567. }
  4568. }
  4569. else
  4570. {
  4571. if (!anyActivity && !localSlave)
  4572. {
  4573. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4574. retryPending();
  4575. }
  4576. }
  4577. }
  4578. }
  4579. inline unsigned headerLength() const
  4580. {
  4581. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4582. }
  4583. void copyHeader(byte *tgt, unsigned channel) const
  4584. {
  4585. unsigned len = logInfo.length();
  4586. memcpy(tgt, logInfo.toByteArray(), len);
  4587. tgt += len;
  4588. *(unsigned *) tgt = parentExtractSize;
  4589. tgt += sizeof(unsigned);
  4590. memcpy(tgt, parentExtract, parentExtractSize);
  4591. tgt += parentExtractSize;
  4592. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4593. tgt += cachedContext.length();
  4594. }
  4595. };
  4596. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4597. {
  4598. Owned <IException> exception;
  4599. bool skipping;
  4600. ConstPointerArray buff;
  4601. unsigned index;
  4602. bool pulled;
  4603. void pullInput()
  4604. {
  4605. try
  4606. {
  4607. if (exception)
  4608. throw exception.getClear();
  4609. unsigned __int64 count = 0;
  4610. for (;;)
  4611. {
  4612. const void * next = CRemoteResultAdaptor::nextRow();
  4613. if (next == NULL)
  4614. {
  4615. next = CRemoteResultAdaptor::nextRow();
  4616. if(next == NULL)
  4617. break;
  4618. buff.append(NULL);
  4619. }
  4620. count++;
  4621. if (count > rowLimit)
  4622. {
  4623. ReleaseRoxieRow(next);
  4624. ReleaseRoxieRows(buff);
  4625. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4626. throwUnexpected();
  4627. }
  4628. else if (count > keyedLimit)
  4629. {
  4630. ReleaseRoxieRow(next);
  4631. ReleaseRoxieRows(buff);
  4632. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4633. throwUnexpected();
  4634. }
  4635. buff.append(next);
  4636. }
  4637. }
  4638. catch (IException *E)
  4639. {
  4640. if (QUERYINTERFACE(E, LimitSkipException))
  4641. {
  4642. Owned<IException> cleanup = E;
  4643. ReleaseRoxieRows(buff);
  4644. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4645. if (onfail)
  4646. buff.append(onfail);
  4647. }
  4648. else
  4649. throw;
  4650. }
  4651. pulled = true;
  4652. }
  4653. public:
  4654. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4655. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4656. {
  4657. skipping = _skipping;
  4658. index = 0;
  4659. pulled = false;
  4660. }
  4661. void setException(IException *E)
  4662. {
  4663. exception.setown(E);
  4664. }
  4665. virtual void onReset()
  4666. {
  4667. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4668. buff.kill();
  4669. index = 0;
  4670. pulled = false;
  4671. exception.clear();
  4672. CRemoteResultAdaptor::onReset();
  4673. }
  4674. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4675. {
  4676. index = 0;
  4677. pulled = false;
  4678. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4679. }
  4680. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4681. {
  4682. // 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
  4683. if (exception)
  4684. throw exception.getClear();
  4685. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4686. }
  4687. virtual const void *nextRow()
  4688. {
  4689. if (skipping)
  4690. {
  4691. if(!pulled)
  4692. pullInput();
  4693. if(buff.isItem(index))
  4694. {
  4695. const void * next = buff.item(index++);
  4696. if(next)
  4697. processed++;
  4698. return next;
  4699. }
  4700. return NULL;
  4701. }
  4702. else
  4703. {
  4704. if (exception)
  4705. throw exception.getClear();
  4706. return CRemoteResultAdaptor::nextRow();
  4707. }
  4708. }
  4709. };
  4710. //=================================================================================
  4711. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4712. {
  4713. IHThorApplyArg &helper;
  4714. public:
  4715. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4716. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4717. {
  4718. }
  4719. virtual void onExecute()
  4720. {
  4721. helper.start();
  4722. for (;;)
  4723. {
  4724. const void * next = inputStream->ungroupedNextRow();
  4725. if (!next)
  4726. break;
  4727. helper.apply(next);
  4728. ReleaseRoxieRow(next);
  4729. }
  4730. helper.end();
  4731. }
  4732. };
  4733. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4734. {
  4735. bool isRoot;
  4736. public:
  4737. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4738. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4739. {
  4740. }
  4741. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4742. {
  4743. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4744. }
  4745. virtual bool isSink() const
  4746. {
  4747. return isRoot;
  4748. }
  4749. };
  4750. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4751. {
  4752. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4753. }
  4754. //=================================================================================
  4755. class CRoxieServerNullActivity : public CRoxieServerActivity
  4756. {
  4757. public:
  4758. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4759. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4760. {
  4761. }
  4762. virtual const void *nextRow()
  4763. {
  4764. return NULL;
  4765. }
  4766. };
  4767. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4768. {
  4769. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4770. }
  4771. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4772. {
  4773. public:
  4774. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4775. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4776. {
  4777. }
  4778. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4779. {
  4780. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4781. }
  4782. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4783. {
  4784. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4785. }
  4786. };
  4787. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4788. {
  4789. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4790. }
  4791. //=================================================================================
  4792. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4793. {
  4794. public:
  4795. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4796. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4797. {
  4798. }
  4799. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4800. {
  4801. return input->gatherConjunctions(collector);
  4802. }
  4803. virtual void resetEOF()
  4804. {
  4805. inputStream->resetEOF();
  4806. }
  4807. virtual const void *nextRow()
  4808. {
  4809. const void * next = inputStream->nextRow();
  4810. if (next)
  4811. processed++;
  4812. return next;
  4813. }
  4814. virtual bool isPassThrough()
  4815. {
  4816. return true;
  4817. }
  4818. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4819. {
  4820. ActivityTimer t(totalCycles, timeActivities);
  4821. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4822. if (next)
  4823. processed++;
  4824. return next;
  4825. }
  4826. IInputSteppingMeta * querySteppingMeta()
  4827. {
  4828. return input->querySteppingMeta();
  4829. }
  4830. };
  4831. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4832. {
  4833. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4834. }
  4835. //=================================================================================
  4836. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4837. {
  4838. protected:
  4839. bool eof;
  4840. bool first;
  4841. public:
  4842. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4843. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4844. {
  4845. eof = false;
  4846. first = true;
  4847. }
  4848. ~CRoxieServerChildBaseActivity()
  4849. {
  4850. }
  4851. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4852. {
  4853. eof = false;
  4854. first = true;
  4855. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4856. }
  4857. };
  4858. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4859. {
  4860. public:
  4861. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4862. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4863. {
  4864. }
  4865. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4866. {
  4867. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4868. }
  4869. };
  4870. //=================================================================================
  4871. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4872. {
  4873. IHThorChildIteratorArg &helper;
  4874. public:
  4875. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4876. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4877. {
  4878. }
  4879. virtual bool needsAllocator() const { return true; }
  4880. virtual const void *nextRow()
  4881. {
  4882. ActivityTimer t(totalCycles, timeActivities);
  4883. if (eof)
  4884. return NULL;
  4885. bool ok;
  4886. if (first)
  4887. {
  4888. ok = helper.first();
  4889. first = false;
  4890. }
  4891. else
  4892. ok = helper.next();
  4893. try
  4894. {
  4895. while (ok)
  4896. {
  4897. processed++;
  4898. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4899. unsigned outSize = helper.transform(rowBuilder);
  4900. if (outSize)
  4901. return rowBuilder.finalizeRowClear(outSize);
  4902. ok = helper.next();
  4903. }
  4904. }
  4905. catch (IException *E)
  4906. {
  4907. throw makeWrappedException(E);
  4908. }
  4909. eof = true;
  4910. return NULL;
  4911. }
  4912. };
  4913. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4914. {
  4915. public:
  4916. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4917. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4918. {
  4919. }
  4920. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4921. {
  4922. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4923. }
  4924. };
  4925. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4926. {
  4927. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4928. }
  4929. //=================================================================================
  4930. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4931. {
  4932. IHThorChildNormalizeArg &helper;
  4933. public:
  4934. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4935. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4936. {
  4937. }
  4938. virtual bool needsAllocator() const { return true; }
  4939. virtual const void *nextRow()
  4940. {
  4941. ActivityTimer t(totalCycles, timeActivities);
  4942. if (eof)
  4943. return NULL;
  4944. bool ok;
  4945. if (first)
  4946. {
  4947. ok = helper.first();
  4948. first = false;
  4949. }
  4950. else
  4951. ok = helper.next();
  4952. if (ok)
  4953. {
  4954. try
  4955. {
  4956. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4957. do {
  4958. unsigned outSize = helper.transform(rowBuilder);
  4959. if (outSize)
  4960. {
  4961. processed++;
  4962. return rowBuilder.finalizeRowClear(outSize);
  4963. }
  4964. ok = helper.next();
  4965. }
  4966. while (ok);
  4967. }
  4968. catch (IException *E)
  4969. {
  4970. throw makeWrappedException(E);
  4971. }
  4972. }
  4973. eof = true;
  4974. return NULL;
  4975. }
  4976. };
  4977. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4978. {
  4979. public:
  4980. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4981. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4982. {
  4983. }
  4984. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4985. {
  4986. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  4987. }
  4988. };
  4989. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4990. {
  4991. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4992. }
  4993. //=================================================================================
  4994. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4995. {
  4996. IHThorChildAggregateArg &helper;
  4997. public:
  4998. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4999. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  5000. {
  5001. }
  5002. virtual bool needsAllocator() const { return true; }
  5003. virtual const void *nextRow()
  5004. {
  5005. ActivityTimer t(totalCycles, timeActivities);
  5006. if (eof)
  5007. return NULL;
  5008. eof = true;
  5009. processed++;
  5010. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5011. helper.clearAggregate(rowBuilder);
  5012. helper.processRows(rowBuilder);
  5013. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  5014. return rowBuilder.finalizeRowClear(finalSize);
  5015. }
  5016. };
  5017. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5018. {
  5019. public:
  5020. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5021. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5022. {
  5023. }
  5024. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5025. {
  5026. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  5027. }
  5028. };
  5029. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5030. {
  5031. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5032. }
  5033. //=================================================================================
  5034. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  5035. {
  5036. IHThorChildGroupAggregateArg &helper;
  5037. RowAggregator aggregated;
  5038. public:
  5039. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  5040. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5041. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  5042. aggregated(helper, helper)
  5043. {
  5044. }
  5045. void processRow(const void * next)
  5046. {
  5047. aggregated.addRow(next);
  5048. }
  5049. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5050. {
  5051. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5052. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  5053. }
  5054. virtual void reset()
  5055. {
  5056. aggregated.reset();
  5057. CRoxieServerChildBaseActivity::reset();
  5058. }
  5059. virtual bool needsAllocator() const { return true; }
  5060. virtual const void *nextRow()
  5061. {
  5062. ActivityTimer t(totalCycles, timeActivities);
  5063. if (eof)
  5064. return NULL;
  5065. if (first)
  5066. {
  5067. helper.processRows(this);
  5068. first = false;
  5069. }
  5070. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  5071. if (next)
  5072. {
  5073. processed++;
  5074. return next->finalizeRowClear();
  5075. }
  5076. eof = true;
  5077. return NULL;
  5078. }
  5079. };
  5080. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5081. {
  5082. public:
  5083. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5084. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5085. {
  5086. }
  5087. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5088. {
  5089. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  5090. }
  5091. };
  5092. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5093. {
  5094. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5095. }
  5096. //=================================================================================
  5097. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  5098. {
  5099. IHThorChildThroughNormalizeArg &helper;
  5100. const void * lastInput;
  5101. unsigned numProcessedLastGroup;
  5102. bool ok;
  5103. public:
  5104. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5105. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5106. {
  5107. lastInput = NULL;
  5108. numProcessedLastGroup = 0;
  5109. ok = false;
  5110. }
  5111. virtual void stop()
  5112. {
  5113. CRoxieServerChildBaseActivity::stop();
  5114. ReleaseRoxieRow(lastInput);
  5115. lastInput = NULL;
  5116. }
  5117. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5118. {
  5119. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5120. numProcessedLastGroup = processed;
  5121. ok = false;
  5122. }
  5123. virtual bool needsAllocator() const { return true; }
  5124. virtual const void *nextRow()
  5125. {
  5126. ActivityTimer t(totalCycles, timeActivities);
  5127. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5128. for (;;)
  5129. {
  5130. if (ok)
  5131. ok = helper.next();
  5132. while (!ok)
  5133. {
  5134. ReleaseRoxieRow(lastInput);
  5135. lastInput = inputStream->nextRow();
  5136. if (!lastInput)
  5137. {
  5138. if (numProcessedLastGroup != processed)
  5139. {
  5140. numProcessedLastGroup = processed;
  5141. return NULL;
  5142. }
  5143. lastInput = inputStream->nextRow();
  5144. if (!lastInput)
  5145. return NULL;
  5146. }
  5147. ok = helper.first(lastInput);
  5148. }
  5149. try
  5150. {
  5151. do
  5152. {
  5153. unsigned outSize = helper.transform(rowBuilder);
  5154. if (outSize)
  5155. {
  5156. processed++;
  5157. return rowBuilder.finalizeRowClear(outSize);
  5158. }
  5159. ok = helper.next();
  5160. } while (ok);
  5161. }
  5162. catch (IException *E)
  5163. {
  5164. throw makeWrappedException(E);
  5165. }
  5166. }
  5167. }
  5168. };
  5169. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5170. {
  5171. public:
  5172. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5173. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5174. {
  5175. }
  5176. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5177. {
  5178. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5179. }
  5180. };
  5181. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5182. {
  5183. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5184. }
  5185. //=================================================================================
  5186. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5187. {
  5188. IHThorDistributionArg &helper;
  5189. public:
  5190. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5191. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5192. {
  5193. }
  5194. virtual void onExecute()
  5195. {
  5196. MemoryAttr ma;
  5197. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5198. helper.clearAggregate(accumulator);
  5199. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5200. for (;;)
  5201. {
  5202. if (!nextrec)
  5203. {
  5204. nextrec.setown(inputStream->nextRow());
  5205. if (!nextrec)
  5206. break;
  5207. }
  5208. helper.process(accumulator, nextrec);
  5209. nextrec.setown(inputStream->nextRow());
  5210. }
  5211. StringBuffer result;
  5212. result.append("<XML>");
  5213. helper.gatherResult(accumulator, result);
  5214. result.append("</XML>");
  5215. helper.sendResult(result.length(), result.str());
  5216. helper.destruct(accumulator);
  5217. }
  5218. };
  5219. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5220. {
  5221. bool isRoot;
  5222. public:
  5223. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5224. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5225. {
  5226. }
  5227. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5228. {
  5229. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5230. }
  5231. virtual bool isSink() const
  5232. {
  5233. return isRoot;
  5234. }
  5235. };
  5236. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5237. {
  5238. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5239. }
  5240. //=================================================================================
  5241. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5242. {
  5243. IHThorLinkedRawIteratorArg &helper;
  5244. public:
  5245. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5246. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5247. {
  5248. }
  5249. virtual const void *nextRow()
  5250. {
  5251. ActivityTimer t(totalCycles, timeActivities);
  5252. const void *ret =helper.next();
  5253. if (ret)
  5254. {
  5255. LinkRoxieRow(ret);
  5256. processed++;
  5257. }
  5258. return ret;
  5259. }
  5260. };
  5261. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5262. {
  5263. public:
  5264. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5265. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5266. {
  5267. }
  5268. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5269. {
  5270. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5271. }
  5272. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5273. {
  5274. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5275. }
  5276. };
  5277. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5278. {
  5279. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5280. }
  5281. //=================================================================================
  5282. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5283. {
  5284. public:
  5285. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5286. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5287. {
  5288. }
  5289. virtual const void *nextRow()
  5290. {
  5291. throwUnexpected();
  5292. }
  5293. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5294. {
  5295. try
  5296. {
  5297. start(parentExtractSize, parentExtract, false);
  5298. {
  5299. ActivityTimer t(totalCycles, timeActivities);
  5300. MemoryBuffer result;
  5301. IRecordSize * inputMeta = input->queryOutputMeta();
  5302. for (;;)
  5303. {
  5304. const void *nextrec = inputStream->ungroupedNextRow();
  5305. if (!nextrec)
  5306. break;
  5307. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5308. ReleaseRoxieRow(nextrec);
  5309. }
  5310. retSize = result.length();
  5311. ret = result.detach();
  5312. }
  5313. stop();
  5314. reset();
  5315. }
  5316. catch(IException *E)
  5317. {
  5318. ctx->notifyAbort(E);
  5319. abort();
  5320. reset();
  5321. throw;
  5322. }
  5323. catch(...)
  5324. {
  5325. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5326. ctx->notifyAbort(E);
  5327. abort();
  5328. reset();
  5329. throw;
  5330. }
  5331. }
  5332. };
  5333. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5334. {
  5335. bool isRoot;
  5336. public:
  5337. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5338. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5339. {
  5340. }
  5341. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5342. {
  5343. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5344. }
  5345. virtual bool isSink() const
  5346. {
  5347. return isRoot;
  5348. }
  5349. };
  5350. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5351. {
  5352. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5353. }
  5354. //=================================================================================
  5355. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5356. {
  5357. IHThorInlineTableArg &helper;
  5358. __uint64 curRow;
  5359. __uint64 numRows;
  5360. public:
  5361. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5362. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5363. {
  5364. curRow = 0;
  5365. numRows = 0;
  5366. }
  5367. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5368. {
  5369. curRow = 0;
  5370. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5371. numRows = helper.numRows();
  5372. }
  5373. virtual bool needsAllocator() const { return true; }
  5374. virtual const void *nextRow()
  5375. {
  5376. ActivityTimer t(totalCycles, timeActivities);
  5377. // Filtering empty rows, returns the next valid row
  5378. while (curRow < numRows)
  5379. {
  5380. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5381. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5382. if (outSize)
  5383. {
  5384. processed++;
  5385. return rowBuilder.finalizeRowClear(outSize);
  5386. }
  5387. }
  5388. return NULL;
  5389. }
  5390. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5391. {
  5392. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5393. }
  5394. };
  5395. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5396. {
  5397. IHThorInlineTableArg &helper;
  5398. __uint64 numRows;
  5399. //An inline table that isn't stranded
  5400. class InlineTableSimpleProcessor : public StrandProcessor
  5401. {
  5402. protected:
  5403. IHThorInlineTableArg &helper;
  5404. __uint64 curRow;
  5405. __uint64 maxRows;
  5406. public:
  5407. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5408. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5409. {
  5410. }
  5411. virtual void start() override
  5412. {
  5413. StrandProcessor::start();
  5414. curRow = 0;
  5415. maxRows = queryParent().numRows;
  5416. }
  5417. virtual const void * nextRow()
  5418. {
  5419. ActivityTimer t(totalCycles, timeActivities);
  5420. //Return rows while the current section is active
  5421. while (curRow < maxRows)
  5422. {
  5423. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5424. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5425. if (outSize)
  5426. {
  5427. processed++;
  5428. return rowBuilder.finalizeRowClear(outSize);
  5429. }
  5430. }
  5431. return NULL;
  5432. }
  5433. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5434. };
  5435. class InlineTableStrandProcessor : public StrandProcessor
  5436. {
  5437. protected:
  5438. IHThorInlineTableArg &helper;
  5439. unsigned whichStrand;
  5440. unsigned numStrands = 0;
  5441. __uint64 sectionSize;
  5442. __uint64 curRow = 0;
  5443. __uint64 sectionMaxRows = 0;
  5444. __uint64 maxRows = 0;
  5445. bool isOrdered;
  5446. bool eosPending;
  5447. public:
  5448. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5449. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5450. {
  5451. sectionSize = queryParent().strandOptions.blockSize;
  5452. eosPending = false;
  5453. }
  5454. virtual void start() override
  5455. {
  5456. StrandProcessor::start();
  5457. numStrands = queryParent().numStrands();
  5458. maxRows = queryParent().numRows;
  5459. curRow = std::min(whichStrand * sectionSize, maxRows);
  5460. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5461. eosPending = isOrdered && (curRow != maxRows);
  5462. }
  5463. virtual const void * nextRow()
  5464. {
  5465. ActivityTimer t(totalCycles, timeActivities);
  5466. for (;;)
  5467. {
  5468. //Return rows while the current section is active
  5469. while (curRow < sectionMaxRows)
  5470. {
  5471. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5472. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5473. if (outSize)
  5474. {
  5475. processed++;
  5476. return rowBuilder.finalizeRowClear(outSize);
  5477. }
  5478. }
  5479. if (curRow == maxRows)
  5480. return NULL;
  5481. //Update current position to the next section
  5482. curRow += (numStrands - 1) * sectionSize;
  5483. if (curRow > maxRows)
  5484. curRow = maxRows;
  5485. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5486. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5487. if (eosPending)
  5488. {
  5489. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5490. eosPending = isOrdered && (curRow != maxRows);
  5491. return queryEndOfSectionMarker();
  5492. }
  5493. }
  5494. }
  5495. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5496. };
  5497. public:
  5498. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5499. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5500. {
  5501. numRows = 0;
  5502. }
  5503. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5504. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5505. {
  5506. if (strandOptions.numStrands <= 1)
  5507. return new InlineTableSimpleProcessor(*this, helper);
  5508. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5509. }
  5510. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5511. {
  5512. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5513. numRows = helper.numRows();
  5514. onStartStrands();
  5515. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5516. }
  5517. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5518. {
  5519. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5520. }
  5521. };
  5522. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5523. {
  5524. StrandOptions strandOptions;
  5525. public:
  5526. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5527. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5528. {
  5529. optStableInput = false; // do not force the output to be ordered
  5530. }
  5531. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5532. {
  5533. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5534. }
  5535. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5536. {
  5537. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5538. }
  5539. };
  5540. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5541. {
  5542. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5543. }
  5544. //=================================================================================
  5545. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5546. {
  5547. IHThorWorkunitReadArg &helper;
  5548. CriticalSection readerCrit;
  5549. Owned<IWorkUnitRowReader> wuReader;
  5550. public:
  5551. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5552. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5553. {
  5554. }
  5555. virtual void onCreate(IHThorArg *_colocalParent)
  5556. {
  5557. CRoxieServerActivity::onCreate(_colocalParent);
  5558. if (!ctx->queryServerContext())
  5559. {
  5560. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5561. }
  5562. }
  5563. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5564. {
  5565. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5566. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5567. OwnedRoxieString fromWuid(helper.getWUID());
  5568. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5569. // MORE _ should that be in onCreate?
  5570. }
  5571. virtual void reset()
  5572. {
  5573. {
  5574. CriticalBlock b(readerCrit);
  5575. wuReader.clear();
  5576. }
  5577. CRoxieServerActivity::reset();
  5578. };
  5579. virtual bool needsAllocator() const { return true; }
  5580. virtual const void *nextRow()
  5581. {
  5582. ActivityTimer t(totalCycles, timeActivities);
  5583. Linked<IWorkUnitRowReader> useReader;
  5584. {
  5585. CriticalBlock b(readerCrit);
  5586. if (!wuReader)
  5587. return NULL;
  5588. useReader.set(wuReader);
  5589. }
  5590. const void *ret = useReader->nextRow();
  5591. if (ret)
  5592. processed++;
  5593. return ret;
  5594. }
  5595. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5596. {
  5597. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5598. }
  5599. };
  5600. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5601. {
  5602. public:
  5603. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5604. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5605. {
  5606. }
  5607. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5608. {
  5609. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5610. }
  5611. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5612. {
  5613. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5614. }
  5615. };
  5616. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5617. {
  5618. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5619. }
  5620. //=================================================================================
  5621. interface ILocalGraphEx : public IEclGraphResults
  5622. {
  5623. public:
  5624. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5625. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5626. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5627. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5628. };
  5629. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5630. {
  5631. public:
  5632. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5633. IMPLEMENT_IINTERFACE
  5634. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5635. {
  5636. connectInputStreams(ctx, consumerOrdered);
  5637. streams.append(this);
  5638. return NULL;
  5639. }
  5640. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5641. {
  5642. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5643. }
  5644. virtual IOutputMetaData * queryOutputMeta() const
  5645. {
  5646. return input->queryOutputMeta();
  5647. }
  5648. virtual unsigned __int64 queryTotalCycles() const
  5649. {
  5650. return input->queryTotalCycles();
  5651. }
  5652. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5653. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5654. virtual IRoxieServerActivity *queryActivity()
  5655. {
  5656. return input->queryActivity();
  5657. }
  5658. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5659. {
  5660. return input->queryIndexReadActivity();
  5661. }
  5662. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5663. {
  5664. CriticalBlock procedure(cs);
  5665. input->start(parentExtractSize, parentExtract, paused);
  5666. startJunction(junction);
  5667. }
  5668. virtual void stop()
  5669. {
  5670. CriticalBlock procedure(cs);
  5671. inputStream->stop();
  5672. }
  5673. virtual void reset()
  5674. {
  5675. CriticalBlock procedure(cs);
  5676. input->reset();
  5677. resetJunction(junction);
  5678. }
  5679. virtual void resetEOF()
  5680. {
  5681. CriticalBlock procedure(cs);
  5682. inputStream->resetEOF();
  5683. }
  5684. virtual const void *nextRow()
  5685. {
  5686. CriticalBlock procedure(cs);
  5687. return inputStream->nextRow();
  5688. }
  5689. virtual bool nextGroup(ConstPointerArray & group)
  5690. {
  5691. CriticalBlock procedure(cs);
  5692. return inputStream->nextGroup(group);
  5693. }
  5694. private:
  5695. CriticalSection cs;
  5696. Linked<IFinalRoxieInput> input;
  5697. Linked<IEngineRowStream> inputStream;
  5698. Owned<IStrandJunction> junction;
  5699. unsigned sourceIdx;
  5700. };
  5701. //=================================================================================
  5702. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5703. {
  5704. public:
  5705. IMPLEMENT_IINTERFACE;
  5706. CPseudoRoxieInput()
  5707. {
  5708. }
  5709. virtual unsigned __int64 queryTotalCycles() const
  5710. {
  5711. return 0;
  5712. }
  5713. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5714. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5715. virtual IRoxieServerActivity *queryActivity()
  5716. {
  5717. throwUnexpected();
  5718. }
  5719. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5720. {
  5721. throwUnexpected();
  5722. }
  5723. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5724. {
  5725. assertex(!idx);
  5726. streams.append(this);
  5727. return NULL;
  5728. }
  5729. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5730. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5731. virtual void stop() { }
  5732. virtual void reset() { }
  5733. virtual void checkAbort() { }
  5734. virtual void resetEOF() { }
  5735. };
  5736. class CIndirectRoxieInput : public CPseudoRoxieInput
  5737. {
  5738. public:
  5739. CIndirectRoxieInput() : input(NULL)
  5740. {
  5741. stream = NULL;
  5742. sourceIdx = 0;
  5743. }
  5744. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5745. {
  5746. input->start(parentExtractSize, parentExtract, paused);
  5747. startJunction(junction);
  5748. }
  5749. virtual void stop()
  5750. {
  5751. stream->stop();
  5752. }
  5753. virtual void reset()
  5754. {
  5755. input->reset();
  5756. resetJunction(junction);
  5757. }
  5758. virtual const void * nextRow()
  5759. {
  5760. return stream->nextRow();
  5761. }
  5762. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5763. {
  5764. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5765. }
  5766. virtual unsigned __int64 queryTotalCycles() const
  5767. {
  5768. return input->queryTotalCycles();
  5769. }
  5770. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5771. {
  5772. return input->gatherConjunctions(collector);
  5773. }
  5774. virtual void resetEOF()
  5775. {
  5776. stream->resetEOF();
  5777. }
  5778. virtual unsigned numConcreteOutputs() const
  5779. {
  5780. return input->numConcreteOutputs();
  5781. }
  5782. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5783. {
  5784. return input->queryConcreteInput(idx);
  5785. }
  5786. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5787. {
  5788. return input->queryConcreteOutputStream(whichInput);
  5789. }
  5790. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5791. {
  5792. return input->queryConcreteOutputJunction(idx);
  5793. }
  5794. virtual IOutputMetaData * queryOutputMeta() const
  5795. {
  5796. return input->queryOutputMeta();
  5797. }
  5798. virtual IRoxieServerActivity *queryActivity()
  5799. {
  5800. return input->queryActivity();
  5801. }
  5802. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5803. {
  5804. input = _input;
  5805. sourceIdx = _sourceIdx;
  5806. }
  5807. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5808. {
  5809. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5810. }
  5811. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5812. {
  5813. assertex(idx == 0);
  5814. connectInputStreams(ctx, consumerOrdered);
  5815. streams.append(this);
  5816. return NULL;
  5817. }
  5818. inline IFinalRoxieInput *queryInput() const
  5819. {
  5820. return input;
  5821. }
  5822. protected:
  5823. unsigned sourceIdx;
  5824. IFinalRoxieInput *input;
  5825. IEngineRowStream *stream;
  5826. Owned<IStrandJunction> junction;
  5827. };
  5828. class CExtractMapperInput : public CIndirectRoxieInput
  5829. {
  5830. unsigned savedParentExtractSize;
  5831. const byte * savedParentExtract;
  5832. public:
  5833. CExtractMapperInput()
  5834. {
  5835. savedParentExtractSize = 0;
  5836. savedParentExtract = NULL;
  5837. }
  5838. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5839. {
  5840. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5841. }
  5842. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5843. {
  5844. savedParentExtractSize = _savedParentExtractSize;
  5845. savedParentExtract = _savedParentExtract;
  5846. }
  5847. };
  5848. class CGraphResult : implements IGraphResult, public CInterface
  5849. {
  5850. CriticalSection cs;
  5851. const byte **rowset;
  5852. size32_t count;
  5853. bool complete;
  5854. void clear()
  5855. {
  5856. CriticalBlock func(cs);
  5857. rtlReleaseRowset(count, rowset);
  5858. rowset = NULL;
  5859. count = 0;
  5860. complete = false;
  5861. }
  5862. public:
  5863. IMPLEMENT_IINTERFACE
  5864. CGraphResult()
  5865. {
  5866. complete = false; // dummy result is not supposed to be used...
  5867. rowset = NULL;
  5868. count = 0;
  5869. }
  5870. CGraphResult(size32_t _count, const byte **_rowset)
  5871. : count(_count), rowset(_rowset)
  5872. {
  5873. complete = true;
  5874. }
  5875. ~CGraphResult()
  5876. {
  5877. clear();
  5878. }
  5879. // interface IGraphResult
  5880. virtual IEngineRowStream * createIterator()
  5881. {
  5882. if (!complete)
  5883. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5884. return new CGraphResultIterator(this);
  5885. }
  5886. virtual void getLinkedResult(unsigned & countResult, const byte * * & result) override
  5887. {
  5888. if (!complete)
  5889. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5890. result = rtlLinkRowset(rowset);
  5891. countResult = count;
  5892. }
  5893. virtual const void * getLinkedRowResult()
  5894. {
  5895. if (!complete)
  5896. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5897. if (count != 1)
  5898. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5899. const void * ret = rowset[0];
  5900. LinkRoxieRow(ret);
  5901. return ret;
  5902. }
  5903. //other
  5904. const void * getRow(unsigned i)
  5905. {
  5906. CriticalBlock func(cs);
  5907. if (i >= count)
  5908. return NULL;
  5909. const void * ret = rowset[i];
  5910. if (ret) LinkRoxieRow(ret);
  5911. return ret;
  5912. }
  5913. protected:
  5914. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5915. {
  5916. unsigned i;
  5917. Linked<CGraphResult> result;
  5918. public:
  5919. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5920. public:
  5921. virtual const void * nextRow()
  5922. {
  5923. return result->getRow(i++);
  5924. }
  5925. virtual void stop()
  5926. {
  5927. }
  5928. virtual void resetEOF()
  5929. {
  5930. throwUnexpected();
  5931. }
  5932. };
  5933. };
  5934. //=================================================================================
  5935. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5936. {
  5937. IHThorLocalResultReadArg &helper;
  5938. CriticalSection iterCrit;
  5939. Owned<IEngineRowStream> iter;
  5940. ILocalGraphEx * graph;
  5941. unsigned graphId;
  5942. unsigned sequence;
  5943. public:
  5944. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5945. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5946. {
  5947. graph = NULL;
  5948. sequence = 0;
  5949. }
  5950. virtual void onCreate(IHThorArg *_colocalParent)
  5951. {
  5952. CRoxieServerActivity::onCreate(_colocalParent);
  5953. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5954. sequence = helper.querySequence();
  5955. }
  5956. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5957. {
  5958. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5959. iter.setown(graph->createResultIterator(sequence));
  5960. }
  5961. virtual void reset()
  5962. {
  5963. {
  5964. CriticalBlock b(iterCrit);
  5965. iter.clear();
  5966. }
  5967. CRoxieServerActivity::reset();
  5968. };
  5969. virtual const void *nextRow()
  5970. {
  5971. ActivityTimer t(totalCycles, timeActivities);
  5972. Linked<IEngineRowStream> useIter;
  5973. {
  5974. CriticalBlock b(iterCrit);
  5975. if (!iter)
  5976. return NULL;
  5977. useIter.set(iter);
  5978. }
  5979. const void * next = useIter->nextRow();
  5980. if (next)
  5981. {
  5982. processed++;
  5983. rowsIn++;
  5984. }
  5985. return next;
  5986. }
  5987. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5988. {
  5989. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5990. }
  5991. };
  5992. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5993. {
  5994. unsigned graphId;
  5995. public:
  5996. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  5997. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  5998. {
  5999. }
  6000. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6001. {
  6002. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  6003. }
  6004. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6005. {
  6006. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6007. }
  6008. };
  6009. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6010. {
  6011. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6012. }
  6013. //=================================================================================
  6014. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  6015. {
  6016. IHThorLocalResultReadArg &helper;
  6017. unsigned sequence;
  6018. public:
  6019. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6020. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  6021. {
  6022. sequence = 0;
  6023. }
  6024. virtual void onCreate(IHThorArg *_colocalParent)
  6025. {
  6026. CRoxieServerActivity::onCreate(_colocalParent);
  6027. sequence = helper.querySequence();
  6028. }
  6029. virtual const void *nextRow()
  6030. {
  6031. ActivityTimer t(totalCycles, timeActivities);
  6032. const void * next = inputStream->nextRow();
  6033. if (next)
  6034. {
  6035. processed++;
  6036. rowsIn++;
  6037. }
  6038. return next;
  6039. }
  6040. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  6041. {
  6042. if (id == sequence)
  6043. {
  6044. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  6045. connectInputStreams(true);
  6046. return true;
  6047. }
  6048. return false;
  6049. }
  6050. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6051. {
  6052. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6053. }
  6054. };
  6055. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  6056. {
  6057. public:
  6058. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6059. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6060. {
  6061. }
  6062. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6063. {
  6064. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  6065. }
  6066. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6067. {
  6068. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6069. }
  6070. };
  6071. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6072. {
  6073. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6074. }
  6075. //=====================================================================================================
  6076. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  6077. {
  6078. IHThorLocalResultWriteArg &helper;
  6079. ILocalGraphEx * graph;
  6080. unsigned graphId;
  6081. public:
  6082. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6083. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  6084. {
  6085. graph = NULL;
  6086. }
  6087. virtual bool needsAllocator() const { return true; }
  6088. virtual void onCreate(IHThorArg *_colocalParent)
  6089. {
  6090. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6091. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6092. }
  6093. virtual void onExecute()
  6094. {
  6095. RtlLinkedDatasetBuilder builder(rowAllocator);
  6096. inputStream->readAll(builder);
  6097. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6098. graph->setResult(helper.querySequence(), result);
  6099. }
  6100. virtual const void *nextRow()
  6101. {
  6102. return inputStream->nextRow(); // I can act as a passthrough input
  6103. }
  6104. IFinalRoxieInput * querySelectOutput(unsigned id)
  6105. {
  6106. if (id == helper.querySequence())
  6107. {
  6108. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6109. return LINK(this);
  6110. }
  6111. return NULL;
  6112. }
  6113. };
  6114. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6115. {
  6116. unsigned graphId;
  6117. public:
  6118. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6119. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6120. {
  6121. isInternal = true;
  6122. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6123. }
  6124. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6125. {
  6126. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6127. }
  6128. };
  6129. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6130. {
  6131. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6132. }
  6133. //=====================================================================================================
  6134. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6135. {
  6136. IHThorDictionaryResultWriteArg &helper;
  6137. ILocalGraphEx * graph;
  6138. unsigned graphId;
  6139. public:
  6140. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6141. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6142. {
  6143. graph = NULL;
  6144. }
  6145. virtual bool needsAllocator() const { return true; }
  6146. virtual void onCreate(IHThorArg *_colocalParent)
  6147. {
  6148. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6149. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6150. }
  6151. virtual void onExecute()
  6152. {
  6153. unsigned sequence = helper.querySequence();
  6154. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6155. for (;;)
  6156. {
  6157. const void *row = inputStream->ungroupedNextRow();
  6158. if (!row)
  6159. break;
  6160. builder.appendOwn(row);
  6161. processed++;
  6162. }
  6163. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6164. graph->setResult(helper.querySequence(), result);
  6165. }
  6166. virtual const void *nextRow()
  6167. {
  6168. return inputStream->nextRow(); // I can act as a passthrough input
  6169. }
  6170. IFinalRoxieInput * querySelectOutput(unsigned id)
  6171. {
  6172. if (id == helper.querySequence())
  6173. {
  6174. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6175. return LINK(this);
  6176. }
  6177. return NULL;
  6178. }
  6179. };
  6180. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6181. {
  6182. unsigned graphId;
  6183. public:
  6184. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6185. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6186. {
  6187. isInternal = true;
  6188. }
  6189. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6190. {
  6191. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6192. }
  6193. };
  6194. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6195. {
  6196. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6197. }
  6198. //=================================================================================
  6199. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6200. {
  6201. protected:
  6202. IHThorGraphLoopResultReadArg &helper;
  6203. CriticalSection iterCrit;
  6204. Owned<IFinalRoxieInput> iterInput;
  6205. Owned<IEngineRowStream> iterStream;
  6206. Owned<IStrandJunction> iterJunction;
  6207. ILocalGraphEx * graph;
  6208. unsigned graphId;
  6209. unsigned sequence;
  6210. public:
  6211. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6212. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6213. {
  6214. graph = NULL;
  6215. sequence = 0;
  6216. }
  6217. virtual void onCreate(IHThorArg *_colocalParent)
  6218. {
  6219. CRoxieServerActivity::onCreate(_colocalParent);
  6220. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6221. }
  6222. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6223. {
  6224. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6225. if (iterInput)
  6226. iterInput->start(parentExtractSize, parentExtract, paused);
  6227. else
  6228. {
  6229. sequence = helper.querySequence();
  6230. if ((int)sequence >= 0)
  6231. {
  6232. try
  6233. {
  6234. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6235. iterInput.clear();
  6236. }
  6237. catch (IException * E)
  6238. {
  6239. throw makeWrappedException(E);
  6240. }
  6241. }
  6242. }
  6243. startJunction(iterJunction);
  6244. }
  6245. virtual void stop()
  6246. {
  6247. if (iterStream)
  6248. iterStream->stop();
  6249. CRoxieServerActivity::stop();
  6250. }
  6251. virtual void reset()
  6252. {
  6253. {
  6254. CriticalBlock b(iterCrit);
  6255. if (iterInput)
  6256. iterInput->reset();
  6257. resetJunction(iterJunction);
  6258. iterInput.clear();
  6259. iterStream.clear();
  6260. iterJunction.clear();
  6261. }
  6262. CRoxieServerActivity::reset();
  6263. };
  6264. virtual const void *nextRow()
  6265. {
  6266. ActivityTimer t(totalCycles, timeActivities);
  6267. Linked<IEngineRowStream> useStream;
  6268. {
  6269. CriticalBlock b(iterCrit);
  6270. if (!iterStream)
  6271. return NULL;
  6272. useStream.set(iterStream);
  6273. }
  6274. const void * next = useStream->nextRow();
  6275. if (next)
  6276. {
  6277. processed++;
  6278. rowsIn++;
  6279. }
  6280. return next;
  6281. }
  6282. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6283. {
  6284. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6285. }
  6286. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6287. {
  6288. ensureCreated();
  6289. basehelper.onStart(parentExtract, NULL);
  6290. processor.noteUseIteration(helper.querySequence());
  6291. }
  6292. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6293. {
  6294. //helper already initialised from the gatherIterationUsage() call.
  6295. CRoxieServerActivity::connectInputStreams(true);
  6296. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6297. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6298. }
  6299. virtual IInputSteppingMeta * querySteppingMeta()
  6300. {
  6301. assertex(iterInput);
  6302. return iterInput->querySteppingMeta();
  6303. }
  6304. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6305. {
  6306. assertex(iterStream);
  6307. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6308. }
  6309. };
  6310. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6311. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6312. {
  6313. public:
  6314. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6315. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6316. {
  6317. sequence = _sequence;
  6318. }
  6319. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6320. {
  6321. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6322. if ((int)sequence >= 0)
  6323. {
  6324. try
  6325. {
  6326. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6327. iterInput.clear();
  6328. }
  6329. catch (IException * E)
  6330. {
  6331. throw makeWrappedException(E);
  6332. }
  6333. }
  6334. }
  6335. };
  6336. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6337. {
  6338. unsigned graphId;
  6339. public:
  6340. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6341. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6342. {
  6343. }
  6344. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6345. {
  6346. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6347. }
  6348. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6349. {
  6350. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6351. }
  6352. };
  6353. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6354. {
  6355. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6356. }
  6357. //=====================================================================================================
  6358. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6359. {
  6360. IHThorGraphLoopResultWriteArg &helper;
  6361. ILocalGraphEx * graph;
  6362. unsigned graphId;
  6363. public:
  6364. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6365. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  6366. {
  6367. graph = NULL;
  6368. }
  6369. virtual bool needsAllocator() const { return true; }
  6370. virtual void onCreate(IHThorArg *_colocalParent)
  6371. {
  6372. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6373. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6374. }
  6375. virtual void onExecute()
  6376. {
  6377. RtlLinkedDatasetBuilder builder(rowAllocator);
  6378. inputStream->readAll(builder);
  6379. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6380. graph->setGraphLoopResult(result);
  6381. }
  6382. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6383. {
  6384. if (idx==0)
  6385. return this;
  6386. else
  6387. return NULL;
  6388. }
  6389. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6390. {
  6391. return input->gatherConjunctions(collector);
  6392. }
  6393. virtual void resetEOF()
  6394. {
  6395. inputStream->resetEOF();
  6396. }
  6397. virtual const void *nextRow()
  6398. {
  6399. const void * next = inputStream->nextRow();
  6400. if (next)
  6401. processed++;
  6402. return next;
  6403. }
  6404. virtual bool isPassThrough()
  6405. {
  6406. return true;
  6407. }
  6408. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6409. {
  6410. ActivityTimer t(totalCycles, timeActivities);
  6411. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6412. if (next)
  6413. processed++;
  6414. return next;
  6415. }
  6416. IInputSteppingMeta * querySteppingMeta()
  6417. {
  6418. return input->querySteppingMeta();
  6419. }
  6420. virtual IOutputMetaData * queryOutputMeta() const
  6421. {
  6422. return input->queryOutputMeta();
  6423. }
  6424. };
  6425. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6426. {
  6427. unsigned graphId;
  6428. public:
  6429. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6430. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6431. {
  6432. isInternal = true;
  6433. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6434. }
  6435. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6436. {
  6437. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6438. }
  6439. };
  6440. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6441. {
  6442. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6443. }
  6444. //=================================================================================
  6445. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6446. {
  6447. protected:
  6448. IHThorDedupArg &helper;
  6449. unsigned numKept;
  6450. unsigned numToKeep;
  6451. public:
  6452. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6453. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6454. {
  6455. numKept = 0;
  6456. numToKeep = 0;
  6457. }
  6458. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6459. {
  6460. numKept = 0;
  6461. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6462. numToKeep = helper.numToKeep();
  6463. }
  6464. };
  6465. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6466. {
  6467. IRangeCompare * stepCompare;
  6468. const void *prev;
  6469. public:
  6470. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6471. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6472. {
  6473. prev = NULL;
  6474. stepCompare = NULL;
  6475. }
  6476. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6477. {
  6478. prev = NULL;
  6479. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6480. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6481. stepCompare = NULL;
  6482. if (stepMeta)
  6483. stepCompare = stepMeta->queryCompare();
  6484. }
  6485. virtual void reset()
  6486. {
  6487. ReleaseClearRoxieRow(prev);
  6488. CRoxieServerDedupActivity::reset();
  6489. }
  6490. virtual const void * nextRow()
  6491. {
  6492. ActivityTimer t(totalCycles, timeActivities);
  6493. const void * next;
  6494. for (;;)
  6495. {
  6496. next = inputStream->nextRow();
  6497. if (!prev || !next || !helper.matches(prev,next))
  6498. {
  6499. numKept = 0;
  6500. break;
  6501. }
  6502. if (numKept < numToKeep-1)
  6503. {
  6504. numKept++;
  6505. break;
  6506. }
  6507. ReleaseRoxieRow(next);
  6508. }
  6509. ReleaseRoxieRow(prev);
  6510. prev = next;
  6511. if (next)
  6512. {
  6513. LinkRoxieRow(next);
  6514. processed++;
  6515. }
  6516. return next;
  6517. }
  6518. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6519. {
  6520. ActivityTimer t(totalCycles, timeActivities);
  6521. const void * next;
  6522. for (;;)
  6523. {
  6524. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6525. //If the record was an in-exact match from the index then return it immediately
  6526. //and don't cause it to dedup following legal records.
  6527. if (!wasCompleteMatch)
  6528. {
  6529. assertex(stepExtra.returnMismatches());
  6530. return next;
  6531. }
  6532. if (!prev || !next || !helper.matches(prev,next))
  6533. {
  6534. numKept = 0;
  6535. break;
  6536. }
  6537. if (numKept < numToKeep-1)
  6538. {
  6539. numKept++;
  6540. break;
  6541. }
  6542. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6543. if (stepExtra.returnMismatches())
  6544. {
  6545. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6546. //condition to advance
  6547. if (stepCompare->docompare(next, seek, numFields) != 0)
  6548. {
  6549. wasCompleteMatch = false;
  6550. break;
  6551. }
  6552. }
  6553. ReleaseRoxieRow(next);
  6554. }
  6555. ReleaseRoxieRow(prev);
  6556. prev = next;
  6557. if (next)
  6558. {
  6559. LinkRoxieRow(next);
  6560. processed++;
  6561. }
  6562. return next;
  6563. }
  6564. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6565. {
  6566. return input->gatherConjunctions(collector);
  6567. }
  6568. virtual void resetEOF()
  6569. {
  6570. inputStream->resetEOF();
  6571. }
  6572. IInputSteppingMeta * querySteppingMeta()
  6573. {
  6574. return input->querySteppingMeta();
  6575. }
  6576. };
  6577. //=================================================================================
  6578. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6579. {
  6580. const void *kept;
  6581. bool first;
  6582. ICompare * compareBest;
  6583. public:
  6584. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6585. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager), compareBest(nullptr)
  6586. {
  6587. kept = nullptr;
  6588. first = true;
  6589. if (helper.keepBest())
  6590. compareBest = helper.queryCompareBest();
  6591. }
  6592. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6593. {
  6594. first = true;
  6595. kept = nullptr;
  6596. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6597. if (numToKeep>1)
  6598. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6599. }
  6600. virtual void reset()
  6601. {
  6602. ReleaseClearRoxieRow(kept);
  6603. CRoxieServerActivity::reset();
  6604. }
  6605. virtual const void * nextRow()
  6606. {
  6607. ActivityTimer t(totalCycles, timeActivities);
  6608. if (first)
  6609. {
  6610. kept = inputStream->nextRow();
  6611. first = false;
  6612. }
  6613. const void * next;
  6614. for (;;)
  6615. {
  6616. next = inputStream->nextRow();
  6617. if (!kept || !next || !helper.matches(kept,next))
  6618. break;
  6619. if (compareBest && compareBest->docompare(kept,next) <= 0)
  6620. continue;
  6621. ReleaseRoxieRow(kept);
  6622. kept = next;
  6623. }
  6624. const void * ret = kept;
  6625. kept = next;
  6626. // CTXLOG("dedup returns %p", ret);
  6627. if (ret) processed++;
  6628. return ret;
  6629. }
  6630. };
  6631. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6632. {
  6633. IHThorDedupArg &helper;
  6634. unsigned survivorIndex;
  6635. ConstPointerArray survivors;
  6636. bool keepLeft;
  6637. bool eof;
  6638. bool first;
  6639. ICompare *primaryCompare;
  6640. public:
  6641. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6642. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6643. {
  6644. keepLeft = _keepLeft;
  6645. primaryCompare = helper.queryComparePrimary();
  6646. eof = false;
  6647. first = true;
  6648. survivorIndex = 0;
  6649. }
  6650. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6651. {
  6652. eof = false;
  6653. first = true;
  6654. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6655. }
  6656. virtual void reset()
  6657. {
  6658. while (survivors.isItem(survivorIndex))
  6659. {
  6660. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6661. }
  6662. survivors.kill();
  6663. eof = false;
  6664. first = true;
  6665. CRoxieServerActivity::reset();
  6666. }
  6667. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6668. {
  6669. for (unsigned idxL = first; idxL < last; idxL++)
  6670. {
  6671. const void * left = group.item(idxL);
  6672. if (left)
  6673. {
  6674. for (unsigned idxR = first; idxR < last; idxR++)
  6675. {
  6676. const void * right = group.item(idxR);
  6677. if ((idxL != idxR) && right)
  6678. {
  6679. if (helper.matches(left, right))
  6680. {
  6681. if (keepLeft)
  6682. {
  6683. group.replace(NULL, idxR);
  6684. ReleaseRoxieRow(right);
  6685. }
  6686. else
  6687. {
  6688. group.replace(NULL, idxL);
  6689. ReleaseRoxieRow(left);
  6690. break;
  6691. }
  6692. }
  6693. }
  6694. }
  6695. }
  6696. }
  6697. }
  6698. void dedupRange(unsigned first, unsigned last, void ** rows)
  6699. {
  6700. for (unsigned idxL = first; idxL < last; idxL++)
  6701. {
  6702. void * left = rows[idxL];
  6703. if (left)
  6704. {
  6705. for (unsigned idxR = first; idxR < last; idxR++)
  6706. {
  6707. void * right = rows[idxR];
  6708. if ((idxL != idxR) && right)
  6709. {
  6710. if (helper.matches(left, right))
  6711. {
  6712. if (keepLeft)
  6713. {
  6714. rows[idxR] = NULL;
  6715. ReleaseRoxieRow(right);
  6716. }
  6717. else
  6718. {
  6719. rows[idxL] = NULL;
  6720. ReleaseRoxieRow(left);
  6721. break;
  6722. }
  6723. }
  6724. }
  6725. }
  6726. }
  6727. }
  6728. }
  6729. bool calcNextDedupAll()
  6730. {
  6731. survivors.kill();
  6732. survivorIndex = 0;
  6733. ConstPointerArray group;
  6734. if (eof || !inputStream->nextGroup(group))
  6735. {
  6736. eof = true;
  6737. return false;
  6738. }
  6739. unsigned max = group.ordinality();
  6740. if (primaryCompare)
  6741. {
  6742. //hard, if not impossible, to hit this code once optimisations in place
  6743. MemoryAttr indexbuff(max*sizeof(void *));
  6744. void ** temp = (void **)indexbuff.bufferBase();
  6745. void * *rows = const_cast<void * *>(group.getArray());
  6746. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6747. unsigned first = 0;
  6748. for (unsigned idx = 1; idx < max; idx++)
  6749. {
  6750. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6751. {
  6752. dedupRange(first, idx, rows);
  6753. first = idx;
  6754. }
  6755. }
  6756. dedupRange(first, max, rows);
  6757. for(unsigned idx2=0; idx2<max; ++idx2)
  6758. {
  6759. void * cur = rows[idx2];
  6760. if(cur)
  6761. survivors.append(cur);
  6762. }
  6763. }
  6764. else
  6765. {
  6766. dedupRange(0, max, group);
  6767. for(unsigned idx=0; idx<max; ++idx)
  6768. {
  6769. const void * cur = group.item(idx);
  6770. if(cur)
  6771. survivors.append(cur);
  6772. }
  6773. }
  6774. return true;
  6775. }
  6776. virtual const void *nextRow()
  6777. {
  6778. ActivityTimer t(totalCycles, timeActivities);
  6779. if (first)
  6780. {
  6781. calcNextDedupAll();
  6782. first = false;
  6783. }
  6784. while (survivors.isItem(survivorIndex))
  6785. {
  6786. const void *ret = survivors.item(survivorIndex++);
  6787. if (ret)
  6788. {
  6789. processed++;
  6790. return ret;
  6791. }
  6792. }
  6793. calcNextDedupAll();
  6794. return NULL;
  6795. }
  6796. };
  6797. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6798. {
  6799. bool compareAll;
  6800. bool keepLeft;
  6801. bool keepBest;
  6802. public:
  6803. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6804. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6805. {
  6806. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6807. compareAll = helper->compareAll();
  6808. keepLeft = helper->keepLeft();
  6809. keepBest = helper->keepBest();
  6810. }
  6811. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6812. {
  6813. if (compareAll)
  6814. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6815. else if (keepLeft && !keepBest)
  6816. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6817. else
  6818. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6819. }
  6820. };
  6821. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6822. {
  6823. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6824. }
  6825. //=================================================================================
  6826. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6827. {
  6828. bool eof;
  6829. IHThorHashDedupArg &helper;
  6830. class HashDedupElement
  6831. {
  6832. public:
  6833. HashDedupElement(unsigned _hash, const void *_keyRow)
  6834. : hash(_hash), keyRow(_keyRow)
  6835. {
  6836. }
  6837. ~HashDedupElement()
  6838. {
  6839. ReleaseRoxieRow(keyRow);
  6840. }
  6841. inline unsigned queryHash() const
  6842. {
  6843. return hash;
  6844. }
  6845. inline const void *queryRow() const
  6846. {
  6847. return keyRow;
  6848. }
  6849. inline const void *getRowClear()
  6850. {
  6851. const void * row = keyRow;
  6852. keyRow = nullptr;
  6853. return row;
  6854. }
  6855. private:
  6856. unsigned hash;
  6857. const void *keyRow;
  6858. };
  6859. static CClassMeta<HashDedupElement> hashDedupElementMeta;
  6860. class HashDedupTable : public SuperHashTable
  6861. {
  6862. public:
  6863. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6864. : helper(_helper),
  6865. activity(_activity),
  6866. keySize(helper.queryKeySize())
  6867. {
  6868. bestCompare=helper.queryCompareBest();
  6869. }
  6870. virtual ~HashDedupTable()
  6871. {
  6872. //elementRowAllocator is a unique allocator, so all rows can be freed in a single call
  6873. elementRowAllocator->releaseAllRows();
  6874. tablecount = 0;
  6875. }
  6876. virtual unsigned getHashFromElement(const void *et) const
  6877. {
  6878. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6879. return element->queryHash();
  6880. }
  6881. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6882. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6883. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6884. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6885. {
  6886. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6887. if (fphash != element->queryHash())
  6888. return false;
  6889. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6890. }
  6891. virtual void onAdd(void *et) {}
  6892. virtual void onRemove(void *et)
  6893. {
  6894. ReleaseRoxieRow(et);
  6895. }
  6896. void onCreate(IRoxieSlaveContext *ctx)
  6897. {
  6898. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6899. elementRowAllocator.setown(activity.createRowAllocatorEx(&hashDedupElementMeta, roxiemem::RHFunique|roxiemem::RHFscanning|roxiemem::RHFdelayrelease));
  6900. }
  6901. void reset()
  6902. {
  6903. kill();
  6904. }
  6905. bool insert(const void * row)
  6906. {
  6907. unsigned hash = helper.queryHash()->hash(row);
  6908. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6909. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6910. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6911. if (find(hash, keyRow.get()))
  6912. return false;
  6913. addNew(createElement(hash, keyRow.getClear()), hash);
  6914. return true;
  6915. }
  6916. bool insertBest(const void * nextrow)
  6917. {
  6918. unsigned hash = helper.queryHash()->hash(nextrow);
  6919. const void *et = find(hash, nextrow);
  6920. if (et)
  6921. {
  6922. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6923. const void * row = element->queryRow();
  6924. if (bestCompare->docompare(row,nextrow) <= 0)
  6925. return false;
  6926. removeExact( const_cast<void *>(et));
  6927. // drop-through to add new row
  6928. }
  6929. addNew(createElement(hash, nextrow), hash);
  6930. return true;
  6931. }
  6932. void gatherStats(CRuntimeStatisticCollection & merged) const
  6933. {
  6934. if (keyRowAllocator)
  6935. keyRowAllocator->gatherStats(merged);
  6936. }
  6937. private:
  6938. inline void *createElement(unsigned hash, const void *row)
  6939. {
  6940. return elementRowAllocator->finalizeRow(sizeof(HashDedupElement), new (elementRowAllocator->createRow()) HashDedupElement(hash, row), sizeof(HashDedupElement));
  6941. }
  6942. IHThorHashDedupArg & helper;
  6943. CachedOutputMetaData keySize;
  6944. Owned<IEngineRowAllocator> keyRowAllocator;
  6945. Owned<IEngineRowAllocator> elementRowAllocator;
  6946. CRoxieServerHashDedupActivity & activity;
  6947. ICompare * bestCompare;
  6948. } table;
  6949. public:
  6950. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6951. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this), hashTableFilled(false), hashDedupTableIter(table)
  6952. {
  6953. eof = false;
  6954. keepBest = helper.keepBest();
  6955. }
  6956. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6957. {
  6958. eof = false;
  6959. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6960. }
  6961. virtual void onCreate(IHThorArg *_colocalParent)
  6962. {
  6963. CRoxieServerActivity::onCreate(colocalParent);
  6964. table.onCreate(ctx);
  6965. }
  6966. virtual void reset()
  6967. {
  6968. table.reset();
  6969. eof = false;
  6970. CRoxieServerActivity::reset();
  6971. hashTableFilled = false;
  6972. }
  6973. virtual const void *nextRow()
  6974. {
  6975. ActivityTimer t(totalCycles, timeActivities);
  6976. if (keepBest)
  6977. {
  6978. if (eof)
  6979. return NULL;
  6980. // Populate hash table with best rows
  6981. if (!hashTableFilled)
  6982. {
  6983. const void * next = inputStream->nextRow();
  6984. while(next)
  6985. {
  6986. if (!table.insertBest(next))
  6987. ReleaseRoxieRow(next);
  6988. next = inputStream->nextRow();
  6989. }
  6990. if (table.count() == 0)
  6991. eof = true;
  6992. hashTableFilled = true;
  6993. hashDedupTableIter.first();
  6994. }
  6995. // Iterate throw hash table returning rows
  6996. if (hashDedupTableIter.isValid())
  6997. {
  6998. HashDedupElement &el = hashDedupTableIter.query();
  6999. const void * row = el.getRowClear();
  7000. hashDedupTableIter.next();
  7001. return row;
  7002. }
  7003. table.reset();
  7004. hashTableFilled = false;
  7005. return NULL;
  7006. }
  7007. else
  7008. {
  7009. while(!eof)
  7010. {
  7011. const void * next = inputStream->nextRow();
  7012. if(!next)
  7013. {
  7014. if (table.count() == 0)
  7015. eof = true;
  7016. table.reset();
  7017. return NULL;
  7018. }
  7019. if(table.insert(next))
  7020. return next;
  7021. else
  7022. ReleaseRoxieRow(next);
  7023. }
  7024. return NULL;
  7025. }
  7026. }
  7027. private:
  7028. bool keepBest;
  7029. bool hashTableFilled;
  7030. SuperHashIteratorOf<HashDedupElement> hashDedupTableIter;
  7031. };
  7032. CClassMeta<CRoxieServerHashDedupActivity::HashDedupElement> CRoxieServerHashDedupActivity::hashDedupElementMeta;
  7033. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  7034. {
  7035. public:
  7036. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7037. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7038. {
  7039. }
  7040. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7041. {
  7042. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  7043. }
  7044. };
  7045. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7046. {
  7047. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7048. }
  7049. //=================================================================================
  7050. class CRoxieServerRollupActivity : public CRoxieServerActivity
  7051. {
  7052. IHThorRollupArg &helper;
  7053. OwnedConstRoxieRow left;
  7054. OwnedConstRoxieRow prev;
  7055. OwnedConstRoxieRow right;
  7056. bool readFirstRow;
  7057. public:
  7058. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7059. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  7060. {
  7061. readFirstRow = false;
  7062. }
  7063. ~CRoxieServerRollupActivity()
  7064. {
  7065. }
  7066. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7067. {
  7068. readFirstRow = false;
  7069. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7070. }
  7071. virtual void reset()
  7072. {
  7073. left.clear();
  7074. prev.clear();
  7075. right.clear();
  7076. CRoxieServerActivity::reset();
  7077. }
  7078. virtual bool needsAllocator() const { return true; }
  7079. virtual const void * nextRow()
  7080. {
  7081. ActivityTimer t(totalCycles, timeActivities);
  7082. if (!readFirstRow)
  7083. {
  7084. left.setown(inputStream->nextRow());
  7085. prev.set(left);
  7086. readFirstRow = true;
  7087. }
  7088. for (;;)
  7089. {
  7090. right.setown(inputStream->nextRow());
  7091. if(!prev || !right || !helper.matches(prev,right))
  7092. {
  7093. const void * ret = left.getClear();
  7094. if(ret)
  7095. processed++;
  7096. left.setown(right.getClear());
  7097. prev.set(left);
  7098. return ret;
  7099. }
  7100. try
  7101. {
  7102. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7103. unsigned outSize = helper.transform(rowBuilder, left, right);
  7104. if (outSize)
  7105. left.setown(rowBuilder.finalizeRowClear(outSize));
  7106. if (helper.getFlags() & RFrolledismatchleft)
  7107. prev.set(left);
  7108. else
  7109. prev.set(right);
  7110. }
  7111. catch(IException * E)
  7112. {
  7113. throw makeWrappedException(E);
  7114. }
  7115. }
  7116. }
  7117. };
  7118. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  7119. {
  7120. public:
  7121. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7122. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7123. {
  7124. }
  7125. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7126. {
  7127. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  7128. }
  7129. };
  7130. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7131. {
  7132. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7133. }
  7134. //=================================================================================
  7135. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  7136. {
  7137. IHThorNormalizeArg &helper;
  7138. unsigned numThisRow;
  7139. unsigned curRow;
  7140. const void *buffer;
  7141. unsigned numProcessedLastGroup;
  7142. public:
  7143. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7144. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  7145. {
  7146. buffer = NULL;
  7147. numThisRow = 0;
  7148. curRow = 0;
  7149. numProcessedLastGroup = 0;
  7150. }
  7151. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7152. {
  7153. numThisRow = 0;
  7154. curRow = 0;
  7155. numProcessedLastGroup = 0;
  7156. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7157. }
  7158. virtual void reset()
  7159. {
  7160. ReleaseClearRoxieRow(buffer);
  7161. CRoxieServerActivity::reset();
  7162. }
  7163. virtual bool needsAllocator() const { return true; }
  7164. virtual const void * nextRow()
  7165. {
  7166. ActivityTimer t(totalCycles, timeActivities);
  7167. for (;;)
  7168. {
  7169. while (curRow == numThisRow)
  7170. {
  7171. if (buffer)
  7172. ReleaseClearRoxieRow(buffer);
  7173. buffer = inputStream->nextRow();
  7174. if (!buffer && (processed == numProcessedLastGroup))
  7175. buffer = inputStream->nextRow();
  7176. if (!buffer)
  7177. {
  7178. numProcessedLastGroup = processed;
  7179. return NULL;
  7180. }
  7181. curRow = 0;
  7182. numThisRow = helper.numExpandedRows(buffer);
  7183. }
  7184. try
  7185. {
  7186. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7187. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7188. if (actualSize != 0)
  7189. {
  7190. processed++;
  7191. return rowBuilder.finalizeRowClear(actualSize);
  7192. }
  7193. }
  7194. catch (IException *E)
  7195. {
  7196. throw makeWrappedException(E);
  7197. }
  7198. }
  7199. }
  7200. };
  7201. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7202. {
  7203. public:
  7204. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7205. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7206. {
  7207. }
  7208. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7209. {
  7210. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7211. }
  7212. };
  7213. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7214. {
  7215. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7216. }
  7217. //=================================================================================
  7218. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7219. {
  7220. IHThorNormalizeChildArg &helper;
  7221. unsigned numThisRow;
  7222. unsigned curRow;
  7223. const void *buffer;
  7224. unsigned numProcessedLastGroup;
  7225. INormalizeChildIterator * cursor;
  7226. const void * curChildRow;
  7227. bool advanceInput()
  7228. {
  7229. for (;;)
  7230. {
  7231. ReleaseClearRoxieRow(buffer);
  7232. buffer = inputStream->nextRow();
  7233. if (!buffer && (processed == numProcessedLastGroup))
  7234. buffer = inputStream->nextRow();
  7235. if (!buffer)
  7236. {
  7237. numProcessedLastGroup = processed;
  7238. return false;
  7239. }
  7240. curChildRow = cursor->first(buffer);
  7241. if (curChildRow)
  7242. {
  7243. curRow = 0;
  7244. return true;
  7245. }
  7246. }
  7247. }
  7248. public:
  7249. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7250. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7251. {
  7252. buffer = NULL;
  7253. cursor = NULL;
  7254. numThisRow = 0;
  7255. curRow = 0;
  7256. numProcessedLastGroup = 0;
  7257. curChildRow = NULL;
  7258. }
  7259. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7260. {
  7261. numThisRow = 0;
  7262. curRow = 0;
  7263. numProcessedLastGroup = 0;
  7264. curChildRow = NULL;
  7265. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7266. cursor = helper.queryIterator();
  7267. }
  7268. virtual void stop()
  7269. {
  7270. CRoxieServerActivity::stop();
  7271. }
  7272. virtual void reset()
  7273. {
  7274. cursor = NULL;
  7275. ReleaseClearRoxieRow(buffer);
  7276. CRoxieServerActivity::reset();
  7277. }
  7278. virtual bool needsAllocator() const { return true; }
  7279. const void *nextRow()
  7280. {
  7281. ActivityTimer t(totalCycles, timeActivities);
  7282. for (;;)
  7283. {
  7284. if (!buffer)
  7285. {
  7286. if (!advanceInput())
  7287. return NULL;
  7288. }
  7289. try
  7290. {
  7291. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7292. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7293. curChildRow = cursor->next();
  7294. if (!curChildRow)
  7295. ReleaseClearRoxieRow(buffer);
  7296. if (outSize != 0)
  7297. {
  7298. processed++;
  7299. return rowBuilder.finalizeRowClear(outSize);
  7300. }
  7301. }
  7302. catch (IException *E)
  7303. {
  7304. throw makeWrappedException(E);
  7305. }
  7306. }
  7307. }
  7308. };
  7309. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7310. {
  7311. public:
  7312. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7313. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7314. {
  7315. }
  7316. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7317. {
  7318. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7319. }
  7320. };
  7321. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7322. {
  7323. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7324. }
  7325. //=================================================================================
  7326. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7327. {
  7328. IHThorNormalizeLinkedChildArg &helper;
  7329. OwnedConstRoxieRow curParent;
  7330. OwnedConstRoxieRow curChild;
  7331. unsigned numProcessedLastGroup;
  7332. bool advanceInput()
  7333. {
  7334. for (;;)
  7335. {
  7336. curParent.setown(inputStream->nextRow());
  7337. if (!curParent && (processed == numProcessedLastGroup))
  7338. curParent.setown(inputStream->nextRow());
  7339. if (!curParent)
  7340. {
  7341. numProcessedLastGroup = processed;
  7342. return false;
  7343. }
  7344. curChild.set(helper.first(curParent));
  7345. if (curChild)
  7346. return true;
  7347. }
  7348. }
  7349. public:
  7350. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7351. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7352. {
  7353. numProcessedLastGroup = 0;
  7354. }
  7355. ~CRoxieServerNormalizeLinkedChildActivity()
  7356. {
  7357. }
  7358. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7359. {
  7360. numProcessedLastGroup = 0;
  7361. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7362. }
  7363. virtual void reset()
  7364. {
  7365. curParent.clear();
  7366. curChild.clear();
  7367. CRoxieServerActivity::reset();
  7368. }
  7369. const void *nextRow()
  7370. {
  7371. ActivityTimer t(totalCycles, timeActivities);
  7372. for (;;)
  7373. {
  7374. if (!curParent)
  7375. {
  7376. if (!advanceInput())
  7377. return NULL;
  7378. }
  7379. try
  7380. {
  7381. const void *ret = curChild.getClear();
  7382. curChild.set(helper.next());
  7383. if (!curChild)
  7384. curParent.clear();
  7385. if (ret)
  7386. {
  7387. processed++;
  7388. return ret;
  7389. }
  7390. }
  7391. catch (IException *E)
  7392. {
  7393. throw makeWrappedException(E);
  7394. }
  7395. }
  7396. }
  7397. };
  7398. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7399. {
  7400. public:
  7401. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7402. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7403. {
  7404. }
  7405. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7406. {
  7407. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7408. }
  7409. };
  7410. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7411. {
  7412. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7413. }
  7414. //=================================================================================
  7415. class CRoxieServerSortActivity : public CRoxieServerActivity
  7416. {
  7417. protected:
  7418. IHThorSortArg &helper;
  7419. ICompare *compare;
  7420. Owned<ISortAlgorithm> sorter;
  7421. bool readInput;
  7422. RoxieSortAlgorithm sortAlgorithm;
  7423. unsigned sortFlags;
  7424. public:
  7425. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7426. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7427. {
  7428. compare = helper.queryCompare();
  7429. readInput = false;
  7430. }
  7431. virtual void onCreate(IHThorArg *_colocalParent)
  7432. {
  7433. CRoxieServerActivity::onCreate(_colocalParent);
  7434. if (sortAlgorithm==unknownSortAlgorithm)
  7435. sorter.clear();
  7436. else
  7437. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7438. }
  7439. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7440. {
  7441. assertex(!readInput);
  7442. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7443. }
  7444. virtual void reset()
  7445. {
  7446. if (sorter)
  7447. sorter->reset();
  7448. readInput = false;
  7449. CRoxieServerActivity::reset();
  7450. }
  7451. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7452. {
  7453. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7454. if (!algorithmName)
  7455. algorithmName = "";
  7456. if (stricmp(algorithmName, "quicksort")==0)
  7457. {
  7458. switch (sortFlags & (TAFstable|TAFspill))
  7459. {
  7460. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7461. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7462. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7463. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7464. }
  7465. }
  7466. else if (stricmp(algorithmName, "parquicksort")==0)
  7467. {
  7468. switch (sortFlags & TAFstable)
  7469. {
  7470. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7471. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7472. default: throwUnexpected();
  7473. }
  7474. }
  7475. else if (stricmp(algorithmName, "heapsort")==0)
  7476. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7477. else if (stricmp(algorithmName, "mergesort")==0)
  7478. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7479. else if (stricmp(algorithmName, "parmergesort")==0)
  7480. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7481. else if (stricmp(algorithmName, "tbbqsort")==0)
  7482. sortAlgorithm = tbbQuickSortAlgorithm;
  7483. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7484. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7485. else
  7486. {
  7487. if (*algorithmName)
  7488. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7489. if (sortFlags & TAFspill)
  7490. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7491. else if (sortFlags & TAFunstable)
  7492. sortAlgorithm = quickSortAlgorithm;
  7493. else
  7494. sortAlgorithm = heapSortAlgorithm;
  7495. }
  7496. return sortAlgorithm;
  7497. }
  7498. virtual const void * nextRow()
  7499. {
  7500. ActivityTimer t(totalCycles, timeActivities);
  7501. if (!readInput)
  7502. {
  7503. if (sortAlgorithm == unknownSortAlgorithm)
  7504. {
  7505. sorter.clear();
  7506. OwnedRoxieString algorithmName(helper.getAlgorithm());
  7507. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7508. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7509. }
  7510. sorter->prepare(inputStream);
  7511. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7512. readInput = true;
  7513. }
  7514. const void *ret = sorter->next();
  7515. if (ret)
  7516. processed++;
  7517. else
  7518. {
  7519. sorter->reset();
  7520. readInput = false; // ready for next group
  7521. }
  7522. return ret;
  7523. }
  7524. };
  7525. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7526. {
  7527. RoxieSortAlgorithm sortAlgorithm;
  7528. unsigned sortFlags;
  7529. public:
  7530. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7531. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7532. {
  7533. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7534. const char *algorithmName = NULL;
  7535. sortFlags = sortHelper->getAlgorithmFlags();
  7536. if (sortFlags & TAFconstant)
  7537. algorithmName = sortHelper->getAlgorithm();
  7538. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7539. if (forceSpill)
  7540. sortFlags |= TAFspill;
  7541. if (!(sortFlags & TAFunstable))
  7542. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7543. if (sortFlags & TAFconstant)
  7544. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7545. else
  7546. sortAlgorithm = unknownSortAlgorithm;
  7547. }
  7548. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7549. {
  7550. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7551. }
  7552. virtual const StatisticsMapping &queryStatsMapping() const
  7553. {
  7554. return sortStatistics;
  7555. }
  7556. };
  7557. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7558. {
  7559. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7560. }
  7561. //=====================================================================================================
  7562. static int compareUint64(const void * _left, const void * _right)
  7563. {
  7564. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7565. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7566. if (left < right)
  7567. return -1;
  7568. if (left > right)
  7569. return -1;
  7570. return 0;
  7571. }
  7572. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7573. {
  7574. protected:
  7575. Owned<ISortAlgorithm> sorter;
  7576. IHThorQuantileArg &helper;
  7577. ConstPointerArray sorted;
  7578. ICompare *compare;
  7579. unsigned flags;
  7580. double skew;
  7581. unsigned __int64 numDivisions;
  7582. bool rangeIsAll;
  7583. size32_t rangeSize;
  7584. rtlDataAttr rangeValues;
  7585. bool calculated;
  7586. bool processedAny;
  7587. bool anyThisGroup;
  7588. bool eof;
  7589. unsigned curQuantile;
  7590. unsigned curIndex;
  7591. unsigned curIndexExtra;
  7592. unsigned skipSize;
  7593. unsigned skipExtra;
  7594. unsigned prevIndex;
  7595. public:
  7596. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7597. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7598. {
  7599. compare = helper.queryCompare();
  7600. skew = 0.0;
  7601. numDivisions = 0;
  7602. calculated = false;
  7603. processedAny = false;
  7604. anyThisGroup = false;
  7605. eof = false;
  7606. rangeIsAll = true;
  7607. rangeSize = 0;
  7608. curQuantile = 0;
  7609. prevIndex = 0;
  7610. curIndex = 0;
  7611. curIndexExtra = 0;
  7612. skipSize = 0;
  7613. skipExtra = 0;
  7614. if (flags & TQFunstable)
  7615. sorter.setown(createQuickSortAlgorithm(compare));
  7616. else
  7617. sorter.setown(createMergeSortAlgorithm(compare));
  7618. }
  7619. virtual void reset()
  7620. {
  7621. sorter->reset();
  7622. calculated = false;
  7623. processedAny = false;
  7624. anyThisGroup = false;
  7625. ReleaseRoxieRows(sorted);
  7626. CRoxieServerActivity::reset();
  7627. }
  7628. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7629. {
  7630. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7631. skew = helper.getSkew();
  7632. numDivisions = helper.getNumDivisions();
  7633. //Check for -ve integer values and treat as out of range
  7634. if ((__int64)numDivisions < 1)
  7635. numDivisions = 1;
  7636. if (flags & TQFhasrange)
  7637. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7638. else
  7639. {
  7640. rangeIsAll = true;
  7641. rangeSize = 0;
  7642. }
  7643. if (rangeSize)
  7644. {
  7645. //Sort the range items into order to allow quick comparison
  7646. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7647. }
  7648. calculated = false;
  7649. processedAny = false;
  7650. anyThisGroup = false;
  7651. eof = false;
  7652. curQuantile = 0;
  7653. prevIndex = 0;
  7654. curIndex = 0;
  7655. curIndexExtra = 0;
  7656. }
  7657. virtual bool needsAllocator() const { return true; }
  7658. virtual const void * nextRow()
  7659. {
  7660. ActivityTimer t(totalCycles, timeActivities);
  7661. if (eof)
  7662. return NULL;
  7663. const void * ret = NULL;
  7664. for(;;)
  7665. {
  7666. if (!calculated)
  7667. {
  7668. if (flags & TQFlocalsorted)
  7669. {
  7670. for (;;)
  7671. {
  7672. const void * next = inputStream->nextRow();
  7673. if (!next)
  7674. break;
  7675. sorted.append(next);
  7676. }
  7677. }
  7678. else
  7679. {
  7680. sorter->prepare(inputStream);
  7681. sorter->getSortedGroup(sorted);
  7682. }
  7683. if (sorted.ordinality() == 0)
  7684. {
  7685. if (processedAny)
  7686. {
  7687. eof = true;
  7688. return NULL;
  7689. }
  7690. //Unusual case 0 rows - add a default row instead
  7691. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7692. size32_t thisSize = helper.createDefault(rowBuilder);
  7693. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7694. }
  7695. calculated = true;
  7696. processedAny = true;
  7697. anyThisGroup = false;
  7698. curQuantile = 0;
  7699. curIndex = 0;
  7700. curIndexExtra = (unsigned)((numDivisions-1) / 2); // to ensure correctly rounded up
  7701. prevIndex = curIndex-1; // Ensure it doesn't match
  7702. skipSize = (unsigned)(sorted.ordinality() / numDivisions);
  7703. skipExtra = (unsigned)(sorted.ordinality() % numDivisions);
  7704. }
  7705. if (isQuantileIncluded(curQuantile))
  7706. {
  7707. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7708. {
  7709. const void * lhs = sorted.item(curIndex);
  7710. if (flags & TQFneedtransform)
  7711. {
  7712. unsigned outSize;
  7713. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7714. try
  7715. {
  7716. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7717. }
  7718. catch (IException *E)
  7719. {
  7720. throw makeWrappedException(E);
  7721. }
  7722. if (outSize)
  7723. ret = rowBuilder.finalizeRowClear(outSize);
  7724. }
  7725. else
  7726. {
  7727. LinkRoxieRow(lhs);
  7728. ret = lhs;
  7729. }
  7730. prevIndex = curIndex; // even if output was skipped?
  7731. }
  7732. }
  7733. curIndex += skipSize;
  7734. curIndexExtra += skipExtra;
  7735. if (curIndexExtra >= numDivisions)
  7736. {
  7737. curIndex++;
  7738. curIndexExtra -= numDivisions;
  7739. }
  7740. //Ensure the current index always stays valid.
  7741. if (curIndex >= sorted.ordinality())
  7742. curIndex = sorted.ordinality()-1;
  7743. curQuantile++;
  7744. if (curQuantile > numDivisions)
  7745. {
  7746. ReleaseRoxieRows(sorted);
  7747. sorter->reset();
  7748. calculated = false; // ready for next group
  7749. }
  7750. if (ret)
  7751. {
  7752. anyThisGroup = true;
  7753. processed++;
  7754. return ret;
  7755. }
  7756. if (curQuantile > numDivisions)
  7757. {
  7758. if (anyThisGroup)
  7759. return NULL;
  7760. }
  7761. }
  7762. }
  7763. bool isQuantileIncluded(unsigned quantile) const
  7764. {
  7765. if (quantile == 0)
  7766. return (flags & TQFfirst) != 0;
  7767. if (quantile == numDivisions)
  7768. return (flags & TQFlast) != 0;
  7769. if (rangeIsAll)
  7770. return true;
  7771. //Compare against the list of ranges provided
  7772. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7773. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7774. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7775. for (unsigned i = 0; i < rangeNum; i++)
  7776. {
  7777. if (ranges[i] == quantile)
  7778. return true;
  7779. }
  7780. return false;
  7781. }
  7782. };
  7783. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7784. {
  7785. unsigned flags;
  7786. public:
  7787. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7788. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7789. {
  7790. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7791. flags = quantileHelper->getFlags();
  7792. }
  7793. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7794. {
  7795. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7796. }
  7797. };
  7798. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7799. {
  7800. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7801. }
  7802. //=====================================================================================================
  7803. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7804. {
  7805. IHThorSortedArg &helper;
  7806. ICompare * compare;
  7807. const void *prev;
  7808. IRangeCompare * stepCompare;
  7809. public:
  7810. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7811. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7812. {
  7813. prev = NULL;
  7814. compare = helper.queryCompare();
  7815. stepCompare = NULL;
  7816. }
  7817. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7818. {
  7819. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7820. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7821. if (stepMeta)
  7822. stepCompare = stepMeta->queryCompare();
  7823. prev = NULL;
  7824. }
  7825. virtual void reset()
  7826. {
  7827. ReleaseClearRoxieRow(prev);
  7828. CRoxieServerActivity::reset();
  7829. }
  7830. virtual const void * nextRow()
  7831. {
  7832. ActivityTimer t(totalCycles, timeActivities);
  7833. const void *ret = inputStream->nextRow();
  7834. if (ret && prev && compare->docompare(prev, ret) > 0)
  7835. {
  7836. // MORE - better to give mismatching rows that indexes?
  7837. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7838. }
  7839. ReleaseRoxieRow(prev);
  7840. prev = ret;
  7841. if (ret)
  7842. {
  7843. LinkRoxieRow(prev);
  7844. processed++;
  7845. }
  7846. return ret;
  7847. }
  7848. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7849. {
  7850. ActivityTimer t(totalCycles, timeActivities);
  7851. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7852. if (ret && prev && compare->docompare(prev, ret) > 0)
  7853. {
  7854. // MORE - better to give mismatching rows that indexes?
  7855. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7856. }
  7857. ReleaseRoxieRow(prev);
  7858. prev = ret;
  7859. if (ret)
  7860. {
  7861. LinkRoxieRow(prev);
  7862. processed++;
  7863. }
  7864. return ret;
  7865. }
  7866. IInputSteppingMeta * querySteppingMeta()
  7867. {
  7868. return input->querySteppingMeta();
  7869. }
  7870. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7871. {
  7872. return input->gatherConjunctions(collector);
  7873. }
  7874. virtual void resetEOF()
  7875. {
  7876. inputStream->resetEOF();
  7877. }
  7878. };
  7879. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7880. {
  7881. public:
  7882. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7883. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7884. {
  7885. }
  7886. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7887. {
  7888. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7889. }
  7890. };
  7891. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7892. {
  7893. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7894. }
  7895. //=====================================================================================================
  7896. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7897. {
  7898. /*
  7899. BE VERY CAREFUL - this code is tricky.
  7900. Note that starts and stops (and resets) can occur in strange orders
  7901. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7902. The last stop should call the upstream stop.
  7903. The first reset should call the upstream reset.
  7904. 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
  7905. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7906. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7907. ignored in the minIndex calculation
  7908. */
  7909. public:
  7910. IHThorArg &helper;
  7911. unsigned activeOutputs;
  7912. unsigned numOutputs;
  7913. unsigned numOriginalOutputs;
  7914. QueueOf<const void, true> buffer;
  7915. CriticalSection crit;
  7916. CriticalSection crit2;
  7917. unsigned tailIdx;
  7918. unsigned headIdx;
  7919. Owned<IException> error;
  7920. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7921. {
  7922. bool eof, eofpending, stopped;
  7923. public:
  7924. CRoxieServerThroughSpillActivity *parent;
  7925. unsigned idx;
  7926. unsigned oid;
  7927. unsigned processed = 0;
  7928. unsigned numStarts = 0;
  7929. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7930. public:
  7931. IMPLEMENT_IINTERFACE;
  7932. OutputAdaptor()
  7933. {
  7934. parent = NULL;
  7935. oid = 0;
  7936. idx = 0;
  7937. processed = 0;
  7938. totalCycles = 0;
  7939. eofpending = false;
  7940. eof = false;
  7941. stopped = false;
  7942. }
  7943. ~OutputAdaptor()
  7944. {
  7945. if (traceStartStop)
  7946. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7947. }
  7948. void init()
  7949. {
  7950. if (traceStartStop)
  7951. DBGLOG("%p init Input adaptor %d", this, oid);
  7952. idx = 0;
  7953. eofpending = false;
  7954. eof = false;
  7955. stopped = false;
  7956. }
  7957. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7958. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7959. virtual IRoxieServerActivity *queryActivity()
  7960. {
  7961. return parent;
  7962. }
  7963. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7964. {
  7965. return parent->queryIndexReadActivity();
  7966. }
  7967. virtual unsigned __int64 queryTotalCycles() const
  7968. {
  7969. return totalCycles;
  7970. }
  7971. virtual const void * nextRow()
  7972. {
  7973. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  7974. if (eof)
  7975. return NULL;
  7976. const void *ret = parent->readBuffered(idx, oid);
  7977. #ifdef TRACE_SPLIT
  7978. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7979. #endif
  7980. if (ret)
  7981. {
  7982. processed++;
  7983. eofpending = false;
  7984. }
  7985. else if (eofpending)
  7986. eof = true;
  7987. else
  7988. eofpending = true;
  7989. return ret;
  7990. }
  7991. virtual IOutputMetaData * queryOutputMeta() const
  7992. {
  7993. return parent->queryOutputMeta();
  7994. }
  7995. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7996. {
  7997. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7998. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7999. // for minIndex to give the correct answers
  8000. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  8001. if (traceStartStop)
  8002. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  8003. parent->start(oid, parentExtractSize, parentExtract, paused);
  8004. numStarts++;
  8005. }
  8006. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  8007. {
  8008. parent->connectInputStreams(consumerOrdered);
  8009. streams.append(this);
  8010. return NULL;
  8011. }
  8012. virtual void stop()
  8013. {
  8014. if (traceStartStop)
  8015. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  8016. if (!stopped)
  8017. {
  8018. parent->stop(oid, idx); // NOTE - may call init()
  8019. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  8020. }
  8021. };
  8022. virtual void reset()
  8023. {
  8024. if (traceStartStop)
  8025. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  8026. parent->reset(oid);
  8027. idx = 0; // value should not be relevant really but this is the safest...
  8028. stopped = false;
  8029. };
  8030. virtual void resetEOF()
  8031. {
  8032. parent->resetEOF();
  8033. }
  8034. virtual void checkAbort()
  8035. {
  8036. parent->checkAbort();
  8037. }
  8038. } *adaptors;
  8039. bool *used;
  8040. unsigned nextFreeOutput()
  8041. {
  8042. unsigned i = numOutputs;
  8043. while (i)
  8044. {
  8045. i--;
  8046. if (!used[i])
  8047. return i;
  8048. }
  8049. throwUnexpected();
  8050. }
  8051. unsigned minIndex(unsigned exceptOid)
  8052. {
  8053. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  8054. // this is trying to determine whether any of the adaptors will in the future read a given record
  8055. unsigned minIdx = (unsigned) -1;
  8056. for (unsigned i = 0; i < numOutputs; i++)
  8057. {
  8058. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  8059. minIdx = adaptors[i].idx;
  8060. }
  8061. return minIdx;
  8062. }
  8063. inline bool isLastTailReader(unsigned exceptOid)
  8064. {
  8065. for (unsigned i = 0; i < numOutputs; i++)
  8066. {
  8067. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  8068. return false;
  8069. }
  8070. return true;
  8071. }
  8072. void initOutputs()
  8073. {
  8074. activeOutputs = numOutputs;
  8075. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8076. if (used[i])
  8077. adaptors[i].init();
  8078. state = STATEstarting;
  8079. }
  8080. public:
  8081. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8082. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  8083. {
  8084. numOriginalOutputs = numOutputs;
  8085. adaptors = new OutputAdaptor[numOutputs];
  8086. used = new bool[numOutputs];
  8087. for (unsigned i = 0; i < numOutputs; i++)
  8088. {
  8089. adaptors[i].parent = this;
  8090. adaptors[i].oid = i;
  8091. used[i] = false;
  8092. }
  8093. tailIdx = 0;
  8094. headIdx = 0;
  8095. activeOutputs = numOutputs;
  8096. }
  8097. ~CRoxieServerThroughSpillActivity()
  8098. {
  8099. delete [] adaptors;
  8100. delete [] used;
  8101. }
  8102. const void *readBuffered(unsigned &idx, unsigned oid)
  8103. {
  8104. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  8105. const unsigned curIdx = idx;
  8106. if (curIdx == headIdx) // test once without getting the crit2 sec
  8107. {
  8108. CriticalBlock b2(crit2); // but only one puller gets to read the head
  8109. if (curIdx == headIdx) // test again now that we have it
  8110. {
  8111. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  8112. if (error)
  8113. throw error.getLink();
  8114. try
  8115. {
  8116. const void *row = inputStream->nextRow();
  8117. if (activeOutputs==1)
  8118. {
  8119. #ifdef TRACE_SPLIT
  8120. CTXLOG("spill %d optimised return of %p", activityId, row);
  8121. #endif
  8122. headIdx++;
  8123. idx++;
  8124. return row; // optimization for the case where only one output still active.
  8125. }
  8126. CriticalBlock b(crit);
  8127. headIdx++;
  8128. idx++;
  8129. if (activeOutputs==1)
  8130. return row; // optimization for the case where only one output still active.
  8131. buffer.enqueue(row);
  8132. if (row) LinkRoxieRow(row);
  8133. return row;
  8134. }
  8135. catch (IException *E)
  8136. {
  8137. #ifdef TRACE_SPLIT
  8138. CTXLOG("spill %d caught exception", activityId);
  8139. #endif
  8140. error.set(E);
  8141. throw;
  8142. }
  8143. catch (...)
  8144. {
  8145. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  8146. error.set(E);
  8147. throw E;
  8148. }
  8149. }
  8150. }
  8151. CriticalBlock b(crit);
  8152. ActivityTimer t(totalCycles, timeActivities); // NOTE - time spent waiting for crit not included here. But it will have been included on the totalTime of the person holding the crit, so that is right
  8153. unsigned lidx = curIdx - tailIdx;
  8154. idx++;
  8155. if (!lidx)
  8156. {
  8157. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  8158. // 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
  8159. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  8160. {
  8161. tailIdx++;
  8162. const void *ret = buffer.dequeue(); // no need to link - last puller
  8163. #ifdef TRACE_SPLIT
  8164. CTXLOG("last puller return of %p", ret);
  8165. #endif
  8166. return ret;
  8167. }
  8168. }
  8169. const void *ret = buffer.item(lidx);
  8170. if (ret) LinkRoxieRow(ret);
  8171. #ifdef TRACE_SPLIT
  8172. CTXLOG("standard return of %p", ret);
  8173. #endif
  8174. return ret;
  8175. }
  8176. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8177. {
  8178. CriticalBlock b(crit);
  8179. if (error)
  8180. throw error.getLink();
  8181. if (collectFactoryStatistics)
  8182. factory->noteStarted(oid);
  8183. if (traceStartStop)
  8184. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8185. if (state != STATEstarted)
  8186. {
  8187. if (state != STATEstarting)
  8188. initOutputs();
  8189. tailIdx = 0;
  8190. headIdx = 0;
  8191. error.clear();
  8192. try
  8193. {
  8194. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8195. }
  8196. catch (IException *E)
  8197. {
  8198. #ifdef TRACE_SPLIT
  8199. CTXLOG("spill %d caught exception in start", activityId);
  8200. #endif
  8201. error.set(E);
  8202. throw;
  8203. }
  8204. catch (...)
  8205. {
  8206. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8207. error.set(E);
  8208. throw E;
  8209. }
  8210. }
  8211. }
  8212. void stop(unsigned oid, unsigned & idx)
  8213. {
  8214. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8215. CriticalBlock b(crit);
  8216. #ifdef TRACE_STARTSTOP
  8217. if (traceStartStop)
  8218. {
  8219. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8220. if (watchActivityId && watchActivityId==activityId)
  8221. {
  8222. CTXLOG("WATCH: stop %d", activityId);
  8223. }
  8224. }
  8225. #endif
  8226. if (state != STATEstarting && state != STATEstarted)
  8227. initOutputs();
  8228. if (activeOutputs > 1)
  8229. {
  8230. if (tailIdx==idx)
  8231. {
  8232. // Discard all buffered rows that are there purely for this adaptor to read them
  8233. unsigned min = minIndex(oid);
  8234. if (min != (unsigned) -1)
  8235. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8236. // Should never happen though if there are still some active.
  8237. // there may be a small window where adaptors are blocked on the semaphore...
  8238. {
  8239. #ifdef TRACE_SPLIT
  8240. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8241. #endif
  8242. while (tailIdx < min)
  8243. {
  8244. ReleaseRoxieRow(buffer.dequeue());
  8245. tailIdx++;
  8246. }
  8247. }
  8248. }
  8249. activeOutputs--;
  8250. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8251. return;
  8252. }
  8253. #ifdef TRACE_SPLIT
  8254. CTXLOG("%p: All outputs done", this);
  8255. #endif
  8256. activeOutputs = numOutputs;
  8257. CRoxieServerActivity::stop();
  8258. };
  8259. void reset(unsigned oid)
  8260. {
  8261. if (traceStartStop)
  8262. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8263. activeOutputs = numOutputs;
  8264. while (buffer.ordinality())
  8265. ReleaseRoxieRow(buffer.dequeue());
  8266. error.clear();
  8267. if (state != STATEreset) // make sure input is only reset once
  8268. CRoxieServerActivity::reset();
  8269. };
  8270. void connectInputStreams(bool consumerOrdered)
  8271. {
  8272. if (!inputStream)
  8273. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8274. }
  8275. virtual const void *nextRow()
  8276. {
  8277. throwUnexpected(); // Internal logic error - we are not anybody's input
  8278. }
  8279. virtual IOutputMetaData * queryOutputMeta() const
  8280. {
  8281. // if (outputMeta)
  8282. // return outputMeta;
  8283. // else
  8284. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8285. }
  8286. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8287. {
  8288. if (idx==(unsigned)-1)
  8289. idx = nextFreeOutput(); // MORE - what is this used for?
  8290. assertex(idx < numOriginalOutputs);
  8291. assertex(!used[idx]);
  8292. used[idx] = true;
  8293. return &adaptors[idx];
  8294. }
  8295. virtual void resetOutputsUsed()
  8296. {
  8297. numOutputs = 1;
  8298. activeOutputs = 1;
  8299. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8300. }
  8301. virtual void noteOutputUsed()
  8302. {
  8303. assertex(numOutputs < numOriginalOutputs);
  8304. numOutputs++;
  8305. activeOutputs = numOutputs;
  8306. }
  8307. virtual bool isPassThrough()
  8308. {
  8309. return numOutputs==1;
  8310. }
  8311. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  8312. {
  8313. for (unsigned i = 0; i < numOutputs; i++)
  8314. addEdgeStats(statsBuilder, i, adaptors[i].numStarts, adaptors[i].processed, 0);
  8315. }
  8316. };
  8317. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8318. {
  8319. public:
  8320. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8321. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8322. {
  8323. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8324. setNumOutputs(helper->getTempUsageCount() + 1);
  8325. }
  8326. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8327. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8328. {
  8329. setNumOutputs(_numOutputs);
  8330. }
  8331. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8332. {
  8333. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8334. }
  8335. };
  8336. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8337. {
  8338. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8339. }
  8340. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8341. {
  8342. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8343. }
  8344. //----------------------------------------------------------------------------------------------
  8345. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8346. {
  8347. public:
  8348. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8349. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8350. {
  8351. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8352. setNumOutputs(helper->numBranches());
  8353. }
  8354. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8355. {
  8356. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8357. }
  8358. };
  8359. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8360. {
  8361. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8362. }
  8363. //=====================================================================================================
  8364. #define PIPE_BUFSIZE 0x8000
  8365. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8366. {
  8367. StringBuffer msg;
  8368. if(pipe->hasError())
  8369. {
  8370. try
  8371. {
  8372. char error[512];
  8373. size32_t sz = pipe->readError(sizeof(error), error);
  8374. if(sz && sz!=(size32_t)-1)
  8375. msg.append(", stderr: '").append(sz, error).append("'");
  8376. }
  8377. catch (IException *e)
  8378. {
  8379. EXCLOG(e, "Error reading pipe stderr");
  8380. e->Release();
  8381. }
  8382. }
  8383. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8384. }
  8385. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8386. {
  8387. IHThorPipeReadArg &helper;
  8388. Owned<IPipeProcess> pipe;
  8389. StringAttr pipeCommand;
  8390. Owned<IOutputRowDeserializer> rowDeserializer;
  8391. Owned<IReadRowStream> readTransformer;
  8392. bool groupSignalled;
  8393. public:
  8394. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8395. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8396. {
  8397. groupSignalled = true;
  8398. }
  8399. virtual bool needsAllocator() const { return true; }
  8400. virtual void onCreate(IHThorArg *_colocalParent)
  8401. {
  8402. CRoxieServerActivity::onCreate(_colocalParent);
  8403. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8404. }
  8405. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8406. {
  8407. groupSignalled = true; // i.e. don't start with a NULL row
  8408. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8409. if (!readTransformer)
  8410. {
  8411. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8412. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8413. }
  8414. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8415. openPipe(pipeProgram);
  8416. }
  8417. virtual void stop()
  8418. {
  8419. CRoxieServerActivity::stop();
  8420. pipe.clear();
  8421. readTransformer->setStream(NULL);
  8422. }
  8423. virtual const void *nextRow()
  8424. {
  8425. ActivityTimer t(totalCycles, timeActivities);
  8426. while (!waitForPipe())
  8427. {
  8428. if (!pipe)
  8429. return NULL;
  8430. if (helper.getPipeFlags() & TPFgroupeachrow)
  8431. {
  8432. if (!groupSignalled)
  8433. {
  8434. groupSignalled = true;
  8435. return NULL;
  8436. }
  8437. }
  8438. }
  8439. const void *ret = readTransformer->next();
  8440. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8441. processed++;
  8442. groupSignalled = false;
  8443. return ret;
  8444. }
  8445. protected:
  8446. bool waitForPipe()
  8447. {
  8448. if (!pipe)
  8449. return false; // done
  8450. if (!readTransformer->eos())
  8451. return true;
  8452. verifyPipe();
  8453. return false;
  8454. }
  8455. void openPipe(char const * cmd)
  8456. {
  8457. pipeCommand.setown(cmd);
  8458. pipe.setown(createPipeProcess());
  8459. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8460. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8461. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8462. readTransformer->setStream(pipeReader.get());
  8463. }
  8464. void verifyPipe()
  8465. {
  8466. if (pipe)
  8467. {
  8468. unsigned err = pipe->wait();
  8469. if(err && !(helper.getPipeFlags() & TPFnofail))
  8470. {
  8471. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8472. }
  8473. pipe.clear();
  8474. }
  8475. }
  8476. };
  8477. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8478. {
  8479. IHThorPipeThroughArg &helper;
  8480. RecordPullerThread puller;
  8481. Owned<IPipeProcess> pipe;
  8482. StringAttr pipeCommand;
  8483. InterruptableSemaphore pipeVerified;
  8484. InterruptableSemaphore pipeOpened;
  8485. CachedOutputMetaData inputMeta;
  8486. Owned<IOutputRowSerializer> rowSerializer;
  8487. Owned<IOutputRowDeserializer> rowDeserializer;
  8488. Owned<IPipeWriteXformHelper> writeTransformer;
  8489. Owned<IReadRowStream> readTransformer;
  8490. bool firstRead;
  8491. bool recreate;
  8492. bool inputExhausted;
  8493. bool groupSignalled;
  8494. public:
  8495. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8496. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8497. {
  8498. recreate = helper.recreateEachRow();
  8499. groupSignalled = true;
  8500. firstRead = false;
  8501. inputExhausted = false;
  8502. }
  8503. virtual bool needsAllocator() const { return true; }
  8504. virtual void onCreate(IHThorArg *_colocalParent)
  8505. {
  8506. CRoxieServerActivity::onCreate(_colocalParent);
  8507. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8508. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8509. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8510. }
  8511. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8512. {
  8513. firstRead = true;
  8514. inputExhausted = false;
  8515. groupSignalled = true; // i.e. don't start with a NULL row
  8516. pipeVerified.reinit();
  8517. pipeOpened.reinit();
  8518. writeTransformer->ready();
  8519. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8520. if (!readTransformer)
  8521. {
  8522. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8523. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8524. }
  8525. if(!recreate)
  8526. {
  8527. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8528. openPipe(pipeProgram);
  8529. }
  8530. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8531. }
  8532. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8533. {
  8534. if (idx)
  8535. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8536. puller.setInput(this, _sourceIdx, _in);
  8537. inputMeta.set(_in->queryOutputMeta());
  8538. }
  8539. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8540. {
  8541. puller.connectInputStreams(ctx, consumerOrdered);
  8542. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8543. }
  8544. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8545. {
  8546. if (idx==0)
  8547. return puller.queryInput();
  8548. else
  8549. return NULL;
  8550. }
  8551. virtual void stop()
  8552. {
  8553. pipeVerified.interrupt(NULL);
  8554. pipeOpened.interrupt(NULL);
  8555. puller.stop();
  8556. CRoxieServerActivity::stop();
  8557. pipe.clear();
  8558. if (readTransformer)
  8559. readTransformer->setStream(NULL);
  8560. }
  8561. virtual void reset()
  8562. {
  8563. puller.reset();
  8564. CRoxieServerActivity::reset();
  8565. }
  8566. virtual const void *nextRow()
  8567. {
  8568. ActivityTimer t(totalCycles, timeActivities);
  8569. while (!waitForPipe())
  8570. {
  8571. if (!pipe)
  8572. return NULL;
  8573. if (helper.getPipeFlags() & TPFgroupeachrow)
  8574. {
  8575. if (!groupSignalled)
  8576. {
  8577. groupSignalled = true;
  8578. return NULL;
  8579. }
  8580. }
  8581. }
  8582. const void *ret = readTransformer->next();
  8583. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8584. processed++;
  8585. groupSignalled = false;
  8586. return ret;
  8587. }
  8588. virtual void processRow(const void *row)
  8589. {
  8590. // called from puller thread
  8591. if(recreate)
  8592. openPipe(helper.getNameFromRow(row));
  8593. writeTransformer->writeTranslatedText(row, pipe);
  8594. ReleaseRoxieRow(row);
  8595. if(recreate)
  8596. {
  8597. closePipe();
  8598. pipeVerified.wait();
  8599. }
  8600. }
  8601. virtual void processDone()
  8602. {
  8603. // called from puller thread
  8604. if(recreate)
  8605. {
  8606. inputExhausted = true;
  8607. pipeOpened.signal();
  8608. }
  8609. else
  8610. {
  8611. closePipe();
  8612. pipeVerified.wait();
  8613. }
  8614. }
  8615. virtual void processEOG()
  8616. {
  8617. }
  8618. void processGroup(const ConstPointerArray &)
  8619. {
  8620. throwUnexpected();
  8621. }
  8622. virtual bool fireException(IException *e)
  8623. {
  8624. pipeOpened.interrupt(LINK(e));
  8625. pipeVerified.interrupt(e);
  8626. return true;
  8627. }
  8628. private:
  8629. bool waitForPipe()
  8630. {
  8631. if (firstRead)
  8632. {
  8633. pipeOpened.wait();
  8634. firstRead = false;
  8635. }
  8636. if (!pipe)
  8637. return false; // done
  8638. if (!readTransformer->eos())
  8639. return true;
  8640. verifyPipe();
  8641. if (recreate && !inputExhausted)
  8642. pipeOpened.wait();
  8643. return false;
  8644. }
  8645. void openPipe(char const * cmd)
  8646. {
  8647. pipeCommand.setown(cmd);
  8648. pipe.setown(createPipeProcess());
  8649. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8650. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8651. writeTransformer->writeHeader(pipe);
  8652. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8653. readTransformer->setStream(pipeReader.get());
  8654. pipeOpened.signal();
  8655. }
  8656. void closePipe()
  8657. {
  8658. writeTransformer->writeFooter(pipe);
  8659. pipe->closeInput();
  8660. }
  8661. void verifyPipe()
  8662. {
  8663. if (pipe)
  8664. {
  8665. unsigned err = pipe->wait();
  8666. if(err && !(helper.getPipeFlags() & TPFnofail))
  8667. {
  8668. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8669. }
  8670. pipe.clear();
  8671. pipeVerified.signal();
  8672. }
  8673. }
  8674. };
  8675. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8676. {
  8677. IHThorPipeWriteArg &helper;
  8678. Owned<IPipeProcess> pipe;
  8679. StringAttr pipeCommand;
  8680. CachedOutputMetaData inputMeta;
  8681. Owned<IOutputRowSerializer> rowSerializer;
  8682. Owned<IPipeWriteXformHelper> writeTransformer;
  8683. bool firstRead;
  8684. bool recreate;
  8685. bool inputExhausted;
  8686. public:
  8687. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8688. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8689. {
  8690. recreate = helper.recreateEachRow();
  8691. firstRead = false;
  8692. inputExhausted = false;
  8693. }
  8694. virtual bool needsAllocator() const { return true; }
  8695. virtual void onCreate(IHThorArg *_colocalParent)
  8696. {
  8697. CRoxieServerActivity::onCreate(_colocalParent);
  8698. inputMeta.set(input->queryOutputMeta());
  8699. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8700. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8701. }
  8702. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8703. {
  8704. firstRead = true;
  8705. inputExhausted = false;
  8706. writeTransformer->ready();
  8707. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8708. if(!recreate)
  8709. {
  8710. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8711. openPipe(pipeProgram);
  8712. }
  8713. }
  8714. virtual void stop()
  8715. {
  8716. if (!aborted && helper.getSequence() >= 0)
  8717. {
  8718. WorkunitUpdate wu = ctx->updateWorkUnit();
  8719. if (wu)
  8720. {
  8721. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8722. if (result)
  8723. {
  8724. result->setResultTotalRowCount(processed);
  8725. result->setResultStatus(ResultStatusCalculated);
  8726. }
  8727. }
  8728. }
  8729. CRoxieServerActivity::stop();
  8730. pipe.clear();
  8731. }
  8732. virtual void onExecute()
  8733. {
  8734. for (;;)
  8735. {
  8736. const void *row = inputStream->ungroupedNextRow();
  8737. if (!row)
  8738. break;
  8739. processed++;
  8740. if(recreate)
  8741. openPipe(helper.getNameFromRow(row));
  8742. writeTransformer->writeTranslatedText(row, pipe);
  8743. ReleaseRoxieRow(row);
  8744. if(recreate)
  8745. closePipe();
  8746. }
  8747. closePipe();
  8748. }
  8749. private:
  8750. void openPipe(char const * cmd)
  8751. {
  8752. pipeCommand.setown(cmd);
  8753. pipe.setown(createPipeProcess());
  8754. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8755. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8756. writeTransformer->writeHeader(pipe);
  8757. }
  8758. void closePipe()
  8759. {
  8760. writeTransformer->writeFooter(pipe);
  8761. pipe->closeInput();
  8762. unsigned err = pipe->wait();
  8763. if(err && !(helper.getPipeFlags() & TPFnofail))
  8764. {
  8765. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8766. }
  8767. pipe.clear();
  8768. }
  8769. };
  8770. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8771. {
  8772. public:
  8773. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8774. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8775. {
  8776. }
  8777. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8778. {
  8779. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8780. }
  8781. };
  8782. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8783. {
  8784. public:
  8785. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8786. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8787. {
  8788. }
  8789. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8790. {
  8791. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8792. }
  8793. };
  8794. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8795. {
  8796. public:
  8797. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8798. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8799. {
  8800. }
  8801. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8802. {
  8803. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8804. }
  8805. };
  8806. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8807. {
  8808. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8809. }
  8810. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8811. {
  8812. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8813. }
  8814. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8815. {
  8816. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8817. }
  8818. //=====================================================================================================
  8819. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8820. {
  8821. IHThorStreamedIteratorArg &helper;
  8822. Owned<IRowStream> rows;
  8823. public:
  8824. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8825. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8826. {
  8827. }
  8828. ~CRoxieServerStreamedIteratorActivity()
  8829. {
  8830. }
  8831. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8832. {
  8833. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8834. rows.setown(helper.createInput());
  8835. }
  8836. virtual void stop()
  8837. {
  8838. if (rows)
  8839. {
  8840. rows->stop();
  8841. rows.clear();
  8842. }
  8843. CRoxieServerActivity::stop();
  8844. }
  8845. virtual const void *nextRow()
  8846. {
  8847. ActivityTimer t(totalCycles, timeActivities);
  8848. assertex(rows != NULL);
  8849. const void * next = rows->nextRow();
  8850. if (next)
  8851. processed++;
  8852. return next;
  8853. }
  8854. };
  8855. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8856. {
  8857. public:
  8858. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8859. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8860. {
  8861. }
  8862. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8863. {
  8864. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8865. }
  8866. };
  8867. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8868. {
  8869. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8870. }
  8871. //=====================================================================================================
  8872. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8873. {
  8874. IHThorFilterArg &helper;
  8875. bool anyThisGroup;
  8876. IRangeCompare * stepCompare;
  8877. public:
  8878. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8879. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8880. {
  8881. anyThisGroup = false;
  8882. stepCompare = NULL;
  8883. }
  8884. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8885. {
  8886. anyThisGroup = false;
  8887. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8888. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8889. stepCompare = NULL;
  8890. if (!eof)
  8891. {
  8892. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8893. if (stepMeta)
  8894. stepCompare = stepMeta->queryCompare();
  8895. }
  8896. }
  8897. virtual const void * nextRow()
  8898. {
  8899. ActivityTimer t(totalCycles, timeActivities);
  8900. if (eof)
  8901. return NULL;
  8902. for (;;)
  8903. {
  8904. OwnedConstRoxieRow ret(inputStream->nextRow());
  8905. if (!ret)
  8906. {
  8907. //stop returning two NULLs in a row.
  8908. if (anyThisGroup)
  8909. {
  8910. anyThisGroup = false;
  8911. return NULL;
  8912. }
  8913. ret.setown(inputStream->nextRow());
  8914. if (!ret)
  8915. {
  8916. eof = true;
  8917. return NULL; // eof...
  8918. }
  8919. }
  8920. if (helper.isValid(ret))
  8921. {
  8922. anyThisGroup = true;
  8923. processed++;
  8924. return ret.getClear();
  8925. }
  8926. }
  8927. }
  8928. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8929. {
  8930. //Could assert that this isn't grouped
  8931. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8932. ActivityTimer t(totalCycles, timeActivities);
  8933. if (eof)
  8934. return NULL;
  8935. for (;;)
  8936. {
  8937. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  8938. if (!ret)
  8939. {
  8940. eof = true;
  8941. return NULL;
  8942. }
  8943. if (!wasCompleteMatch)
  8944. {
  8945. anyThisGroup = false; // RKC->GH - is this right??
  8946. return ret.getClear();
  8947. }
  8948. if (helper.isValid(ret))
  8949. {
  8950. anyThisGroup = true;
  8951. processed++;
  8952. return ret.getClear();
  8953. }
  8954. if (!stepExtra.returnMismatches())
  8955. {
  8956. ret.clear();
  8957. return nextRow();
  8958. }
  8959. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8960. //condition to advance
  8961. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8962. {
  8963. wasCompleteMatch = false;
  8964. anyThisGroup = false; // WHY?
  8965. return ret.getClear();
  8966. }
  8967. }
  8968. }
  8969. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8970. {
  8971. return input->gatherConjunctions(collector);
  8972. }
  8973. virtual void resetEOF()
  8974. {
  8975. eof = prefiltered;
  8976. anyThisGroup = false;
  8977. inputStream->resetEOF();
  8978. }
  8979. IInputSteppingMeta * querySteppingMeta()
  8980. {
  8981. return input->querySteppingMeta();
  8982. }
  8983. };
  8984. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8985. {
  8986. public:
  8987. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8988. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8989. {
  8990. optStableInput = false;
  8991. }
  8992. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8993. {
  8994. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  8995. }
  8996. };
  8997. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8998. {
  8999. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9000. }
  9001. //=====================================================================================================
  9002. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  9003. {
  9004. IHThorFilterGroupArg &helper;
  9005. unsigned curIndex;
  9006. ConstPointerArray gathered;
  9007. IRangeCompare * stepCompare;
  9008. public:
  9009. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9010. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  9011. {
  9012. curIndex = 0;
  9013. stepCompare = NULL;
  9014. }
  9015. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9016. {
  9017. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  9018. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  9019. assertex(eof == !helper.canMatchAny());
  9020. curIndex = 0;
  9021. stepCompare = NULL;
  9022. if (!eof)
  9023. {
  9024. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  9025. if (inputStepping)
  9026. stepCompare = inputStepping->queryCompare();
  9027. }
  9028. }
  9029. virtual void reset()
  9030. {
  9031. releaseGathered();
  9032. CRoxieServerLateStartActivity::reset();
  9033. }
  9034. inline void releaseGathered()
  9035. {
  9036. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9037. gathered.kill();
  9038. curIndex = 0;
  9039. }
  9040. virtual const void * nextRow()
  9041. {
  9042. ActivityTimer t(totalCycles, timeActivities);
  9043. for (;;)
  9044. {
  9045. if (eof)
  9046. return NULL;
  9047. if (gathered.ordinality())
  9048. {
  9049. if (gathered.isItem(curIndex))
  9050. {
  9051. const void * ret = gathered.item(curIndex++);
  9052. processed++;
  9053. return ret;
  9054. }
  9055. curIndex = 0;
  9056. gathered.kill();
  9057. return NULL;
  9058. }
  9059. const void * ret = inputStream->nextRow();
  9060. while (ret)
  9061. {
  9062. gathered.append(ret);
  9063. ret = inputStream->nextRow();
  9064. }
  9065. unsigned num = gathered.ordinality();
  9066. if (num != 0)
  9067. {
  9068. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9069. ReleaseRoxieRows(gathered); // read next group
  9070. }
  9071. else
  9072. eof = true;
  9073. }
  9074. }
  9075. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9076. {
  9077. ActivityTimer t(totalCycles, timeActivities);
  9078. if (eof)
  9079. return NULL;
  9080. if (gathered.ordinality())
  9081. {
  9082. while (gathered.isItem(curIndex))
  9083. {
  9084. const void * ret = gathered.item(curIndex++);
  9085. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  9086. {
  9087. processed++;
  9088. return ret;
  9089. }
  9090. ReleaseRoxieRow(ret);
  9091. }
  9092. curIndex = 0;
  9093. gathered.kill();
  9094. //nextRowGE never returns an end of group marker.
  9095. }
  9096. //Not completely sure about this - it could lead the the start of a group being skipped,
  9097. //so the group filter could potentially work on a different group. If so, we'd need to check the
  9098. //next fields were a subset of the grouping fields - more an issue for the group activity.
  9099. //MORE: What do we do with wasCompleteMatch? something like the following????
  9100. #if 0
  9101. for (;;)
  9102. {
  9103. const void * ret;
  9104. if (stepExtra.returnMismatches())
  9105. {
  9106. bool matchedCompletely = true;
  9107. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9108. if (!wasCompleteMatch)
  9109. return ret;
  9110. }
  9111. else
  9112. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9113. #endif
  9114. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9115. while (ret)
  9116. {
  9117. gathered.append(ret);
  9118. ret = inputStream->nextRow();
  9119. }
  9120. unsigned num = gathered.ordinality();
  9121. if (num != 0)
  9122. {
  9123. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9124. ReleaseRoxieRows(gathered); // read next group
  9125. }
  9126. else
  9127. eof = true;
  9128. return IEngineRowStream::ungroupedNextRow();
  9129. }
  9130. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9131. {
  9132. return input->gatherConjunctions(collector);
  9133. }
  9134. virtual void resetEOF()
  9135. {
  9136. eof = false;
  9137. releaseGathered();
  9138. inputStream->resetEOF();
  9139. }
  9140. IInputSteppingMeta * querySteppingMeta()
  9141. {
  9142. return input->querySteppingMeta();
  9143. }
  9144. };
  9145. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  9146. {
  9147. public:
  9148. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9149. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9150. {
  9151. }
  9152. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9153. {
  9154. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  9155. }
  9156. };
  9157. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9158. {
  9159. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9160. }
  9161. //=================================================================================
  9162. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  9163. {
  9164. IHThorSideEffectArg &helper;
  9165. CriticalSection ecrit;
  9166. Owned<IException> exception;
  9167. bool executed;
  9168. public:
  9169. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9170. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  9171. {
  9172. executed = false;
  9173. }
  9174. virtual const void * nextRow()
  9175. {
  9176. ActivityTimer t(totalCycles, timeActivities);
  9177. CriticalBlock b(ecrit);
  9178. if (exception)
  9179. throw(exception.getLink());
  9180. if (!executed)
  9181. {
  9182. try
  9183. {
  9184. executed = true;
  9185. helper.action();
  9186. }
  9187. catch(IException *E)
  9188. {
  9189. exception.set(E);
  9190. throw;
  9191. }
  9192. }
  9193. return NULL;
  9194. }
  9195. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9196. {
  9197. CriticalBlock b(ecrit);
  9198. if (exception)
  9199. throw(exception.getLink());
  9200. if (!executed)
  9201. {
  9202. try
  9203. {
  9204. ActivityTimer t(totalCycles, timeActivities);
  9205. executed = true;
  9206. start(parentExtractSize, parentExtract, false);
  9207. helper.action();
  9208. stop();
  9209. }
  9210. catch(IException *E)
  9211. {
  9212. ctx->notifyAbort(E);
  9213. abort();
  9214. exception.set(E);
  9215. throw;
  9216. }
  9217. }
  9218. }
  9219. virtual void reset()
  9220. {
  9221. executed = false;
  9222. exception.clear();
  9223. CRoxieServerActivity::reset();
  9224. }
  9225. };
  9226. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9227. {
  9228. bool isRoot;
  9229. public:
  9230. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9231. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9232. {
  9233. }
  9234. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9235. {
  9236. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9237. }
  9238. virtual bool isSink() const
  9239. {
  9240. return isRoot && !meta.queryOriginal();
  9241. }
  9242. };
  9243. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9244. {
  9245. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9246. }
  9247. //=================================================================================
  9248. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9249. {
  9250. IHThorActionArg &helper;
  9251. public:
  9252. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9253. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9254. {
  9255. }
  9256. virtual void onExecute()
  9257. {
  9258. helper.action();
  9259. }
  9260. };
  9261. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9262. {
  9263. public:
  9264. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9265. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9266. {
  9267. }
  9268. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9269. {
  9270. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9271. }
  9272. };
  9273. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9274. {
  9275. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9276. }
  9277. //=================================================================================
  9278. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9279. {
  9280. IHThorSampleArg &helper;
  9281. unsigned numSamples;
  9282. unsigned numToSkip;
  9283. unsigned whichSample;
  9284. bool anyThisGroup;
  9285. bool eof;
  9286. public:
  9287. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9288. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9289. {
  9290. numSamples = 0;
  9291. numToSkip = 0;
  9292. whichSample = 0;
  9293. anyThisGroup = false;
  9294. eof = false;
  9295. }
  9296. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9297. {
  9298. anyThisGroup = false;
  9299. eof = false;
  9300. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9301. numSamples = helper.getProportion();
  9302. whichSample = helper.getSampleNumber();
  9303. numToSkip = (whichSample ? whichSample-1 : 0);
  9304. }
  9305. virtual const void * nextRow()
  9306. {
  9307. ActivityTimer t(totalCycles, timeActivities);
  9308. if (eof)
  9309. return NULL;
  9310. for (;;)
  9311. {
  9312. const void * ret = inputStream->nextRow();
  9313. if (!ret)
  9314. {
  9315. //this does work with groups - may or may not be useful...
  9316. //reset the sample for each group.... probably best.
  9317. numToSkip = (whichSample ? whichSample-1 : 0);
  9318. if (anyThisGroup)
  9319. {
  9320. anyThisGroup = false;
  9321. return NULL;
  9322. }
  9323. ret = inputStream->nextRow();
  9324. if (!ret)
  9325. {
  9326. eof = true;
  9327. return NULL; // eof...
  9328. }
  9329. }
  9330. if (numToSkip == 0)
  9331. {
  9332. anyThisGroup = true;
  9333. numToSkip = numSamples-1;
  9334. processed++;
  9335. return ret;
  9336. }
  9337. numToSkip--;
  9338. ReleaseRoxieRow(ret);
  9339. }
  9340. }
  9341. };
  9342. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9343. {
  9344. public:
  9345. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9346. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9347. {
  9348. }
  9349. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9350. {
  9351. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9352. }
  9353. };
  9354. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9355. {
  9356. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9357. }
  9358. //=================================================================================
  9359. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9360. {
  9361. IHThorChooseSetsArg &helper;
  9362. unsigned numSets;
  9363. unsigned * setCounts;
  9364. bool done;
  9365. public:
  9366. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9367. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9368. {
  9369. setCounts = NULL;
  9370. numSets = 0;
  9371. done = false;
  9372. }
  9373. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9374. {
  9375. done = false;
  9376. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9377. numSets = helper.getNumSets();
  9378. setCounts = new unsigned[numSets];
  9379. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9380. helper.setCounts(setCounts);
  9381. }
  9382. virtual void reset()
  9383. {
  9384. delete [] setCounts;
  9385. setCounts = NULL;
  9386. CRoxieServerActivity::reset();
  9387. }
  9388. virtual const void * nextRow()
  9389. {
  9390. ActivityTimer t(totalCycles, timeActivities);
  9391. if (done)
  9392. return NULL;
  9393. for (;;)
  9394. {
  9395. const void * ret = inputStream->ungroupedNextRow();
  9396. if (!ret)
  9397. {
  9398. done = true;
  9399. return NULL;
  9400. }
  9401. processed++;
  9402. switch (helper.getRecordAction(ret))
  9403. {
  9404. case 2:
  9405. done = true;
  9406. return ret;
  9407. case 1:
  9408. return ret;
  9409. }
  9410. ReleaseRoxieRow(ret);
  9411. }
  9412. }
  9413. };
  9414. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9415. {
  9416. public:
  9417. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9418. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9419. {
  9420. }
  9421. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9422. {
  9423. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9424. }
  9425. };
  9426. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9427. {
  9428. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9429. }
  9430. //=================================================================================
  9431. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9432. {
  9433. protected:
  9434. IHThorChooseSetsExArg &helper;
  9435. unsigned numSets;
  9436. unsigned curIndex;
  9437. unsigned * setCounts;
  9438. count_t * limits;
  9439. bool done;
  9440. ConstPointerArray gathered;
  9441. virtual bool includeRow(const void * row) = 0;
  9442. virtual void calculateSelection() = 0;
  9443. public:
  9444. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9445. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9446. {
  9447. setCounts = NULL;
  9448. limits = NULL;
  9449. done = false;
  9450. curIndex = 0;
  9451. numSets = 0;
  9452. }
  9453. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9454. {
  9455. done = false;
  9456. curIndex = 0;
  9457. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9458. numSets = helper.getNumSets();
  9459. setCounts = new unsigned[numSets];
  9460. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9461. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9462. helper.getLimits(limits);
  9463. }
  9464. virtual void reset()
  9465. {
  9466. delete [] setCounts;
  9467. setCounts = NULL;
  9468. free(limits);
  9469. limits = NULL;
  9470. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9471. gathered.kill();
  9472. curIndex = 0;
  9473. CRoxieServerActivity::reset();
  9474. }
  9475. virtual const void * nextRow()
  9476. {
  9477. ActivityTimer t(totalCycles, timeActivities);
  9478. if (gathered.ordinality() == 0)
  9479. {
  9480. curIndex = 0;
  9481. if (!inputStream->nextGroup(gathered))
  9482. {
  9483. done = true;
  9484. return NULL;
  9485. }
  9486. ForEachItemIn(idx1, gathered)
  9487. {
  9488. unsigned category = helper.getCategory(gathered.item(idx1));
  9489. if (category)
  9490. setCounts[category-1]++;
  9491. }
  9492. calculateSelection();
  9493. }
  9494. while (gathered.isItem(curIndex))
  9495. {
  9496. const void * row = gathered.item(curIndex);
  9497. gathered.replace(NULL, curIndex);
  9498. curIndex++;
  9499. if (includeRow(row))
  9500. {
  9501. processed++;
  9502. return row;
  9503. }
  9504. ReleaseRoxieRow(row);
  9505. }
  9506. gathered.kill();
  9507. return NULL;
  9508. }
  9509. };
  9510. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9511. {
  9512. unsigned * numToSkip;
  9513. public:
  9514. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9515. {
  9516. numToSkip = NULL;
  9517. }
  9518. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9519. {
  9520. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9521. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9522. }
  9523. virtual void reset()
  9524. {
  9525. free(numToSkip);
  9526. numToSkip = NULL;
  9527. CRoxieServerChooseSetsExActivity::reset();
  9528. }
  9529. protected:
  9530. virtual void calculateSelection()
  9531. {
  9532. for (unsigned idx=0; idx < numSets; idx++)
  9533. {
  9534. if (setCounts[idx] < limits[idx])
  9535. numToSkip[idx] = 0;
  9536. else
  9537. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9538. }
  9539. }
  9540. virtual bool includeRow(const void * row)
  9541. {
  9542. unsigned category = helper.getCategory(row);
  9543. if (category)
  9544. {
  9545. if (numToSkip[category-1] == 0)
  9546. return true;
  9547. numToSkip[category-1]--;
  9548. }
  9549. return false;
  9550. }
  9551. };
  9552. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9553. {
  9554. count_t * counter;
  9555. public:
  9556. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9557. {
  9558. counter = NULL;
  9559. }
  9560. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9561. {
  9562. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9563. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9564. }
  9565. virtual void reset()
  9566. {
  9567. free(counter);
  9568. counter = NULL;
  9569. CRoxieServerChooseSetsExActivity::reset();
  9570. }
  9571. protected:
  9572. virtual void calculateSelection()
  9573. {
  9574. }
  9575. virtual bool includeRow(const void * row)
  9576. {
  9577. unsigned category = helper.getCategory(row);
  9578. if (category)
  9579. {
  9580. assertex(category <= numSets);
  9581. counter[category-1] += limits[category-1];
  9582. if(counter[category-1] >= setCounts[category-1])
  9583. {
  9584. counter[category-1] -= setCounts[category-1];
  9585. return true;
  9586. }
  9587. }
  9588. return false;
  9589. }
  9590. };
  9591. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9592. {
  9593. public:
  9594. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9595. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9596. {
  9597. }
  9598. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9599. {
  9600. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9601. }
  9602. };
  9603. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9604. {
  9605. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9606. }
  9607. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9608. {
  9609. public:
  9610. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9611. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9612. {
  9613. }
  9614. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9615. {
  9616. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9617. }
  9618. };
  9619. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9620. {
  9621. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9622. }
  9623. //=================================================================================
  9624. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9625. {
  9626. IHThorEnthArg &helper;
  9627. unsigned __int64 numerator;
  9628. unsigned __int64 denominator;
  9629. unsigned __int64 counter;
  9630. bool eof;
  9631. public:
  9632. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9633. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9634. {
  9635. eof = false;
  9636. numerator = denominator = counter = 0;
  9637. }
  9638. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9639. {
  9640. eof = false;
  9641. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9642. numerator = helper.getProportionNumerator();
  9643. denominator = helper.getProportionDenominator();
  9644. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9645. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9646. if (counter >= denominator)
  9647. counter %= denominator;
  9648. }
  9649. inline bool wanted()
  9650. {
  9651. counter += numerator;
  9652. if(counter >= denominator)
  9653. {
  9654. counter -= denominator;
  9655. return true;
  9656. }
  9657. return false;
  9658. }
  9659. virtual const void * nextRow()
  9660. {
  9661. ActivityTimer t(totalCycles, timeActivities);
  9662. if (eof)
  9663. return NULL;
  9664. const void * ret;
  9665. for (;;)
  9666. {
  9667. ret = inputStream->ungroupedNextRow();
  9668. if (!ret) //eof
  9669. {
  9670. eof = true;
  9671. return ret;
  9672. }
  9673. if (wanted())
  9674. return ret;
  9675. ReleaseRoxieRow(ret);
  9676. }
  9677. }
  9678. };
  9679. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9680. {
  9681. public:
  9682. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9683. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9684. {
  9685. }
  9686. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9687. {
  9688. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9689. }
  9690. };
  9691. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9692. {
  9693. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9694. }
  9695. //=================================================================================
  9696. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9697. {
  9698. IHThorAggregateArg &helper;
  9699. bool eof;
  9700. bool isInputGrouped;
  9701. bool abortEarly;
  9702. public:
  9703. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9704. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9705. {
  9706. eof = false;
  9707. isInputGrouped = false;
  9708. abortEarly = false;
  9709. }
  9710. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9711. {
  9712. eof = false;
  9713. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9714. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9715. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9716. }
  9717. virtual bool needsAllocator() const { return true; }
  9718. virtual const void * nextRow()
  9719. {
  9720. ActivityTimer t(totalCycles, timeActivities);
  9721. if (eof)
  9722. return NULL;
  9723. const void * next = inputStream->nextRow();
  9724. if (!next && isInputGrouped)
  9725. {
  9726. eof = true;
  9727. return NULL;
  9728. }
  9729. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9730. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9731. if (next)
  9732. {
  9733. finalSize = helper.processFirst(rowBuilder, next);
  9734. ReleaseRoxieRow(next);
  9735. if (!abortEarly)
  9736. {
  9737. for (;;)
  9738. {
  9739. next = inputStream->nextRow();
  9740. if (!next)
  9741. break;
  9742. finalSize = helper.processNext(rowBuilder, next);
  9743. ReleaseRoxieRow(next);
  9744. }
  9745. }
  9746. }
  9747. if (!isInputGrouped) // either read all, or aborted early
  9748. eof = true;
  9749. processed++;
  9750. return rowBuilder.finalizeRowClear(finalSize);
  9751. }
  9752. };
  9753. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9754. {
  9755. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9756. {
  9757. protected:
  9758. IHThorAggregateArg &helper;
  9759. OwnedConstRoxieRow result;
  9760. bool eof = false;
  9761. bool isInputGrouped = false;
  9762. bool abortEarly = false;
  9763. public:
  9764. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9765. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9766. {
  9767. }
  9768. virtual const void * nextRow() override
  9769. {
  9770. ActivityTimer t(totalCycles, timeActivities);
  9771. if (eof || isAborting())
  9772. return NULL;
  9773. const void * next = inputStream->nextRow();
  9774. if (!next && isInputGrouped)
  9775. {
  9776. eof = true;
  9777. return NULL;
  9778. }
  9779. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9780. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9781. if (next)
  9782. {
  9783. finalSize = helper.processFirst(rowBuilder, next);
  9784. ReleaseRoxieRow(next);
  9785. if (!abortEarly)
  9786. {
  9787. for (;;)
  9788. {
  9789. next = inputStream->nextRow();
  9790. if (!next)
  9791. break;
  9792. finalSize = helper.processNext(rowBuilder, next);
  9793. ReleaseRoxieRow(next);
  9794. if (isAborting())
  9795. break;
  9796. }
  9797. }
  9798. }
  9799. if (!isInputGrouped) // either read all, or aborted early
  9800. eof = true;
  9801. processed++;
  9802. return rowBuilder.finalizeRowClear(finalSize);
  9803. }
  9804. virtual void threadmain() override
  9805. {
  9806. isInputGrouped = true; // gather no row if there are no input rows.
  9807. result.setown(nextRow());
  9808. queryActivity().noteStrandFinished(inputStream);
  9809. }
  9810. virtual void reset() override
  9811. {
  9812. StrandProcessor::reset();
  9813. result.clear();
  9814. eof = false;
  9815. }
  9816. //interface IOutputOutputCallback
  9817. virtual bool noteEndOfInputChunk() { return true; }
  9818. virtual void noteEndOfInput() {}
  9819. virtual void stopStream()
  9820. {
  9821. inputStream->stop();
  9822. }
  9823. const void * queryResult() const { return result; }
  9824. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9825. };
  9826. //This class is only used when a single aggregate is being calculated.
  9827. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9828. {
  9829. public:
  9830. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9831. {
  9832. }
  9833. virtual const void *nextRow()
  9834. {
  9835. return parent.getCombinedAggregate();
  9836. }
  9837. virtual void stop()
  9838. {
  9839. parent.outputStopped();
  9840. }
  9841. virtual void resetEOF()
  9842. {
  9843. throwUnexpected();
  9844. }
  9845. protected:
  9846. CRoxieServerStrandedAggregateActivity & parent;
  9847. } combiner;
  9848. class NullCallback : implements IOrderedOutputCallback
  9849. {
  9850. public:
  9851. virtual bool noteEndOfInputChunk() { return true; }
  9852. virtual void noteEndOfInput() {}
  9853. } nullCallback;
  9854. public:
  9855. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9856. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
  9857. {
  9858. isInputGrouped = false;
  9859. abortEarly = false;
  9860. }
  9861. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9862. {
  9863. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9864. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9865. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9866. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9867. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9868. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9869. strandOptions.numStrands = 1;
  9870. else if (!isInputGrouped)
  9871. combineStreams = true;
  9872. }
  9873. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9874. {
  9875. PointerArrayOf<IEngineRowStream> localStreams;
  9876. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9877. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9878. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9879. if (localStreams.ordinality() == 1)
  9880. combineStreams = false; // Select a more efficient/simpler code path
  9881. if (combineStreams)
  9882. {
  9883. assertex(!outJunction); // this needs more thought!
  9884. streams.append(&combiner);
  9885. }
  9886. else
  9887. {
  9888. streams.swapWith(localStreams);
  9889. }
  9890. return outJunction.getClear();
  9891. }
  9892. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9893. {
  9894. if (traceLevel > 4)
  9895. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9896. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9897. }
  9898. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9899. virtual bool needsAllocator() const { return true; }
  9900. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9901. {
  9902. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9903. onStartStrands();
  9904. if (combineStreams)
  9905. {
  9906. barrier.setown(createStrandBarrier());
  9907. ForEachItemIn(i, strands)
  9908. barrier->startStrand(queryAggregate(i));
  9909. active.store(1);
  9910. }
  9911. else
  9912. active.store(0);
  9913. }
  9914. virtual void reset() override
  9915. {
  9916. CRoxieServerStrandedActivity::reset();
  9917. barrier.clear();
  9918. calculated = false;
  9919. }
  9920. //Helper functions for the single aggregate case
  9921. const void * getCombinedAggregate()
  9922. {
  9923. if (calculated)
  9924. return NULL;
  9925. calculated= true;
  9926. barrier->waitForStrands();
  9927. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9928. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9929. bool isFirst = true;
  9930. for (unsigned i=0; i < numStrands(); i++)
  9931. {
  9932. const void * next = queryAggregate(i).queryResult();
  9933. if (next)
  9934. {
  9935. if (isFirst)
  9936. {
  9937. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9938. isFirst = false;
  9939. }
  9940. else
  9941. finalSize = helper.mergeAggregate(rowBuilder, next);
  9942. }
  9943. }
  9944. return rowBuilder.finalizeRowClear(finalSize);
  9945. }
  9946. void outputStopped()
  9947. {
  9948. //only called if generating a single result.
  9949. assertex(combineStreams);
  9950. if (barrier)
  9951. {
  9952. requestAbort(); // if strands are still running, abort them
  9953. barrier->waitForStrands();
  9954. }
  9955. else
  9956. {
  9957. ForEachItemIn(i, strands)
  9958. queryAggregate(i).stopStream();
  9959. }
  9960. CRoxieServerStrandedActivity::stop();
  9961. }
  9962. void noteStrandFinished(IRowStream * stream)
  9963. {
  9964. barrier->noteStrandFinished(stream);
  9965. }
  9966. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  9967. {
  9968. //The non-ordered aggregate does not need to process the ordered call back information.
  9969. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  9970. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  9971. return &nullCallback;
  9972. }
  9973. inline AggregateProcessor & queryAggregate(unsigned i)
  9974. {
  9975. return static_cast<AggregateProcessor &>(strands.item(i));
  9976. }
  9977. protected:
  9978. IHThorAggregateArg &helper;
  9979. Owned<IStrandBarrier> barrier;
  9980. IEngineRowStream * combinedStream = nullptr;
  9981. bool isInputGrouped;
  9982. bool abortEarly;
  9983. bool combineStreams = false;
  9984. bool calculated = false;
  9985. };
  9986. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9987. {
  9988. StrandOptions strandOptions;
  9989. public:
  9990. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9991. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  9992. {
  9993. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  9994. if (!(helper->getAggregateFlags() & TAForderedmerge))
  9995. optStableInput = false;
  9996. }
  9997. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9998. {
  9999. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  10000. }
  10001. };
  10002. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10003. {
  10004. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10005. }
  10006. //=================================================================================
  10007. typedef unsigned t_hashPrefix;
  10008. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  10009. {
  10010. IHThorHashAggregateArg &helper;
  10011. RowAggregator aggregated;
  10012. bool eof;
  10013. bool gathered;
  10014. bool isGroupedAggregate;
  10015. public:
  10016. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  10017. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  10018. isGroupedAggregate(_isGroupedAggregate),
  10019. aggregated(helper, helper)
  10020. {
  10021. eof = false;
  10022. gathered = false;
  10023. }
  10024. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10025. {
  10026. eof = false;
  10027. gathered = false;
  10028. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10029. }
  10030. virtual void reset()
  10031. {
  10032. aggregated.reset();
  10033. CRoxieServerActivity::reset();
  10034. }
  10035. virtual bool needsAllocator() const { return true; }
  10036. virtual const void * nextRow()
  10037. {
  10038. ActivityTimer t(totalCycles, timeActivities);
  10039. if (eof)
  10040. return NULL;
  10041. if (!gathered)
  10042. {
  10043. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  10044. bool eog = true;
  10045. for (;;)
  10046. {
  10047. const void * next = inputStream->nextRow();
  10048. if (!next)
  10049. {
  10050. if (isGroupedAggregate)
  10051. {
  10052. if (eog)
  10053. eof = true;
  10054. break;
  10055. }
  10056. next = inputStream->nextRow();
  10057. if (!next)
  10058. break;
  10059. }
  10060. eog = false;
  10061. aggregated.addRow(next);
  10062. ReleaseRoxieRow(next);
  10063. }
  10064. gathered = true;
  10065. }
  10066. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  10067. if (next)
  10068. {
  10069. processed++;
  10070. return next->finalizeRowClear();
  10071. }
  10072. if (!isGroupedAggregate)
  10073. eof = true;
  10074. aggregated.reset();
  10075. gathered = false;
  10076. return NULL;
  10077. }
  10078. };
  10079. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  10080. {
  10081. public:
  10082. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10083. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10084. {
  10085. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  10086. }
  10087. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10088. {
  10089. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  10090. }
  10091. protected:
  10092. bool isGroupedAggregate;
  10093. };
  10094. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10095. {
  10096. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10097. }
  10098. //=================================================================================
  10099. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  10100. {
  10101. IHThorDegroupArg &helper;
  10102. bool eof;
  10103. public:
  10104. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10105. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  10106. {
  10107. eof = false;
  10108. }
  10109. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10110. {
  10111. eof = false;
  10112. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10113. }
  10114. virtual const void * nextRow()
  10115. {
  10116. ActivityTimer t(totalCycles, timeActivities);
  10117. if (eof)
  10118. return NULL;
  10119. const void * ret = inputStream->ungroupedNextRow();
  10120. if (ret)
  10121. processed++;
  10122. else
  10123. eof = true;
  10124. return ret;
  10125. }
  10126. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  10127. {
  10128. ActivityTimer t(totalCycles, timeActivities);
  10129. if (eof)
  10130. return NULL;
  10131. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  10132. if (ret)
  10133. processed++;
  10134. else
  10135. eof = true;
  10136. return ret;
  10137. }
  10138. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  10139. {
  10140. return input->gatherConjunctions(collector);
  10141. }
  10142. virtual void resetEOF()
  10143. {
  10144. eof = false;
  10145. inputStream->resetEOF();
  10146. }
  10147. IInputSteppingMeta * querySteppingMeta()
  10148. {
  10149. return input->querySteppingMeta();
  10150. }
  10151. };
  10152. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  10153. {
  10154. public:
  10155. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10156. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10157. {
  10158. }
  10159. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10160. {
  10161. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  10162. }
  10163. };
  10164. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10165. {
  10166. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10167. }
  10168. //=================================================================================
  10169. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  10170. {
  10171. IHThorDiskReadArg &helper;
  10172. bool needTransform;
  10173. bool eof;
  10174. bool anyThisGroup;
  10175. unsigned __int64 rowLimit;
  10176. unsigned __int64 choosenLimit;
  10177. public:
  10178. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10179. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  10180. {
  10181. needTransform = helper.needTransform();
  10182. rowLimit = (unsigned __int64) -1;
  10183. choosenLimit = 0;
  10184. eof = false;
  10185. anyThisGroup = false;
  10186. }
  10187. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10188. {
  10189. anyThisGroup = false;
  10190. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10191. if (helper.canMatchAny())
  10192. eof = false;
  10193. else
  10194. eof = true;
  10195. choosenLimit = helper.getChooseNLimit();
  10196. rowLimit = helper.getRowLimit();
  10197. helper.setCallback(NULL); // members should not be called - change if they are
  10198. }
  10199. virtual bool needsAllocator() const { return true; }
  10200. virtual const void * nextRow()
  10201. {
  10202. ActivityTimer t(totalCycles, timeActivities);
  10203. if (eof)
  10204. return NULL;
  10205. if (processed==choosenLimit)
  10206. {
  10207. eof = true;
  10208. return NULL;
  10209. }
  10210. if (needTransform)
  10211. {
  10212. for (;;)
  10213. {
  10214. OwnedConstRoxieRow in = inputStream->nextRow();
  10215. if (!in)
  10216. {
  10217. if (anyThisGroup)
  10218. {
  10219. anyThisGroup = false;
  10220. return NULL;
  10221. }
  10222. in.setown(inputStream->nextRow());
  10223. if (!in)
  10224. {
  10225. eof = true;
  10226. return NULL; // eof...
  10227. }
  10228. }
  10229. if (likely(helper.canMatch(in)))
  10230. {
  10231. unsigned outSize;
  10232. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10233. try
  10234. {
  10235. outSize = helper.transform(rowBuilder, in);
  10236. }
  10237. catch (IException *E)
  10238. {
  10239. throw makeWrappedException(E);
  10240. }
  10241. if (outSize)
  10242. {
  10243. anyThisGroup = true;
  10244. processed++;
  10245. if (processed==rowLimit)
  10246. {
  10247. if (traceLevel > 4)
  10248. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10249. helper.onLimitExceeded();
  10250. }
  10251. return rowBuilder.finalizeRowClear(outSize);
  10252. }
  10253. }
  10254. }
  10255. }
  10256. else
  10257. {
  10258. const void *ret = inputStream->nextRow();
  10259. if (ret)
  10260. {
  10261. processed++;
  10262. if (processed==rowLimit)
  10263. {
  10264. if (traceLevel > 4)
  10265. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10266. ReleaseClearRoxieRow(ret);
  10267. helper.onLimitExceeded(); // should not return
  10268. throwUnexpected();
  10269. }
  10270. }
  10271. return ret;
  10272. }
  10273. }
  10274. };
  10275. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10276. {
  10277. public:
  10278. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10279. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10280. {
  10281. }
  10282. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10283. {
  10284. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10285. }
  10286. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10287. {
  10288. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite || sourceKind==TAKspillwrite) // Bit of a hack - codegen probably should differentiate
  10289. setInput(0, source, sourceIdx);
  10290. else
  10291. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10292. }
  10293. };
  10294. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10295. {
  10296. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10297. }
  10298. //=================================================================================
  10299. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10300. {
  10301. public:
  10302. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10303. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10304. {
  10305. }
  10306. ~CRoxieServerSpillWriteActivity()
  10307. {
  10308. }
  10309. virtual const void *nextRow()
  10310. {
  10311. ActivityTimer t(totalCycles, timeActivities);
  10312. return inputStream->nextRow();
  10313. }
  10314. };
  10315. //==================================================================================
  10316. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10317. {
  10318. protected:
  10319. Owned<IExtRowWriter> outSeq;
  10320. Owned<IOutputRowSerializer> rowSerializer;
  10321. Linked<IFileIOStream> diskout;
  10322. bool blockcompressed;
  10323. bool extend;
  10324. bool overwrite;
  10325. bool encrypted;
  10326. bool grouped;
  10327. IHThorDiskWriteArg &helper;
  10328. Owned<IRecordSize> diskmeta;
  10329. Owned<IRoxieWriteHandler> writer;
  10330. bool tallycrc;
  10331. unsigned __int64 uncompressedBytesWritten;
  10332. CRC32 crc;
  10333. void updateWorkUnitResult(unsigned __int64 reccount)
  10334. {
  10335. assertex(writer);
  10336. // MORE - a lot of this is common with hthor
  10337. WorkunitUpdate wu = ctx->updateWorkUnit();
  10338. if (wu)
  10339. {
  10340. OwnedRoxieString rawLogicalName = helper.getFileName();
  10341. StringBuffer lfn; // logical filename
  10342. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10343. if (lfn.length())
  10344. {
  10345. unsigned flags = helper.getFlags();
  10346. WUFileKind fileKind;
  10347. if (TDXtemporary & flags)
  10348. fileKind = WUFileTemporary;
  10349. else if(TDXjobtemp & flags)
  10350. fileKind = WUFileJobOwned;
  10351. else if(TDWowned & flags)
  10352. fileKind = WUFileOwned;
  10353. else
  10354. fileKind = WUFileStandard;
  10355. StringArray clusters;
  10356. writer->getClusters(clusters);
  10357. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10358. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10359. {
  10360. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10361. if (result)
  10362. {
  10363. result->setResultTotalRowCount(reccount);
  10364. result->setResultStatus(ResultStatusCalculated);
  10365. if (helper.getFlags() & TDWresult)
  10366. result->setResultFilename(lfn.str());
  10367. else
  10368. result->setResultLogicalName(lfn.str());
  10369. }
  10370. }
  10371. }
  10372. }
  10373. }
  10374. void resolve()
  10375. {
  10376. OwnedRoxieString rawLogicalName = helper.getFileName();
  10377. assertex(rawLogicalName);
  10378. assertex((helper.getFlags() & TDXtemporary) == 0);
  10379. StringArray clusters;
  10380. unsigned clusterIdx = 0;
  10381. while(true)
  10382. {
  10383. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10384. if(!cluster)
  10385. break;
  10386. clusters.append(cluster);
  10387. clusterIdx++;
  10388. }
  10389. if (clusters.length())
  10390. {
  10391. if (extend)
  10392. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10393. }
  10394. else
  10395. {
  10396. if (roxieName.length())
  10397. clusters.append(roxieName.str());
  10398. else
  10399. clusters.append(".");
  10400. }
  10401. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10402. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10403. }
  10404. public:
  10405. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10406. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10407. {
  10408. extend = ((helper.getFlags() & TDWextend) != 0);
  10409. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10410. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10411. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10412. if (grouped)
  10413. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10414. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta->getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  10415. encrypted = false; // set later
  10416. tallycrc = true;
  10417. uncompressedBytesWritten = 0;
  10418. }
  10419. ~CRoxieServerDiskWriteActivity()
  10420. {
  10421. }
  10422. virtual bool needsAllocator() const
  10423. {
  10424. return true;
  10425. }
  10426. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10427. {
  10428. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10429. resolve();
  10430. Owned<IFileIO> io;
  10431. void *ekey;
  10432. size32_t ekeylen;
  10433. helper.getEncryptKey(ekeylen, ekey);
  10434. Owned<ICompressor> ecomp;
  10435. if (ekeylen!=0)
  10436. {
  10437. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10438. memset(ekey,0,ekeylen);
  10439. rtlFree(ekey);
  10440. encrypted = true;
  10441. blockcompressed = true;
  10442. }
  10443. if (blockcompressed)
  10444. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10445. else
  10446. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10447. if (!io)
  10448. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10449. diskout.setown(createBufferedIOStream(io));
  10450. if (extend)
  10451. diskout->seek(0, IFSend);
  10452. tallycrc = !blockcompressed; // MORE: Should this be controlled by an activity hint/flag?
  10453. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10454. rowSerializer.set(rowIf->queryRowSerializer());
  10455. unsigned rwFlags = rw_autoflush;
  10456. if(grouped)
  10457. rwFlags |= rw_grouped;
  10458. if(tallycrc)
  10459. rwFlags |= rw_crc;
  10460. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10461. }
  10462. virtual void stop()
  10463. {
  10464. if (aborted)
  10465. {
  10466. if (writer)
  10467. writer->finish(false, this);
  10468. }
  10469. else
  10470. {
  10471. if (outSeq)
  10472. outSeq->flush(&crc);
  10473. if (outSeq)
  10474. uncompressedBytesWritten = outSeq->getPosition();
  10475. outSeq.clear();
  10476. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10477. if (writer)
  10478. {
  10479. updateWorkUnitResult(processed);
  10480. writer->finish(true, this);
  10481. }
  10482. }
  10483. writer.clear();
  10484. CRoxieServerActivity::stop();
  10485. }
  10486. virtual void reset()
  10487. {
  10488. CRoxieServerActivity::reset();
  10489. diskout.clear();
  10490. outSeq.clear();
  10491. writer.clear();
  10492. uncompressedBytesWritten = 0;
  10493. crc.reset();
  10494. }
  10495. virtual void onExecute()
  10496. {
  10497. for (;;)
  10498. {
  10499. const void *row = inputStream->nextRow();
  10500. if (!row)
  10501. {
  10502. row = inputStream->nextRow();
  10503. if (!row)
  10504. break;
  10505. if (grouped)
  10506. outSeq->putRow(NULL);
  10507. }
  10508. processed++;
  10509. outSeq->putRow(row);
  10510. }
  10511. }
  10512. virtual void setFileProperties(IFileDescriptor *desc) const
  10513. {
  10514. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10515. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10516. if (blockcompressed)
  10517. {
  10518. // caller has already set @size from file size...
  10519. fileProps.setPropBool("@blockCompressed", true);
  10520. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10521. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10522. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10523. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10524. }
  10525. else if (tallycrc && crc.get())
  10526. partProps.setPropInt64("@fileCrc", crc.get());
  10527. if (encrypted)
  10528. fileProps.setPropBool("@encrypted", true);
  10529. fileProps.setPropInt64("@recordCount", processed);
  10530. partProps.setPropInt64("@recordCount", processed);
  10531. unsigned flags = helper.getFlags();
  10532. if (flags & TDWpersist)
  10533. fileProps.setPropBool("@persistent", true);
  10534. if (grouped)
  10535. fileProps.setPropBool("@grouped", true);
  10536. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10537. fileProps.setPropBool("@owned", true);
  10538. if (flags & TDWresult)
  10539. fileProps.setPropBool("@result", true);
  10540. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10541. if (workUnit)
  10542. {
  10543. fileProps.setProp("@owner", workUnit->queryUser());
  10544. fileProps.setProp("@workunit", workUnit->queryWuid());
  10545. fileProps.setProp("@job", workUnit->queryJobName());
  10546. }
  10547. if (flags & TDWexpires)
  10548. setExpiryTime(fileProps, helper.getExpiryDays());
  10549. if (flags & TDWupdate)
  10550. {
  10551. unsigned eclCRC;
  10552. unsigned __int64 totalCRC;
  10553. helper.getUpdateCRCs(eclCRC, totalCRC);
  10554. fileProps.setPropInt("@eclCRC", eclCRC);
  10555. fileProps.setPropInt64("@totalCRC", totalCRC);
  10556. }
  10557. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10558. IRecordSize * inputMeta = input->queryOutputMeta();
  10559. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10560. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10561. const char *recordECL = helper.queryRecordECL();
  10562. if (recordECL && *recordECL)
  10563. fileProps.setProp("ECL", recordECL);
  10564. setRtlFormat(fileProps, helper.queryDiskRecordSize());
  10565. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10566. }
  10567. virtual IUserDescriptor *queryUserDescriptor() const
  10568. {
  10569. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10570. if (workUnit)
  10571. return workUnit->queryUserDescriptor();//ad-hoc mode
  10572. else
  10573. {
  10574. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10575. if (daliHelper)
  10576. return daliHelper->queryUserDescriptor();//predeployed query mode
  10577. }
  10578. return NULL;
  10579. }
  10580. virtual bool isOutputTransformed() const { return false; }
  10581. };
  10582. //=================================================================================
  10583. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10584. {
  10585. IHThorCsvWriteArg &csvHelper;
  10586. CSVOutputStream csvOutput;
  10587. public:
  10588. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10589. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10590. {
  10591. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10592. }
  10593. virtual void onExecute()
  10594. {
  10595. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10596. if (header)
  10597. {
  10598. csvOutput.beginLine();
  10599. csvOutput.writeHeaderLn(strlen(header), header);
  10600. diskout->write(csvOutput.length(), csvOutput.str());
  10601. }
  10602. for (;;)
  10603. {
  10604. const void *nextrec = inputStream->ungroupedNextRow();
  10605. if (!nextrec)
  10606. break;
  10607. processed++;
  10608. csvOutput.beginLine();
  10609. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10610. csvOutput.endLine();
  10611. diskout->write(csvOutput.length(), csvOutput.str());
  10612. ReleaseRoxieRow(nextrec);
  10613. }
  10614. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10615. if (footer)
  10616. {
  10617. csvOutput.beginLine();
  10618. csvOutput.writeHeaderLn(strlen(footer), footer);
  10619. diskout->write(csvOutput.length(), csvOutput.str());
  10620. }
  10621. }
  10622. virtual void setFileProperties(IFileDescriptor *desc) const
  10623. {
  10624. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10625. IPropertyTree &props = desc->queryProperties();
  10626. props.setProp("@format","utf8n");
  10627. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10628. StringBuffer separator;
  10629. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10630. const char *s = rs;
  10631. while (s && *s)
  10632. {
  10633. if (',' == *s)
  10634. separator.append("\\,");
  10635. else
  10636. separator.append(*s);
  10637. ++s;
  10638. }
  10639. props.setProp("@csvSeparate", separator.str());
  10640. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10641. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10642. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10643. props.setProp("@kind", "csv");
  10644. }
  10645. virtual bool isOutputTransformed() const { return true; }
  10646. };
  10647. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10648. {
  10649. IHThorXmlWriteArg &xmlHelper;
  10650. StringAttr rowTag;
  10651. ThorActivityKind kind;
  10652. unsigned headerLength;
  10653. unsigned footerLength;
  10654. public:
  10655. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10656. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10657. {
  10658. }
  10659. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10660. {
  10661. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10662. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10663. if (!xmlpath)
  10664. rowTag.set(DEFAULTXMLROWTAG);
  10665. else
  10666. {
  10667. const char *path = xmlpath;
  10668. if (*path == '/') path++;
  10669. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10670. rowTag.set(path);
  10671. }
  10672. }
  10673. virtual void onExecute()
  10674. {
  10675. StringBuffer header;
  10676. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10677. if (kind==TAKjsonwrite)
  10678. buildJsonHeader(header, suppliedHeader, rowTag);
  10679. else if (suppliedHeader)
  10680. header.set(suppliedHeader);
  10681. else
  10682. header.append(DEFAULTXMLHEADER).newline();
  10683. headerLength = header.length();
  10684. diskout->write(header.length(), header.str());
  10685. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSONRootless : WTStandard);
  10686. writer->outputBeginArray(rowTag); //need to set this
  10687. writer->clear(); //but not output it
  10688. for (;;)
  10689. {
  10690. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10691. if (!nextrec)
  10692. break;
  10693. processed++;
  10694. writer->clear().outputBeginNested(rowTag, false);
  10695. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10696. writer->outputEndNested(rowTag);
  10697. diskout->write(writer->length(), writer->str());
  10698. }
  10699. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10700. StringBuffer footer;
  10701. if (kind==TAKjsonwrite)
  10702. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10703. else if (suppliedFooter)
  10704. footer.append(suppliedFooter);
  10705. else
  10706. footer.append(DEFAULTXMLFOOTER);
  10707. footerLength=footer.length();
  10708. diskout->write(footer.length(), footer);
  10709. }
  10710. virtual void reset()
  10711. {
  10712. CRoxieServerDiskWriteActivity::reset();
  10713. rowTag.clear();
  10714. }
  10715. virtual void setFileProperties(IFileDescriptor *desc) const
  10716. {
  10717. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10718. desc->queryProperties().setProp("@format","utf8n");
  10719. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10720. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10721. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10722. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10723. }
  10724. virtual bool isOutputTransformed() const { return true; }
  10725. };
  10726. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10727. {
  10728. bool isRoot;
  10729. bool isTemp;
  10730. public:
  10731. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10732. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  10733. {
  10734. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10735. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10736. setNumOutputs(helper->getTempUsageCount());
  10737. if (_kind != TAKspillwrite)
  10738. assertex(numOutputs == 0);
  10739. }
  10740. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10741. {
  10742. switch (numOutputs)
  10743. {
  10744. case 0:
  10745. switch (kind)
  10746. {
  10747. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10748. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10749. case TAKxmlwrite:
  10750. case TAKjsonwrite:
  10751. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10752. };
  10753. throwUnexpected();
  10754. case 1:
  10755. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10756. default:
  10757. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10758. }
  10759. }
  10760. virtual bool isSink() const
  10761. {
  10762. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10763. }
  10764. };
  10765. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  10766. {
  10767. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  10768. }
  10769. //=================================================================================
  10770. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10771. {
  10772. IHThorIndexWriteArg &helper;
  10773. bool overwrite;
  10774. Owned<ClusterWriteHandler> clusterHandler;
  10775. Owned<IRoxieWriteHandler> writer;
  10776. unsigned __int64 reccount;
  10777. unsigned int fileCrc;
  10778. StringBuffer filename;
  10779. unsigned __int64 duplicateKeyCount = 0;
  10780. unsigned __int64 cummulativeDuplicateKeyCount = 0;
  10781. void updateWorkUnitResult()
  10782. {
  10783. // MORE - a lot of this is common with hthor
  10784. WorkunitUpdate wu = ctx->updateWorkUnit();
  10785. if (wu)
  10786. {
  10787. OwnedRoxieString rawLogicalName = helper.getFileName();
  10788. StringBuffer lfn; // logical filename
  10789. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10790. if (lfn.length())
  10791. {
  10792. if (helper.getSequence() >= 0)
  10793. {
  10794. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10795. if (result)
  10796. {
  10797. result->setResultTotalRowCount(reccount);
  10798. result->setResultStatus(ResultStatusCalculated);
  10799. result->setResultLogicalName(lfn.str());
  10800. }
  10801. }
  10802. if(clusterHandler)
  10803. clusterHandler->finish(writer->queryFile());
  10804. CTXLOG("Created roxie index file %s", lfn.str());
  10805. }
  10806. }
  10807. }
  10808. virtual void resolve()
  10809. {
  10810. StringArray clusters;
  10811. unsigned clusterIdx = 0;
  10812. while(true)
  10813. {
  10814. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10815. if(!cluster)
  10816. break;
  10817. clusters.append(cluster);
  10818. clusterIdx++;
  10819. }
  10820. if (roxieName.length())
  10821. clusters.append(roxieName.str());
  10822. else
  10823. clusters.append(".");
  10824. OwnedRoxieString fname(helper.getFileName());
  10825. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10826. filename.set(writer->queryFile()->queryFilename());
  10827. if (writer->queryFile()->exists())
  10828. {
  10829. if (overwrite)
  10830. {
  10831. CTXLOG("Removing existing %s from DFS",filename.str());
  10832. writer->queryFile()->remove();
  10833. }
  10834. else
  10835. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10836. }
  10837. }
  10838. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10839. {
  10840. size32_t nameLen;
  10841. char * nameBuff;
  10842. size32_t valueLen;
  10843. char * valueBuff;
  10844. unsigned idx = 0;
  10845. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10846. {
  10847. StringBuffer name(nameLen, nameBuff);
  10848. StringBuffer value(valueLen, valueBuff);
  10849. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10850. {
  10851. OwnedRoxieString fname(helper.getFileName());
  10852. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10853. }
  10854. if(!validateXMLTag(name.str()))
  10855. {
  10856. OwnedRoxieString fname(helper.getFileName());
  10857. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10858. }
  10859. if(!metadata)
  10860. metadata.setown(createPTree("metadata", ipt_fast));
  10861. metadata->setProp(name.str(), value.str());
  10862. }
  10863. }
  10864. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10865. {
  10866. if(!metadata)
  10867. metadata.setown(createPTree("metadata", ipt_fast));
  10868. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10869. setRtlFormat(*metadata, helper.queryDiskRecordSize());
  10870. }
  10871. public:
  10872. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10873. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10874. {
  10875. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10876. reccount = 0;
  10877. fileCrc = 0;
  10878. }
  10879. ~CRoxieServerIndexWriteActivity()
  10880. {
  10881. }
  10882. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10883. {
  10884. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10885. resolve();
  10886. }
  10887. virtual void onExecute()
  10888. {
  10889. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10890. size32_t fileposSize = hasTrailingFileposition(helper.queryDiskRecordSize()->queryTypeInfo()) ? sizeof(offset_t) : 0;
  10891. size32_t maxDiskRecordSize;
  10892. if (isVariable)
  10893. {
  10894. if (helper.getFlags() & TIWmaxlength)
  10895. maxDiskRecordSize = helper.getMaxKeySize();
  10896. else
  10897. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10898. }
  10899. else
  10900. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize()-fileposSize;
  10901. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10902. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10903. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10904. fileCrc = -1;
  10905. {
  10906. Owned<IFileIO> io;
  10907. try
  10908. {
  10909. io.setown(writer->queryFile()->open(IFOcreate));
  10910. }
  10911. catch(IException * e)
  10912. {
  10913. e->Release();
  10914. clearKeyStoreCache(false);
  10915. io.setown(writer->queryFile()->open(IFOcreate));
  10916. }
  10917. if(!io)
  10918. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10919. Owned<IFileIOStream> out = createIOStream(io);
  10920. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10921. if (helper.getFlags() & TIWrowcompress)
  10922. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10923. else if (!(helper.getFlags() & TIWnolzwcompress))
  10924. flags |= HTREE_COMPRESSED_KEY;
  10925. if (isVariable)
  10926. flags |= HTREE_VARSIZE;
  10927. Owned<IPropertyTree> metadata;
  10928. buildUserMetadata(metadata);
  10929. buildLayoutMetadata(metadata);
  10930. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10931. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0, &helper, true, false);
  10932. class BcWrapper : implements IBlobCreator
  10933. {
  10934. IKeyBuilder *builder;
  10935. public:
  10936. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10937. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10938. {
  10939. return builder->createBlob(size, (const char *) ptr);
  10940. }
  10941. } bc(builder);
  10942. // Loop thru the results
  10943. for (;;)
  10944. {
  10945. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10946. if (!nextrec)
  10947. break;
  10948. try
  10949. {
  10950. unsigned __int64 fpos=0;
  10951. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10952. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10953. builder->processKeyData(rowBuffer, fpos, thisSize);
  10954. }
  10955. catch(IException * e)
  10956. {
  10957. throw makeWrappedException(e);
  10958. }
  10959. reccount++;
  10960. }
  10961. duplicateKeyCount = builder->getDuplicateCount();
  10962. cummulativeDuplicateKeyCount += duplicateKeyCount;
  10963. builder->finish(metadata, &fileCrc);
  10964. }
  10965. }
  10966. virtual void stop()
  10967. {
  10968. if (writer)
  10969. {
  10970. if (!aborted)
  10971. updateWorkUnitResult();
  10972. writer->finish(!aborted, this);
  10973. writer.clear();
  10974. }
  10975. CRoxieServerActivity::stop();
  10976. }
  10977. virtual void reset()
  10978. {
  10979. noteStatistic(StNumDuplicateKeys, cummulativeDuplicateKeyCount);
  10980. CRoxieServerActivity::reset();
  10981. writer.clear();
  10982. }
  10983. //interface IRoxiePublishCallback
  10984. virtual void setFileProperties(IFileDescriptor *desc) const
  10985. {
  10986. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10987. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10988. // Now publish to name services
  10989. StringBuffer dir,base;
  10990. offset_t indexFileSize = writer->queryFile()->size();
  10991. if(clusterHandler)
  10992. clusterHandler->splitPhysicalFilename(dir, base);
  10993. else
  10994. {
  10995. // Check filename is URL and get localpath, only actually necessary if force remote reads are are on
  10996. RemoteFilename rfn;
  10997. rfn.setRemotePath(filename);
  10998. StringBuffer localPath;
  10999. rfn.getLocalPath(localPath);
  11000. splitFilename(localPath, &dir, &dir, &base, &base);
  11001. }
  11002. desc->setDefaultDir(dir.str());
  11003. //properties of the first file part.
  11004. Owned<IPropertyTree> attrs;
  11005. if(clusterHandler)
  11006. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  11007. else
  11008. {
  11009. // add cluster
  11010. StringBuffer mygroupname;
  11011. desc->setNumParts(1);
  11012. desc->setPartMask(base.str());
  11013. attrs.set(&desc->queryPart(0)->queryProperties());
  11014. }
  11015. attrs->setPropInt64("@size", indexFileSize);
  11016. attrs->setPropInt64("@recordCount", reccount);
  11017. CDateTime createTime, modifiedTime, accessedTime;
  11018. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  11019. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  11020. unsigned hour, min, sec, nanosec;
  11021. modifiedTime.getTime(hour, min, sec, nanosec);
  11022. modifiedTime.setTime(hour, min, sec, 0);
  11023. StringBuffer timestr;
  11024. modifiedTime.getString(timestr);
  11025. if(timestr.length())
  11026. attrs->setProp("@modified", timestr.str());
  11027. if(clusterHandler)
  11028. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  11029. // properties of the logical file
  11030. IPropertyTree & properties = desc->queryProperties();
  11031. properties.setProp("@kind", "key");
  11032. properties.setPropInt64("@size", indexFileSize);
  11033. properties.setPropInt64("@recordCount", reccount);
  11034. properties.setPropInt64("@duplicateKeyCount", duplicateKeyCount);
  11035. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  11036. if (workUnit)
  11037. {
  11038. properties.setProp("@owner", workUnit->queryUser());
  11039. properties.setProp("@workunit", workUnit->queryWuid());
  11040. properties.setProp("@job", workUnit->queryJobName());
  11041. }
  11042. char const * rececl = helper.queryRecordECL();
  11043. if(rececl && *rececl)
  11044. properties.setProp("ECL", rececl);
  11045. if (helper.getFlags() & TIWexpires)
  11046. setExpiryTime(properties, helper.getExpiryDays());
  11047. if (helper.getFlags() & TIWupdate)
  11048. {
  11049. unsigned eclCRC;
  11050. unsigned __int64 totalCRC;
  11051. helper.getUpdateCRCs(eclCRC, totalCRC);
  11052. properties.setPropInt("@eclCRC", eclCRC);
  11053. properties.setPropInt64("@totalCRC", totalCRC);
  11054. }
  11055. properties.setPropInt("@fileCrc", fileCrc);
  11056. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  11057. // Legacy record layout info
  11058. void * layoutMetaBuff;
  11059. size32_t layoutMetaSize;
  11060. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  11061. {
  11062. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  11063. rtlFree(layoutMetaBuff);
  11064. }
  11065. // New record layout info
  11066. setRtlFormat(properties, helper.queryDiskRecordSize());
  11067. // Bloom info
  11068. const IBloomBuilderInfo * const *bloomFilters = helper.queryBloomInfo();
  11069. while (bloomFilters && *bloomFilters)
  11070. {
  11071. const IBloomBuilderInfo *info = *bloomFilters++;
  11072. IPropertyTree *bloom = properties.addPropTree("Bloom");
  11073. bloom->setPropInt64("@bloomFieldMask", info->getBloomFields());
  11074. 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.
  11075. VStringBuffer pval("%f", info->getBloomProbability());
  11076. bloom->setProp("@bloomProbability", pval.str());
  11077. }
  11078. }
  11079. IUserDescriptor *queryUserDescriptor() const
  11080. {
  11081. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  11082. if (workUnit)
  11083. return workUnit->queryUserDescriptor();//ad-hoc mode
  11084. else
  11085. {
  11086. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  11087. if (daliHelper)
  11088. return daliHelper->queryUserDescriptor();//predeployed query mode
  11089. }
  11090. return NULL;
  11091. }
  11092. };
  11093. //=================================================================================
  11094. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  11095. {
  11096. public:
  11097. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11098. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11099. {
  11100. setNumOutputs(0);
  11101. }
  11102. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11103. {
  11104. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  11105. }
  11106. virtual bool isSink() const
  11107. {
  11108. return true;
  11109. }
  11110. virtual const StatisticsMapping &queryStatsMapping() const
  11111. {
  11112. return indexWriteStatistics; // Overridden by anyone that needs more
  11113. }
  11114. };
  11115. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11116. {
  11117. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  11118. }
  11119. //=================================================================================
  11120. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  11121. {
  11122. if((flags & JFmatchAbortLimitSkips) != 0)
  11123. {
  11124. limitFail = false;
  11125. limitOnFail = false;
  11126. }
  11127. else
  11128. {
  11129. limitOnFail = ((flags & JFonfail) != 0);
  11130. limitFail = !limitOnFail;
  11131. }
  11132. }
  11133. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  11134. {
  11135. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  11136. IHThorJoinArg &helper;
  11137. ICompare * collate;
  11138. ICompare * collateupper;
  11139. ThorActivityKind activityKind;
  11140. bool leftOuterJoin;
  11141. bool rightOuterJoin;
  11142. bool exclude;
  11143. bool limitFail;
  11144. bool limitOnFail;
  11145. bool forceSpill;
  11146. unsigned keepLimit;
  11147. unsigned joinLimit;
  11148. unsigned atmostLimit;
  11149. unsigned abortLimit;
  11150. unsigned atmostsTriggered;
  11151. bool betweenjoin;
  11152. OwnedRowArray right;
  11153. const void * left;
  11154. const void * pendingRight;
  11155. unsigned rightIndex;
  11156. unsigned joinCounter;
  11157. BoolArray matchedRight;
  11158. bool matchedLeft;
  11159. Owned<IException> failingLimit;
  11160. ConstPointerArray filteredRight;
  11161. Owned<IRHLimitedCompareHelper> limitedhelper;
  11162. OwnedConstRoxieRow defaultLeft;
  11163. OwnedConstRoxieRow defaultRight;
  11164. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11165. Owned<IEngineRowAllocator> defaultRightAllocator;
  11166. Owned<IGroupedInput> sortedLeft;
  11167. Owned<IGroupedInput> groupedSortedRight;
  11168. bool cloneLeft;
  11169. void createDefaultLeft()
  11170. {
  11171. if (!defaultLeft)
  11172. {
  11173. if (!defaultLeftAllocator)
  11174. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11175. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11176. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11177. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11178. }
  11179. }
  11180. void createDefaultRight()
  11181. {
  11182. if (!defaultRight)
  11183. {
  11184. if (!defaultRightAllocator)
  11185. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11186. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11187. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11188. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11189. }
  11190. }
  11191. public:
  11192. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11193. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11194. {
  11195. // MORE - some of this should be done in factory
  11196. unsigned joinFlags = helper.getJoinFlags();
  11197. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11198. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11199. exclude = (joinFlags & JFexclude) != 0;
  11200. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11201. getLimitType(joinFlags, limitFail, limitOnFail);
  11202. if (joinFlags & JFslidingmatch)
  11203. {
  11204. betweenjoin = true;
  11205. collate = helper.queryCompareLeftRightLower();
  11206. collateupper = helper.queryCompareLeftRightUpper();
  11207. }
  11208. else
  11209. {
  11210. betweenjoin = false;
  11211. collate = collateupper = helper.queryCompareLeftRight();
  11212. }
  11213. rightIndex = 0;
  11214. joinCounter = 0;
  11215. state = JSfill;
  11216. matchedLeft = false;
  11217. joinLimit = 0;
  11218. keepLimit = 0; // wait until ctx available
  11219. atmostLimit = 0; // wait until ctx available
  11220. abortLimit = 0; // wait until ctx available
  11221. atmostsTriggered = 0;
  11222. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11223. left = NULL;
  11224. pendingRight = NULL;
  11225. activityKind = _factory->getKind();
  11226. }
  11227. virtual bool needsAllocator() const { return true; }
  11228. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11229. {
  11230. left = NULL;
  11231. rightIndex = 0;
  11232. joinCounter = 0;
  11233. state = JSfill;
  11234. matchedLeft = false;
  11235. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11236. keepLimit = helper.getKeepLimit();
  11237. if (keepLimit == 0)
  11238. keepLimit = (unsigned)-1;
  11239. atmostsTriggered = 0;
  11240. atmostLimit = helper.getJoinLimit();
  11241. if(atmostLimit == 0)
  11242. atmostLimit = (unsigned)-1;
  11243. else
  11244. assertex(!rightOuterJoin && !betweenjoin);
  11245. abortLimit = helper.getMatchAbortLimit();
  11246. if (abortLimit == 0)
  11247. abortLimit = (unsigned)-1;
  11248. if (rightOuterJoin)
  11249. createDefaultLeft();
  11250. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11251. createDefaultRight();
  11252. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11253. RoxieSortAlgorithm sortAlgorithm;
  11254. if (forceSpill)
  11255. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11256. else
  11257. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11258. if (helper.isLeftAlreadySorted())
  11259. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11260. else
  11261. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11262. ICompare *compareRight = helper.queryCompareRight();
  11263. if (helper.isRightAlreadySorted())
  11264. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11265. else
  11266. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11267. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11268. { //limited match join (s[1..n])
  11269. limitedhelper.setown(createRHLimitedCompareHelper());
  11270. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11271. }
  11272. }
  11273. virtual void reset()
  11274. {
  11275. if (atmostsTriggered)
  11276. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11277. right.clear();
  11278. ReleaseClearRoxieRow(left);
  11279. ReleaseClearRoxieRow(pendingRight);
  11280. defaultRight.clear();
  11281. defaultLeft.clear();
  11282. sortedLeft.clear();
  11283. groupedSortedRight.clear();
  11284. CRoxieServerTwoInputActivity::reset();
  11285. }
  11286. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11287. {
  11288. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11289. {
  11290. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11291. puller->setInput(0, _sourceIdx, _in);
  11292. _in = puller;
  11293. _sourceIdx = 0;
  11294. }
  11295. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11296. }
  11297. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11298. {
  11299. if (idx==(unsigned)-1)
  11300. idx = 0;
  11301. return idx ? NULL : this;
  11302. }
  11303. void fillLeft()
  11304. {
  11305. matchedLeft = false;
  11306. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11307. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11308. fillRight();
  11309. if (limitedhelper && 0==rightIndex)
  11310. {
  11311. rightIndex = 0;
  11312. joinCounter = 0;
  11313. right.clear();
  11314. matchedRight.kill();
  11315. if (left)
  11316. {
  11317. limitedhelper->getGroup(right,left);
  11318. ForEachItemIn(idx, right)
  11319. matchedRight.append(false);
  11320. }
  11321. }
  11322. }
  11323. void fillRight()
  11324. {
  11325. if (limitedhelper)
  11326. return;
  11327. failingLimit.clear();
  11328. if(betweenjoin && left)
  11329. {
  11330. aindex_t start = 0;
  11331. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11332. start++;
  11333. if(start>0)
  11334. right.clearPart(0, start);
  11335. }
  11336. else
  11337. right.clear();
  11338. rightIndex = 0;
  11339. joinCounter = 0;
  11340. unsigned groupCount = 0;
  11341. const void * next;
  11342. while(true)
  11343. {
  11344. if(pendingRight)
  11345. {
  11346. next = pendingRight;
  11347. pendingRight = NULL;
  11348. }
  11349. else
  11350. {
  11351. next = groupedSortedRight->nextRow();
  11352. }
  11353. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11354. {
  11355. while(next)
  11356. {
  11357. ReleaseClearRoxieRow(next);
  11358. next = groupedSortedRight->nextRow();
  11359. }
  11360. continue;
  11361. }
  11362. while(next)
  11363. {
  11364. if(groupCount==abortLimit)
  11365. {
  11366. if(limitFail)
  11367. failLimit();
  11368. if (ctx->queryDebugContext())
  11369. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11370. if(limitOnFail)
  11371. {
  11372. assertex(!failingLimit);
  11373. try
  11374. {
  11375. failLimit();
  11376. }
  11377. catch(IException * except)
  11378. {
  11379. failingLimit.setown(except);
  11380. }
  11381. assertex(failingLimit != NULL);
  11382. }
  11383. right.append(next);
  11384. do
  11385. {
  11386. next = groupedSortedRight->nextRow();
  11387. ReleaseRoxieRow(next);
  11388. } while(next);
  11389. break;
  11390. }
  11391. else if(groupCount==atmostLimit)
  11392. {
  11393. atmostsTriggered++;
  11394. right.clear();
  11395. groupCount = 0;
  11396. while(next)
  11397. {
  11398. ReleaseRoxieRow(next);
  11399. next = groupedSortedRight->nextRow();
  11400. }
  11401. }
  11402. else
  11403. {
  11404. right.append(next);
  11405. groupCount++;
  11406. }
  11407. next = groupedSortedRight->nextRow();
  11408. }
  11409. // 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
  11410. if(betweenjoin && left)
  11411. {
  11412. pendingRight = groupedSortedRight->nextRow();
  11413. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11414. break;
  11415. }
  11416. else
  11417. break;
  11418. }
  11419. matchedRight.kill();
  11420. ForEachItemIn(idx, right)
  11421. matchedRight.append(false);
  11422. }
  11423. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter, unsigned flags)
  11424. {
  11425. if (cloneLeft)
  11426. {
  11427. LinkRoxieRow(curLeft);
  11428. return curLeft;
  11429. }
  11430. try
  11431. {
  11432. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11433. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  11434. if (thisSize)
  11435. return rowBuilder.finalizeRowClear(thisSize);
  11436. else
  11437. return NULL;
  11438. }
  11439. catch (IException *E)
  11440. {
  11441. throw makeWrappedException(E);
  11442. }
  11443. }
  11444. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  11445. {
  11446. try
  11447. {
  11448. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11449. unsigned numRows = rows.ordinality();
  11450. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11451. if (numRows>0)
  11452. flags |= JTFmatchedright;
  11453. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray(), flags);
  11454. if (thisSize)
  11455. return rowBuilder.finalizeRowClear(thisSize);
  11456. else
  11457. return NULL;
  11458. }
  11459. catch (IException *E)
  11460. {
  11461. throw makeWrappedException(E);
  11462. }
  11463. }
  11464. const void * joinException(const void * curLeft, IException * except)
  11465. {
  11466. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11467. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except, JTFmatchedleft);
  11468. return rowBuilder.finalizeRowClear(thisSize);
  11469. }
  11470. void failLimit()
  11471. {
  11472. helper.onMatchAbortLimitExceeded();
  11473. CommonXmlWriter xmlwrite(0);
  11474. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11475. {
  11476. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11477. }
  11478. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11479. }
  11480. virtual const void * nextRow()
  11481. {
  11482. ActivityTimer t(totalCycles, timeActivities);
  11483. for (;;)
  11484. {
  11485. switch (state)
  11486. {
  11487. case JSfill:
  11488. fillLeft();
  11489. state = JSfillright;
  11490. break;
  11491. case JSfillright:
  11492. fillRight();
  11493. state = JScollate;
  11494. break;
  11495. case JSfillleft:
  11496. fillLeft();
  11497. state = JScollate;
  11498. break;
  11499. case JScollate:
  11500. if (right.ordinality() == 0)
  11501. {
  11502. if (left == NULL)
  11503. return NULL;
  11504. state = JSleftonly;
  11505. }
  11506. else
  11507. {
  11508. if (!left)
  11509. state = JSrightonly;
  11510. else
  11511. {
  11512. int diff;
  11513. if(betweenjoin)
  11514. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11515. else
  11516. diff = collate->docompare(left, right.item(0));
  11517. bool limitExceeded = right.ordinality()>abortLimit;
  11518. if (diff == 0)
  11519. {
  11520. if (limitExceeded)
  11521. {
  11522. const void * ret = NULL;
  11523. if(failingLimit)
  11524. ret = joinException(left, failingLimit);
  11525. ReleaseRoxieRow(left);
  11526. left = NULL;
  11527. state = JSfillleft;
  11528. ForEachItemIn(idx, right)
  11529. matchedRight.replace(true, idx);
  11530. if(ret)
  11531. {
  11532. processed++;
  11533. return ret;
  11534. }
  11535. }
  11536. else
  11537. {
  11538. state = JScompare;
  11539. joinLimit = keepLimit;
  11540. }
  11541. }
  11542. else if (diff < 0)
  11543. state = JSleftonly;
  11544. else if (limitExceeded)
  11545. {
  11546. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11547. state = JSfillright;
  11548. }
  11549. else
  11550. state = JSrightonly;
  11551. }
  11552. }
  11553. break;
  11554. case JSrightonly:
  11555. if (rightOuterJoin)
  11556. {
  11557. switch (activityKind)
  11558. {
  11559. case TAKjoin:
  11560. {
  11561. while (right.isItem(rightIndex))
  11562. {
  11563. if (!matchedRight.item(rightIndex))
  11564. {
  11565. const void * rhs = right.item(rightIndex++);
  11566. const void *ret = joinRecords(defaultLeft, rhs, 0, JTFmatchedright);
  11567. if (ret)
  11568. {
  11569. processed++;
  11570. return ret;
  11571. }
  11572. }
  11573. else
  11574. rightIndex++;
  11575. }
  11576. break;
  11577. }
  11578. //Probably excessive to implement the following, but possibly useful
  11579. case TAKdenormalize:
  11580. {
  11581. OwnedConstRoxieRow newLeft;
  11582. newLeft.set(defaultLeft);
  11583. unsigned rowSize = 0;
  11584. unsigned leftCount = 0;
  11585. while (right.isItem(rightIndex))
  11586. {
  11587. if (!matchedRight.item(rightIndex))
  11588. {
  11589. const void * rhs = right.item(rightIndex);
  11590. try
  11591. {
  11592. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11593. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedright);
  11594. if (thisSize)
  11595. {
  11596. rowSize = thisSize;
  11597. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11598. }
  11599. }
  11600. catch (IException *E)
  11601. {
  11602. throw makeWrappedException(E);
  11603. }
  11604. }
  11605. rightIndex++;
  11606. }
  11607. state = JSfillright;
  11608. if (rowSize)
  11609. {
  11610. processed++;
  11611. return newLeft.getClear();
  11612. }
  11613. break;
  11614. }
  11615. case TAKdenormalizegroup:
  11616. {
  11617. filteredRight.kill();
  11618. while (right.isItem(rightIndex))
  11619. {
  11620. if (!matchedRight.item(rightIndex))
  11621. filteredRight.append(right.item(rightIndex));
  11622. rightIndex++;
  11623. }
  11624. state = JSfillright;
  11625. if (filteredRight.ordinality())
  11626. {
  11627. const void * ret = denormalizeRecords(defaultLeft, filteredRight, 0);
  11628. filteredRight.kill();
  11629. if (ret)
  11630. {
  11631. processed++;
  11632. return ret;
  11633. }
  11634. }
  11635. break;
  11636. }
  11637. }
  11638. }
  11639. state = JSfillright;
  11640. break;
  11641. case JSleftonly:
  11642. {
  11643. const void * ret = NULL;
  11644. if (!matchedLeft && leftOuterJoin)
  11645. {
  11646. switch (activityKind)
  11647. {
  11648. case TAKjoin:
  11649. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  11650. break;
  11651. case TAKdenormalize:
  11652. ret = left;
  11653. left = NULL;
  11654. break;
  11655. case TAKdenormalizegroup:
  11656. filteredRight.kill();
  11657. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11658. break;
  11659. }
  11660. }
  11661. ReleaseRoxieRow(left);
  11662. left = NULL;
  11663. state = JSfillleft;
  11664. if (ret)
  11665. {
  11666. processed++;
  11667. return ret;
  11668. }
  11669. break;
  11670. }
  11671. case JScompare:
  11672. if (joinLimit != 0)
  11673. {
  11674. switch (activityKind)
  11675. {
  11676. case TAKjoin:
  11677. {
  11678. while (right.isItem(rightIndex))
  11679. {
  11680. const void * rhs = right.item(rightIndex++);
  11681. if (helper.match(left, rhs))
  11682. {
  11683. matchedRight.replace(true, rightIndex-1);
  11684. matchedLeft = true;
  11685. if (!exclude)
  11686. {
  11687. const void *ret = joinRecords(left, rhs, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  11688. if (ret)
  11689. {
  11690. processed++;
  11691. joinLimit--;
  11692. return ret;
  11693. }
  11694. }
  11695. }
  11696. }
  11697. break;
  11698. }
  11699. case TAKdenormalize:
  11700. {
  11701. OwnedConstRoxieRow newLeft;
  11702. newLeft.set(left);
  11703. unsigned rowSize = 0;
  11704. unsigned leftCount = 0;
  11705. while (right.isItem(rightIndex) && joinLimit)
  11706. {
  11707. try
  11708. {
  11709. const void * rhs = right.item(rightIndex++);
  11710. if (helper.match(left, rhs))
  11711. {
  11712. matchedRight.replace(true, rightIndex-1);
  11713. matchedLeft = true;
  11714. if (!exclude)
  11715. {
  11716. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11717. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedleft|JTFmatchedright);
  11718. if (thisSize)
  11719. {
  11720. rowSize = thisSize;
  11721. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11722. joinLimit--;
  11723. }
  11724. }
  11725. }
  11726. }
  11727. catch (IException *E)
  11728. {
  11729. throw makeWrappedException(E);
  11730. }
  11731. }
  11732. state = JSleftonly;
  11733. rightIndex = 0;
  11734. if (rowSize)
  11735. {
  11736. processed++;
  11737. return newLeft.getClear();
  11738. }
  11739. break;
  11740. }
  11741. case TAKdenormalizegroup:
  11742. {
  11743. filteredRight.kill();
  11744. while (right.isItem(rightIndex))
  11745. {
  11746. const void * rhs = right.item(rightIndex++);
  11747. if (helper.match(left, rhs))
  11748. {
  11749. matchedRight.replace(true, rightIndex-1);
  11750. filteredRight.append(rhs);
  11751. matchedLeft = true;
  11752. if (filteredRight.ordinality()==joinLimit)
  11753. break;
  11754. }
  11755. }
  11756. state = JSleftonly;
  11757. rightIndex = 0;
  11758. if (!exclude && filteredRight.ordinality())
  11759. {
  11760. const void * ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11761. filteredRight.kill();
  11762. if (ret)
  11763. {
  11764. processed++;
  11765. return ret;
  11766. }
  11767. }
  11768. break;
  11769. }
  11770. }
  11771. }
  11772. state = JSleftonly;
  11773. rightIndex = 0;
  11774. joinCounter = 0;
  11775. break;
  11776. }
  11777. }
  11778. }
  11779. };
  11780. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11781. {
  11782. unsigned input2;
  11783. unsigned input2idx;
  11784. bool forceSpill;
  11785. public:
  11786. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11787. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11788. {
  11789. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11790. input2 = 0;
  11791. input2idx = 0;
  11792. }
  11793. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11794. {
  11795. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11796. }
  11797. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11798. {
  11799. if (idx==1)
  11800. {
  11801. input2 = source;
  11802. input2idx = sourceidx;
  11803. }
  11804. else
  11805. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11806. }
  11807. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11808. {
  11809. switch (idx)
  11810. {
  11811. case 1:
  11812. sourceidx = input2idx;
  11813. return input2;
  11814. case 0:
  11815. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11816. default:
  11817. return (unsigned) -1;
  11818. }
  11819. }
  11820. virtual unsigned numInputs() const { return 2; }
  11821. virtual const StatisticsMapping &queryStatsMapping() const
  11822. {
  11823. return joinStatistics;
  11824. }
  11825. };
  11826. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11827. {
  11828. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11829. }
  11830. //=================================================================================
  11831. #define CONCAT_READAHEAD 1000
  11832. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11833. {
  11834. public:
  11835. IMPLEMENT_IINTERFACE;
  11836. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11837. : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
  11838. {
  11839. }
  11840. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11841. {
  11842. space.reinit(CONCAT_READAHEAD);
  11843. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11844. }
  11845. void stop()
  11846. {
  11847. space.interrupt();
  11848. puller.stop();
  11849. }
  11850. IFinalRoxieInput *queryInput() const
  11851. {
  11852. return puller.queryInput();
  11853. }
  11854. void reset()
  11855. {
  11856. puller.reset();
  11857. ForEachItemIn(idx, buffer)
  11858. ReleaseRoxieRow(buffer.item(idx));
  11859. buffer.clear();
  11860. eof = false;
  11861. atEog = true;
  11862. }
  11863. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11864. {
  11865. puller.setInput(this, _sourceIdx, _in);
  11866. }
  11867. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11868. {
  11869. puller.connectInputStreams(ctx, consumerOrdered);
  11870. }
  11871. virtual void processRow(const void *row)
  11872. {
  11873. buffer.enqueue(row);
  11874. ready.signal();
  11875. space.wait();
  11876. }
  11877. virtual void processGroup(const ConstPointerArray &rows)
  11878. {
  11879. // We use record-by-record input mode of the puller thread even in grouped mode.
  11880. throwUnexpected();
  11881. }
  11882. virtual void processEOG()
  11883. {
  11884. if (grouped)
  11885. processRow(NULL);
  11886. }
  11887. virtual void processDone()
  11888. {
  11889. processRow(NULL);
  11890. }
  11891. virtual bool fireException(IException *e)
  11892. {
  11893. // called from puller thread on failure
  11894. ready.interrupt(LINK(e));
  11895. space.interrupt(e);
  11896. return true;
  11897. }
  11898. bool peek(const void * &row, bool &anyActive)
  11899. {
  11900. if (!eof)
  11901. {
  11902. if (buffer.ordinality())
  11903. {
  11904. space.signal();
  11905. row = buffer.dequeue();
  11906. if (row==NULL)
  11907. {
  11908. if (atEog)
  11909. {
  11910. eof = true;
  11911. return false;
  11912. }
  11913. else
  11914. atEog = true;
  11915. }
  11916. else if (grouped)
  11917. atEog = false;
  11918. return true;
  11919. }
  11920. anyActive = true;
  11921. }
  11922. return false;
  11923. }
  11924. protected:
  11925. RecordPullerThread puller;
  11926. InterruptableSemaphore space;
  11927. InterruptableSemaphore &ready;
  11928. SafeQueueOf<const void, true> buffer;
  11929. bool atEog;
  11930. bool eof;
  11931. bool grouped;
  11932. };
  11933. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11934. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11935. {
  11936. InterruptableSemaphore ready;
  11937. ReaderArray pullers;
  11938. unsigned numInputs;
  11939. unsigned nextPuller; // for round robin
  11940. unsigned readyPending;
  11941. bool eof;
  11942. bool inGroup;
  11943. bool grouped;
  11944. public:
  11945. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11946. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11947. {
  11948. numInputs = _numInputs;
  11949. eof = (numInputs==0);
  11950. inGroup = false;
  11951. nextPuller = 0;
  11952. readyPending = 0;
  11953. for (unsigned i = 0; i < numInputs; i++)
  11954. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11955. }
  11956. ~CRoxieServerThreadedConcatActivity()
  11957. {
  11958. ForEachItemIn(idx, pullers)
  11959. delete &pullers.item(idx);
  11960. }
  11961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11962. {
  11963. eof = (numInputs==0);
  11964. inGroup = false;
  11965. nextPuller = 0;
  11966. readyPending = 0;
  11967. ready.reinit();
  11968. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11969. ForEachItemIn(idx, pullers)
  11970. {
  11971. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  11972. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  11973. // in the part of the subgraph that the thread uses has been started.
  11974. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  11975. }
  11976. }
  11977. virtual void stop()
  11978. {
  11979. ready.interrupt();
  11980. ForEachItemIn(idx, pullers)
  11981. pullers.item(idx).stop();
  11982. CRoxieServerActivity::stop();
  11983. }
  11984. virtual unsigned __int64 queryLocalCycles() const
  11985. {
  11986. return 0;
  11987. }
  11988. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  11989. {
  11990. if (pullers.isItem(idx))
  11991. return pullers.item(idx).queryInput();
  11992. else
  11993. return NULL;
  11994. }
  11995. virtual void reset()
  11996. {
  11997. CRoxieServerActivity::reset();
  11998. ForEachItemIn(idx, pullers)
  11999. pullers.item(idx).reset();
  12000. eof = false;
  12001. inGroup = false;
  12002. nextPuller = 0;
  12003. readyPending = 0;
  12004. }
  12005. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12006. {
  12007. if (pullers.isItem(idx))
  12008. pullers.item(idx).setInput(_sourceIdx, _in);
  12009. else
  12010. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12011. }
  12012. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12013. {
  12014. ForEachItemIn(i, pullers)
  12015. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  12016. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  12017. }
  12018. virtual const void * nextRow()
  12019. {
  12020. ActivityTimer t(totalCycles, timeActivities);
  12021. if (eof)
  12022. return NULL;
  12023. for (;;)
  12024. {
  12025. if (readyPending && !inGroup)
  12026. {
  12027. if (readyPending > 1)
  12028. ready.signal(readyPending-1);
  12029. readyPending = 0;
  12030. }
  12031. else
  12032. ready.wait();
  12033. bool anyActive = false;
  12034. ForEachItemIn(unused_index, pullers)
  12035. {
  12036. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  12037. const void *ret;
  12038. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  12039. if (fetched)
  12040. {
  12041. inGroup = (ret != NULL);
  12042. return ret;
  12043. }
  12044. if (inGroup && grouped)
  12045. {
  12046. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  12047. readyPending++;
  12048. anyActive = true;
  12049. break;
  12050. }
  12051. nextPuller++;
  12052. if (nextPuller==pullers.ordinality())
  12053. nextPuller = 0;
  12054. }
  12055. if (!anyActive)
  12056. break;
  12057. // A ready signal without anything being ready means someone reached end-of-file.
  12058. }
  12059. eof = true;
  12060. return NULL;
  12061. }
  12062. };
  12063. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  12064. {
  12065. IEngineRowStream *curStream;
  12066. bool eogSeen;
  12067. bool anyThisGroup;
  12068. bool grouped;
  12069. unsigned streamIdx;
  12070. public:
  12071. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12072. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12073. {
  12074. eogSeen = false;
  12075. anyThisGroup = false;
  12076. grouped = _grouped;
  12077. streamIdx = 0;
  12078. curStream = NULL;
  12079. }
  12080. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12081. {
  12082. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12083. streamIdx = 0;
  12084. curStream = streamArray[streamIdx];
  12085. eogSeen = false;
  12086. anyThisGroup = false;
  12087. }
  12088. virtual const void * nextRow()
  12089. {
  12090. ActivityTimer t(totalCycles, timeActivities);
  12091. if (!curStream)
  12092. return NULL; // eof
  12093. const void * next = curStream->nextRow();
  12094. if (next)
  12095. {
  12096. anyThisGroup = true;
  12097. eogSeen = false;
  12098. processed++;
  12099. return next;
  12100. }
  12101. else if (!eogSeen)
  12102. {
  12103. eogSeen = true;
  12104. if (grouped)
  12105. {
  12106. if (anyThisGroup)
  12107. {
  12108. anyThisGroup = false;
  12109. return NULL;
  12110. }
  12111. else
  12112. return nextRow();
  12113. }
  12114. else
  12115. return nextRow();
  12116. }
  12117. else if (streamIdx < numStreams-1)
  12118. {
  12119. streamIdx++;
  12120. curStream = streamArray[streamIdx];
  12121. eogSeen = false;
  12122. return nextRow();
  12123. }
  12124. else
  12125. {
  12126. curStream = NULL;
  12127. return NULL;
  12128. }
  12129. }
  12130. };
  12131. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  12132. {
  12133. bool ordered;
  12134. bool grouped;
  12135. public:
  12136. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12137. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12138. {
  12139. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  12140. ordered = helper->isOrdered();
  12141. grouped = helper->queryOutputMeta()->isGrouped();
  12142. }
  12143. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12144. {
  12145. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  12146. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12147. else
  12148. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12149. }
  12150. };
  12151. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12152. {
  12153. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12154. }
  12155. //=================================================================================
  12156. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12157. {
  12158. IEngineRowStream* selectedStream;
  12159. unsigned savedParentExtractSize;
  12160. const byte * savedParentExtract;
  12161. bool foundInput;
  12162. bool unusedStopped;
  12163. public:
  12164. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12165. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12166. {
  12167. foundInput = false;
  12168. unusedStopped = false;
  12169. selectedStream = NULL;
  12170. savedParentExtractSize = 0;;
  12171. savedParentExtract = NULL;
  12172. }
  12173. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12174. {
  12175. //Don't start the inputs yet so we can short-circuit...
  12176. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12177. savedParentExtractSize = parentExtractSize;
  12178. savedParentExtract = parentExtract;
  12179. }
  12180. virtual void stop()
  12181. {
  12182. if (unusedStopped)
  12183. {
  12184. if (selectedStream)
  12185. selectedStream->stop();
  12186. }
  12187. else
  12188. {
  12189. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12190. for (unsigned i = 0; i < numStreams; i++)
  12191. streamArray[i]->stop();
  12192. }
  12193. CRoxieServerMultiInputBaseActivity::stop();
  12194. }
  12195. virtual void reset()
  12196. {
  12197. CRoxieServerMultiInputBaseActivity::reset();
  12198. foundInput = false;
  12199. unusedStopped = false;
  12200. selectedStream = NULL;
  12201. }
  12202. virtual unsigned __int64 queryLocalCycles() const
  12203. {
  12204. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12205. }
  12206. virtual const void * nextRow()
  12207. {
  12208. ActivityTimer t(totalCycles, timeActivities);
  12209. if (!foundInput)
  12210. {
  12211. foundInput = true;
  12212. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12213. //If we get an exception in this loop then stop() will stop any started inputs
  12214. for (unsigned i=0; i < numStreams; i++)
  12215. {
  12216. selectedStream = streamArray[i];
  12217. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12218. startJunction(junctionArray[i]);
  12219. const void * next = selectedStream->nextRow();
  12220. if (next)
  12221. {
  12222. //Found a row so stop remaining
  12223. for (unsigned j=i+1; j < numInputs; j++)
  12224. streamArray[j]->stop();
  12225. unusedStopped = true;
  12226. processed++;
  12227. return next;
  12228. }
  12229. selectedStream->stop();
  12230. }
  12231. unusedStopped = true;
  12232. selectedStream = NULL;
  12233. return NULL;
  12234. }
  12235. if (!selectedStream)
  12236. return NULL;
  12237. const void * next = selectedStream->nextRow();
  12238. if (next)
  12239. processed++;
  12240. return next;
  12241. }
  12242. };
  12243. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12244. {
  12245. public:
  12246. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12247. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12248. {
  12249. }
  12250. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12251. {
  12252. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12253. }
  12254. };
  12255. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12256. {
  12257. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12258. }
  12259. //=================================================================================
  12260. class SingleNodeActivityContext : public IThorActivityContext
  12261. {
  12262. public:
  12263. SingleNodeActivityContext(unsigned _numStrands, unsigned _curStrand) : strands(_numStrands), curStrand(_curStrand) { assertex(curStrand < strands); }
  12264. virtual bool isLocal() const override { return false; }
  12265. virtual unsigned numSlaves() const override { return 1; }
  12266. virtual unsigned numStrands() const override { return strands; }
  12267. virtual unsigned querySlave() const override { return 0; }
  12268. virtual unsigned queryStrand() const override { return curStrand; }
  12269. protected:
  12270. unsigned strands;
  12271. unsigned curStrand;
  12272. };
  12273. class CRoxieServerExternalActivity : public CRoxieServerMultiInputActivity
  12274. {
  12275. Owned<IRowStream> rows;
  12276. SingleNodeActivityContext activityContext;
  12277. public:
  12278. CRoxieServerExternalActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12279. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), activityContext(1, 0)
  12280. {
  12281. }
  12282. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  12283. {
  12284. Owned<IStrandJunction> junction = CRoxieServerMultiInputActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12285. associateInputsWithHelper();
  12286. return junction.getClear();
  12287. }
  12288. virtual void connectInputStreams(bool consumerOrdered)
  12289. {
  12290. CRoxieServerMultiInputActivity::connectInputStreams(consumerOrdered);
  12291. associateInputsWithHelper();
  12292. }
  12293. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12294. {
  12295. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12296. if (factory->getKind() != TAKexternalsink)
  12297. {
  12298. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12299. rows.setown(helper.createOutput(&activityContext));
  12300. }
  12301. }
  12302. virtual void stop()
  12303. {
  12304. if (rows)
  12305. {
  12306. rows->stop();
  12307. rows.clear();
  12308. }
  12309. CRoxieServerMultiInputBaseActivity::stop();
  12310. }
  12311. virtual void reset()
  12312. {
  12313. rows.clear();
  12314. }
  12315. virtual const void * nextRow()
  12316. {
  12317. ActivityTimer t(totalCycles, timeActivities);
  12318. assertex(rows);
  12319. const void * next = rows->nextRow();
  12320. if (next)
  12321. processed++;
  12322. return next;
  12323. }
  12324. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  12325. {
  12326. try
  12327. {
  12328. start(parentExtractSize, parentExtract, false);
  12329. assertex(!rows);
  12330. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12331. helper.execute(&activityContext);
  12332. stop();
  12333. }
  12334. catch (IException * E)
  12335. {
  12336. ctx->notifyAbort(E);
  12337. abort();
  12338. throw;
  12339. }
  12340. }
  12341. protected:
  12342. void associateInputsWithHelper()
  12343. {
  12344. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12345. for (unsigned i = 0; i < numInputs; i++)
  12346. helper.setInput(i, streamArray[i]);
  12347. }
  12348. };
  12349. class CRoxieServerExternalActivityFactory : public CRoxieServerMultiInputFactory
  12350. {
  12351. bool isRoot;
  12352. public:
  12353. CRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12354. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  12355. {
  12356. }
  12357. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12358. {
  12359. return new CRoxieServerExternalActivity(_ctx, this, _probeManager, numInputs());
  12360. }
  12361. virtual bool isSink() const
  12362. {
  12363. return (kind == TAKexternalsink) && isRoot;
  12364. }
  12365. };
  12366. IRoxieServerActivityFactory *createRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12367. {
  12368. return new CRoxieServerExternalActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  12369. }
  12370. //=================================================================================
  12371. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12372. {
  12373. IHThorMergeArg &helper;
  12374. unsigned *mergeheap;
  12375. unsigned activeInputs;
  12376. const void **pending;
  12377. bool first;
  12378. ICompare *compare;
  12379. bool dedup;
  12380. void permute()
  12381. {
  12382. assertex(activeInputs == 0);
  12383. for(unsigned i = 0; i < numStreams; i++)
  12384. if(pullInput(i))
  12385. mergeheap[activeInputs++] = i;
  12386. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12387. // the heap property: no element should be smaller than its parent
  12388. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12389. // 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
  12390. if (activeInputs >= 2)
  12391. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12392. siftDown(p);
  12393. if(dedup)
  12394. siftDownDedupTop();
  12395. else
  12396. siftDown(0);
  12397. }
  12398. void readNext()
  12399. {
  12400. if(!pullInput(mergeheap[0]))
  12401. if(!promote(0))
  12402. return;
  12403. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12404. if(dedup)
  12405. siftDownDedupTop();
  12406. else
  12407. siftDown(0);
  12408. }
  12409. bool pullInput(unsigned i)
  12410. {
  12411. const void *next = streamArray[i]->ungroupedNextRow();
  12412. pending[i] = next;
  12413. return (next != NULL);
  12414. }
  12415. bool promote(unsigned p)
  12416. {
  12417. activeInputs--;
  12418. if(activeInputs == p)
  12419. return false;
  12420. mergeheap[p] = mergeheap[activeInputs];
  12421. return true;
  12422. }
  12423. bool siftDown(unsigned p)
  12424. {
  12425. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12426. bool nochange = true;
  12427. while(1)
  12428. {
  12429. unsigned c = p*2 + 1;
  12430. if(c >= activeInputs)
  12431. return nochange;
  12432. if(c+1 < activeInputs)
  12433. {
  12434. int childcmp = BuffCompare(c+1, c);
  12435. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12436. ++c;
  12437. }
  12438. int cmp = BuffCompare(c, p);
  12439. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12440. return nochange;
  12441. nochange = false;
  12442. unsigned r = mergeheap[c];
  12443. mergeheap[c] = mergeheap[p];
  12444. mergeheap[p] = r;
  12445. p = c;
  12446. }
  12447. }
  12448. void siftDownDedupTop()
  12449. {
  12450. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12451. if(activeInputs < 2)
  12452. return;
  12453. unsigned c = 1;
  12454. int childcmp = 1;
  12455. if(activeInputs >= 3)
  12456. {
  12457. childcmp = BuffCompare(2, 1);
  12458. if(childcmp < 0)
  12459. c = 2;
  12460. }
  12461. int cmp = BuffCompare(c, 0);
  12462. if(cmp > 0)
  12463. return;
  12464. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12465. while(cmp <= 0)
  12466. {
  12467. if(cmp == 0)
  12468. {
  12469. if(mergeheap[c] < mergeheap[0])
  12470. {
  12471. unsigned r = mergeheap[c];
  12472. mergeheap[c] = mergeheap[0];
  12473. mergeheap[0] = r;
  12474. }
  12475. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12476. if(!pullInput(mergeheap[c]))
  12477. if(!promote(c))
  12478. break;
  12479. siftDown(c);
  12480. }
  12481. else
  12482. {
  12483. unsigned r = mergeheap[c];
  12484. mergeheap[c] = mergeheap[0];
  12485. mergeheap[0] = r;
  12486. if(siftDown(c))
  12487. break;
  12488. }
  12489. cmp = BuffCompare(c, 0);
  12490. }
  12491. // the following loop ensures the uniqueness property holds on the other branch too
  12492. c = 3-c;
  12493. if(activeInputs <= c)
  12494. return;
  12495. while(childcmp == 0)
  12496. {
  12497. if(mergeheap[c] < mergeheap[0])
  12498. {
  12499. unsigned r = mergeheap[c];
  12500. mergeheap[c] = mergeheap[0];
  12501. mergeheap[0] = r;
  12502. }
  12503. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12504. if(!pullInput(mergeheap[c]))
  12505. if(!promote(c))
  12506. break;
  12507. siftDown(c);
  12508. childcmp = BuffCompare(c, 0);
  12509. }
  12510. }
  12511. inline int BuffCompare(unsigned a, unsigned b)
  12512. {
  12513. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12514. }
  12515. public:
  12516. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12517. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12518. {
  12519. activeInputs = 0;
  12520. first = true;
  12521. mergeheap = new unsigned[numInputs];
  12522. pending = new const void *[numStreams];
  12523. compare = helper.queryCompare();
  12524. dedup = helper.dedup();
  12525. for (unsigned i = 0; i < numStreams; i++)
  12526. pending[i] = NULL;
  12527. }
  12528. ~CRoxieServerMergeActivity()
  12529. {
  12530. delete [] mergeheap;
  12531. delete [] pending;
  12532. }
  12533. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12534. {
  12535. activeInputs = 0;
  12536. first = true;
  12537. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12538. }
  12539. virtual void reset()
  12540. {
  12541. for (unsigned i = 0; i < numStreams; i++)
  12542. ReleaseClearRoxieRow(pending[i]);
  12543. CRoxieServerMultiInputActivity::reset();
  12544. }
  12545. virtual const void * nextRow()
  12546. {
  12547. ActivityTimer t(totalCycles, timeActivities);
  12548. if (first)
  12549. {
  12550. permute();
  12551. first = false;
  12552. }
  12553. if (activeInputs)
  12554. {
  12555. const void *next = pending[mergeheap[0]];
  12556. readNext();
  12557. if (next)
  12558. processed++;
  12559. return next;
  12560. }
  12561. else
  12562. return NULL;
  12563. }
  12564. };
  12565. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12566. {
  12567. public:
  12568. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12569. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12570. {
  12571. }
  12572. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12573. {
  12574. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12575. }
  12576. };
  12577. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12578. {
  12579. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12580. }
  12581. //=================================================================================
  12582. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12583. {
  12584. IHThorRegroupArg &helper;
  12585. unsigned streamIndex;
  12586. bool eof;
  12587. unsigned __int64 numProcessedLastGroup;
  12588. public:
  12589. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12590. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  12591. {
  12592. streamIndex = 0;
  12593. eof = false;
  12594. numProcessedLastGroup = 0;
  12595. }
  12596. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12597. {
  12598. streamIndex = 0;
  12599. eof = false;
  12600. numProcessedLastGroup = processed;
  12601. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12602. }
  12603. const void * nextFromInputs()
  12604. {
  12605. unsigned initialStream = streamIndex;
  12606. while (streamIndex < numStreams)
  12607. {
  12608. const void * next = streamArray[streamIndex]->nextRow();
  12609. if (next)
  12610. {
  12611. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12612. {
  12613. ReleaseRoxieRow(next);
  12614. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12615. }
  12616. return next;
  12617. }
  12618. streamIndex++;
  12619. }
  12620. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12621. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12622. streamIndex = 0;
  12623. return NULL;
  12624. }
  12625. virtual const void * nextRow()
  12626. {
  12627. ActivityTimer t(totalCycles, timeActivities);
  12628. if (eof)
  12629. return NULL;
  12630. const void * ret = nextFromInputs();
  12631. if (ret)
  12632. {
  12633. processed++;
  12634. return ret;
  12635. }
  12636. if (numProcessedLastGroup != processed)
  12637. {
  12638. numProcessedLastGroup = processed;
  12639. return NULL;
  12640. }
  12641. eof = true;
  12642. return NULL;
  12643. }
  12644. };
  12645. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12646. {
  12647. public:
  12648. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12649. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12650. {
  12651. }
  12652. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12653. {
  12654. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12655. }
  12656. };
  12657. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12658. {
  12659. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12660. }
  12661. //=================================================================================
  12662. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12663. {
  12664. IHThorCombineArg &helper;
  12665. unsigned __int64 numProcessedLastGroup;
  12666. public:
  12667. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12668. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12669. {
  12670. numProcessedLastGroup = 0;
  12671. }
  12672. ~CRoxieServerCombineActivity()
  12673. {
  12674. }
  12675. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12676. {
  12677. numProcessedLastGroup = processed;
  12678. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12679. }
  12680. void nextInputs(ConstPointerArray & out)
  12681. {
  12682. for (unsigned i=0; i < numStreams; i++)
  12683. {
  12684. const void * next = streamArray[i]->nextRow();
  12685. if (next)
  12686. out.append(next);
  12687. }
  12688. }
  12689. virtual bool needsAllocator() const { return true; }
  12690. virtual const void * nextRow()
  12691. {
  12692. ActivityTimer t(totalCycles, timeActivities);
  12693. for (;;)
  12694. {
  12695. ConstPointerArray group;
  12696. nextInputs(group);
  12697. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12698. nextInputs(group);
  12699. if (group.ordinality() == 0)
  12700. {
  12701. numProcessedLastGroup = processed;
  12702. return NULL;
  12703. }
  12704. else if (group.ordinality() != numInputs)
  12705. {
  12706. ReleaseRoxieRows(group);
  12707. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12708. }
  12709. try
  12710. {
  12711. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12712. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12713. ReleaseRoxieRows(group);
  12714. if (outSize)
  12715. {
  12716. processed++;
  12717. return rowBuilder.finalizeRowClear(outSize);
  12718. }
  12719. }
  12720. catch (IException *E)
  12721. {
  12722. ReleaseRoxieRows(group);
  12723. throw makeWrappedException(E);
  12724. }
  12725. }
  12726. }
  12727. };
  12728. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12729. {
  12730. public:
  12731. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12732. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12733. {
  12734. }
  12735. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12736. {
  12737. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12738. }
  12739. };
  12740. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12741. {
  12742. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12743. }
  12744. //=================================================================================
  12745. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12746. {
  12747. IHThorCombineGroupArg &helper;
  12748. unsigned __int64 numProcessedLastGroup;
  12749. public:
  12750. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12751. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12752. {
  12753. numProcessedLastGroup = 0;
  12754. }
  12755. ~CRoxieServerCombineGroupActivity()
  12756. {
  12757. }
  12758. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12759. {
  12760. numProcessedLastGroup = processed;
  12761. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12762. }
  12763. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12764. {
  12765. if (idx==(unsigned)-1)
  12766. idx = 0;
  12767. return idx ? NULL : this;
  12768. }
  12769. virtual bool needsAllocator() const { return true; }
  12770. virtual const void * nextRow()
  12771. {
  12772. ActivityTimer t(totalCycles, timeActivities);
  12773. for (;;)
  12774. {
  12775. const void * left = inputStream->nextRow();
  12776. if (!left && (numProcessedLastGroup == processed))
  12777. left = inputStream->nextRow();
  12778. if (!left)
  12779. {
  12780. if (numProcessedLastGroup == processed)
  12781. {
  12782. const void * nextRight = inputStream1->nextRow();
  12783. if (nextRight)
  12784. {
  12785. ReleaseRoxieRow(nextRight);
  12786. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12787. }
  12788. }
  12789. else
  12790. numProcessedLastGroup = processed;
  12791. return NULL;
  12792. }
  12793. ConstPointerArray group;
  12794. for (;;)
  12795. {
  12796. const void * in = inputStream1->nextRow();
  12797. if (!in)
  12798. break;
  12799. group.append(in);
  12800. }
  12801. if (group.ordinality() == 0)
  12802. {
  12803. ReleaseRoxieRow(left);
  12804. ReleaseRoxieRows(group);
  12805. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12806. }
  12807. try
  12808. {
  12809. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12810. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12811. ReleaseRoxieRow(left);
  12812. ReleaseRoxieRows(group);
  12813. if (outSize)
  12814. {
  12815. processed++;
  12816. return rowBuilder.finalizeRowClear(outSize);
  12817. }
  12818. }
  12819. catch (IException *E)
  12820. {
  12821. ReleaseRoxieRow(left);
  12822. ReleaseRoxieRows(group);
  12823. throw makeWrappedException(E);
  12824. }
  12825. }
  12826. }
  12827. };
  12828. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12829. {
  12830. unsigned input2;
  12831. unsigned input2idx;
  12832. public:
  12833. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12834. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12835. {
  12836. input2 = 0;
  12837. input2idx = 0;
  12838. }
  12839. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12840. {
  12841. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12842. }
  12843. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12844. {
  12845. if (idx==1)
  12846. {
  12847. input2 = source;
  12848. input2idx = sourceidx;
  12849. }
  12850. else
  12851. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12852. }
  12853. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12854. {
  12855. switch (idx)
  12856. {
  12857. case 1:
  12858. sourceidx = input2idx;
  12859. return input2;
  12860. case 0:
  12861. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12862. default:
  12863. return (unsigned) -1;
  12864. }
  12865. }
  12866. virtual unsigned numInputs() const { return 2; }
  12867. };
  12868. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12869. {
  12870. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12871. }
  12872. //=================================================================================
  12873. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12874. {
  12875. IHThorRollupGroupArg &helper;
  12876. bool eof;
  12877. public:
  12878. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12879. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12880. helper((IHThorRollupGroupArg &)basehelper)
  12881. {
  12882. eof = false;
  12883. }
  12884. ~CRoxieServerRollupGroupActivity()
  12885. {
  12886. }
  12887. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12888. {
  12889. eof = false;
  12890. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12891. }
  12892. virtual bool needsAllocator() const { return true; }
  12893. virtual const void * nextRow()
  12894. {
  12895. ActivityTimer t(totalCycles, timeActivities);
  12896. if (eof)
  12897. return NULL;
  12898. for (;;)
  12899. {
  12900. ConstPointerArray group;
  12901. for (;;)
  12902. {
  12903. const void * in = inputStream->nextRow();
  12904. if (!in)
  12905. break;
  12906. group.append(in);
  12907. }
  12908. if (group.ordinality() == 0)
  12909. {
  12910. eof = true;
  12911. return NULL;
  12912. }
  12913. try
  12914. {
  12915. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12916. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12917. ReleaseRoxieRows(group);
  12918. if (outSize)
  12919. {
  12920. processed++;
  12921. return rowBuilder.finalizeRowClear(outSize);
  12922. }
  12923. }
  12924. catch (IException * E)
  12925. {
  12926. ReleaseRoxieRows(group);
  12927. throw makeWrappedException(E);
  12928. }
  12929. }
  12930. }
  12931. };
  12932. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12933. {
  12934. public:
  12935. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12936. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12937. {
  12938. }
  12939. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12940. {
  12941. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12942. }
  12943. };
  12944. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12945. {
  12946. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12947. }
  12948. //=================================================================================
  12949. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12950. {
  12951. IHThorFilterProjectArg &helper;
  12952. unsigned numProcessedLastGroup;
  12953. unsigned __int64 recordCount;
  12954. public:
  12955. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12956. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12957. {
  12958. numProcessedLastGroup = 0;
  12959. recordCount = 0;
  12960. }
  12961. ~CRoxieServerFilterProjectActivity()
  12962. {
  12963. }
  12964. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12965. {
  12966. numProcessedLastGroup = 0;
  12967. recordCount = 0;
  12968. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  12969. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  12970. }
  12971. virtual bool needsAllocator() const { return true; }
  12972. virtual const void * nextRow()
  12973. {
  12974. ActivityTimer t(totalCycles, timeActivities);
  12975. if (eof)
  12976. return NULL;
  12977. for (;;)
  12978. {
  12979. const void * in = inputStream->nextRow();
  12980. if (!in)
  12981. {
  12982. recordCount = 0;
  12983. if (numProcessedLastGroup == processed)
  12984. in = inputStream->nextRow();
  12985. if (!in)
  12986. {
  12987. numProcessedLastGroup = processed;
  12988. return NULL;
  12989. }
  12990. }
  12991. try
  12992. {
  12993. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12994. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  12995. ReleaseRoxieRow(in);
  12996. if (outSize)
  12997. {
  12998. processed++;
  12999. return rowBuilder.finalizeRowClear(outSize);
  13000. }
  13001. }
  13002. catch (IException *E)
  13003. {
  13004. throw makeWrappedException(E);
  13005. }
  13006. }
  13007. }
  13008. };
  13009. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  13010. {
  13011. public:
  13012. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13013. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13014. {
  13015. //MORE: Code generator needs to indicate if the count is used.
  13016. //optStableInput = false;
  13017. }
  13018. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13019. {
  13020. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  13021. }
  13022. };
  13023. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13024. {
  13025. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13026. }
  13027. //=====================================================
  13028. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  13029. {
  13030. class ProjectProcessor : public StrandProcessor
  13031. {
  13032. protected:
  13033. IHThorProjectArg &helper;
  13034. public:
  13035. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  13036. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  13037. {
  13038. }
  13039. virtual const void * nextRow()
  13040. {
  13041. ActivityTimer t(totalCycles, timeActivities);
  13042. for (;;)
  13043. {
  13044. OwnedConstRoxieRow in = inputStream->nextRow();
  13045. if (!in)
  13046. {
  13047. if (numProcessedLastGroup == processed)
  13048. in.setown(inputStream->nextRow());
  13049. if (!in)
  13050. {
  13051. numProcessedLastGroup = processed;
  13052. return NULL;
  13053. }
  13054. }
  13055. try
  13056. {
  13057. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13058. size32_t outSize;
  13059. outSize = helper.transform(rowBuilder, in);
  13060. if (outSize)
  13061. {
  13062. processed++;
  13063. return rowBuilder.finalizeRowClear(outSize);
  13064. }
  13065. }
  13066. catch (IException *E)
  13067. {
  13068. throw parent.makeWrappedException(E);
  13069. }
  13070. }
  13071. }
  13072. };
  13073. public:
  13074. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  13075. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  13076. {
  13077. }
  13078. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13079. {
  13080. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  13081. onStartStrands();
  13082. }
  13083. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  13084. {
  13085. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  13086. }
  13087. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  13088. };
  13089. class CRoxieServerProjectActivity : public CRoxieServerActivity
  13090. {
  13091. unsigned numProcessedLastGroup;
  13092. unsigned __int64 recordCount;
  13093. bool count;
  13094. public:
  13095. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13096. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13097. count(_count)
  13098. {
  13099. numProcessedLastGroup = 0;
  13100. recordCount = 0;
  13101. }
  13102. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13103. {
  13104. numProcessedLastGroup = 0;
  13105. recordCount = 0;
  13106. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13107. }
  13108. virtual bool needsAllocator() const { return true; }
  13109. virtual const void * nextRow()
  13110. {
  13111. ActivityTimer t(totalCycles, timeActivities);
  13112. for (;;)
  13113. {
  13114. OwnedConstRoxieRow in = inputStream->nextRow();
  13115. if (!in)
  13116. {
  13117. recordCount = 0;
  13118. if (numProcessedLastGroup == processed)
  13119. in.setown(inputStream->nextRow());
  13120. if (!in)
  13121. {
  13122. numProcessedLastGroup = processed;
  13123. return NULL;
  13124. }
  13125. }
  13126. try
  13127. {
  13128. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13129. size32_t outSize;
  13130. if (count)
  13131. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  13132. else
  13133. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  13134. if (outSize)
  13135. {
  13136. processed++;
  13137. return rowBuilder.finalizeRowClear(outSize);
  13138. }
  13139. }
  13140. catch (IException *E)
  13141. {
  13142. throw makeWrappedException(E);
  13143. }
  13144. }
  13145. }
  13146. };
  13147. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  13148. {
  13149. protected:
  13150. StrandOptions strandOptions;
  13151. bool count;
  13152. public:
  13153. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13154. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  13155. {
  13156. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  13157. optStableInput = count;
  13158. }
  13159. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13160. {
  13161. // 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.
  13162. if (kind == TAKproject) // Not supported on prefetch or count projects
  13163. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  13164. else
  13165. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  13166. }
  13167. };
  13168. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13169. {
  13170. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13171. }
  13172. //=================================================================================
  13173. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  13174. {
  13175. unsigned numProcessedLastGroup;
  13176. bool count;
  13177. bool eof;
  13178. bool allPulled;
  13179. bool isThreaded;
  13180. unsigned preload;
  13181. unsigned __int64 recordCount;
  13182. IHThorPrefetchProjectArg &helper;
  13183. RecordPullerThread puller;
  13184. InterruptableSemaphore ready;
  13185. InterruptableSemaphore space;
  13186. class PrefetchInfo : public CInterface
  13187. {
  13188. public:
  13189. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  13190. {
  13191. if (helper.preTransform(extract, _in, _recordCount))
  13192. {
  13193. in.setown(_in);
  13194. recordCount = _recordCount;
  13195. }
  13196. else
  13197. {
  13198. ReleaseRoxieRow(_in);
  13199. recordCount = 0;
  13200. }
  13201. }
  13202. OwnedConstRoxieRow in;
  13203. unsigned __int64 recordCount;
  13204. rtlRowBuilder extract;
  13205. };
  13206. QueueOf<PrefetchInfo, true> pulled;
  13207. CriticalSection pulledCrit;
  13208. public:
  13209. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13210. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13211. helper((IHThorPrefetchProjectArg &) basehelper),
  13212. puller(false),
  13213. count(_count)
  13214. {
  13215. numProcessedLastGroup = 0;
  13216. recordCount = 0;
  13217. eof = false;
  13218. allPulled = false;
  13219. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  13220. preload = 0;
  13221. }
  13222. ~CRoxieServerPrefetchProjectActivity()
  13223. {
  13224. while (pulled.ordinality())
  13225. ::Release(pulled.dequeue());
  13226. }
  13227. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13228. {
  13229. if (idx)
  13230. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13231. puller.setInput(this, _sourceIdx, _in);
  13232. }
  13233. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13234. {
  13235. puller.connectInputStreams(ctx, consumerOrdered);
  13236. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  13237. }
  13238. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13239. {
  13240. if (idx==0)
  13241. return puller.queryInput();
  13242. else
  13243. return NULL;
  13244. }
  13245. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13246. {
  13247. numProcessedLastGroup = 0;
  13248. recordCount = 0;
  13249. eof = false;
  13250. allPulled = false;
  13251. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13252. preload = helper.getLookahead();
  13253. if (!preload)
  13254. preload = ctx->queryOptions().prefetchProjectPreload;
  13255. space.reinit(preload);
  13256. ready.reinit();
  13257. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  13258. }
  13259. virtual void stop()
  13260. {
  13261. space.interrupt();
  13262. ready.interrupt();
  13263. CRoxieServerActivity::stop();
  13264. puller.stop();
  13265. }
  13266. virtual void reset()
  13267. {
  13268. CRoxieServerActivity::reset();
  13269. puller.reset();
  13270. allPulled = false;
  13271. while (pulled.ordinality())
  13272. ::Release(pulled.dequeue());
  13273. }
  13274. virtual PrefetchInfo *readNextRecord()
  13275. {
  13276. if (!isThreaded)
  13277. {
  13278. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13279. puller.pullRecords(1);
  13280. }
  13281. else
  13282. ready.wait();
  13283. CriticalBlock b(pulledCrit);
  13284. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13285. space.signal();
  13286. return ret;
  13287. }
  13288. virtual bool needsAllocator() const { return true; }
  13289. virtual const void * nextRow()
  13290. {
  13291. ActivityTimer t(totalCycles, timeActivities);
  13292. if (eof)
  13293. return NULL;
  13294. for (;;)
  13295. {
  13296. Owned<PrefetchInfo> in = readNextRecord();
  13297. if (!in)
  13298. {
  13299. recordCount = 0;
  13300. if (numProcessedLastGroup == processed)
  13301. in.setown(readNextRecord());
  13302. if (!in)
  13303. {
  13304. numProcessedLastGroup = processed;
  13305. eof = true;
  13306. return NULL;
  13307. }
  13308. }
  13309. try
  13310. {
  13311. if (in->in)
  13312. {
  13313. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13314. size32_t outSize;
  13315. IThorChildGraph *child = helper.queryChild();
  13316. Owned<IEclGraphResults> results;
  13317. if (child)
  13318. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13319. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13320. if (outSize)
  13321. {
  13322. processed++;
  13323. return rowBuilder.finalizeRowClear(outSize);
  13324. }
  13325. }
  13326. }
  13327. catch (IException *E)
  13328. {
  13329. throw makeWrappedException(E);
  13330. }
  13331. }
  13332. }
  13333. // interface IExceptionHandler
  13334. virtual bool fireException(IException *e)
  13335. {
  13336. // called from puller thread on failure
  13337. ready.interrupt(LINK(e));
  13338. space.interrupt(e);
  13339. return true;
  13340. }
  13341. // interface IRecordPullerCallback
  13342. virtual void processRow(const void *row)
  13343. {
  13344. {
  13345. CriticalBlock b(pulledCrit);
  13346. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13347. }
  13348. if (isThreaded)
  13349. {
  13350. ready.signal();
  13351. space.wait();
  13352. }
  13353. }
  13354. virtual void processEOG()
  13355. {
  13356. {
  13357. CriticalBlock b(pulledCrit);
  13358. pulled.enqueue(NULL);
  13359. }
  13360. if (isThreaded)
  13361. {
  13362. ready.signal();
  13363. space.wait();
  13364. }
  13365. }
  13366. virtual void processGroup(const ConstPointerArray &rows)
  13367. {
  13368. throwUnexpected();
  13369. }
  13370. virtual void processDone()
  13371. {
  13372. CriticalBlock b(pulledCrit);
  13373. allPulled = true;
  13374. if (isThreaded)
  13375. ready.signal();
  13376. }
  13377. };
  13378. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13379. {
  13380. public:
  13381. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13382. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13383. {
  13384. }
  13385. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13386. {
  13387. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
  13388. }
  13389. };
  13390. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13391. {
  13392. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13393. }
  13394. //=================================================================================
  13395. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13396. {
  13397. public:
  13398. CPointerArrayRoxieInput()
  13399. {
  13400. rowset = NULL;
  13401. rowcount = 0;
  13402. curRow = 0;
  13403. }
  13404. void init(size32_t _rowcount, const byte **_rowset)
  13405. {
  13406. rowset = _rowset;
  13407. rowcount = _rowcount;
  13408. curRow = 0;
  13409. }
  13410. virtual const void * nextRow()
  13411. {
  13412. if (curRow < rowcount)
  13413. {
  13414. const void * ret = rowset[curRow];
  13415. if (ret)
  13416. LinkRoxieRow(ret);
  13417. curRow++;
  13418. return ret;
  13419. }
  13420. return NULL;
  13421. }
  13422. protected:
  13423. const byte **rowset;
  13424. size32_t rowcount;
  13425. size32_t curRow;
  13426. };
  13427. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13428. {
  13429. protected:
  13430. IHThorLoopArg &helper;
  13431. ThorActivityKind activityKind;
  13432. unsigned maxIterations;
  13433. bool finishedLooping;
  13434. unsigned flags;
  13435. bool eof;
  13436. rtlRowBuilder loopExtractBuilder;
  13437. unsigned loopGraphId;
  13438. Linked<IOutputMetaData> counterMeta;
  13439. public:
  13440. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13441. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13442. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13443. {
  13444. eof = false;
  13445. finishedLooping = false;
  13446. activityKind = factory->getKind();
  13447. flags = helper.getFlags();
  13448. maxIterations = 0;
  13449. }
  13450. virtual bool needsAllocator() const { return true; }
  13451. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13452. {
  13453. eof = false;
  13454. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13455. int iterations = (int) helper.numIterations();
  13456. maxIterations = (iterations >= 0) ? iterations : 0;
  13457. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13458. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13459. finishedLooping = true;
  13460. loopExtractBuilder.clear();
  13461. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13462. }
  13463. virtual void stop()
  13464. {
  13465. CRoxieServerActivity::stop();
  13466. loopExtractBuilder.clear();
  13467. }
  13468. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13469. {
  13470. if (flags & IHThorLoopArg::LFcounter)
  13471. {
  13472. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13473. *((thor_loop_counter_t *)counterRow) = counter;
  13474. RtlLinkedDatasetBuilder builder(rowAllocator);
  13475. builder.appendOwn(counterRow);
  13476. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13477. graph->setInputResult(2, counterResult);
  13478. }
  13479. }
  13480. };
  13481. //=================================================================================
  13482. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13483. {
  13484. Owned<IActivityGraph> loopQuery;
  13485. Owned<IRoxieServerChildGraph> loopGraph;
  13486. IEngineRowStream * curStream;
  13487. RtlLinkedDatasetBuilder *loopInputBuilder;
  13488. CPointerArrayRoxieInput arrayInput;
  13489. Linked<IEngineRowStream> resultStream;
  13490. unsigned loopCounter;
  13491. public:
  13492. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13493. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13494. {
  13495. curStream = NULL;
  13496. loopCounter = 0;
  13497. loopInputBuilder = NULL;
  13498. }
  13499. virtual bool needsAllocator() const { return true; }
  13500. virtual void onCreate(IHThorArg *_colocalParent)
  13501. {
  13502. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13503. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13504. }
  13505. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13506. {
  13507. curStream = inputStream;
  13508. loopCounter = 1;
  13509. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13510. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13511. loopGraph.set(loopQuery->queryLoopGraph());
  13512. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13513. }
  13514. virtual void stop()
  13515. {
  13516. delete loopInputBuilder;
  13517. loopInputBuilder = NULL;
  13518. CRoxieServerLoopActivity::stop();
  13519. }
  13520. virtual const void * nextRow()
  13521. {
  13522. ActivityTimer t(totalCycles, timeActivities);
  13523. if (eof)
  13524. return NULL;
  13525. unsigned emptyIterations = 0;
  13526. for (;;)
  13527. {
  13528. for (;;)
  13529. {
  13530. const void * ret = curStream->nextRow();
  13531. if (!ret)
  13532. {
  13533. ret = curStream->nextRow(); // more cope with groups somehow....
  13534. if (!ret)
  13535. {
  13536. if (finishedLooping)
  13537. {
  13538. eof = true;
  13539. return NULL;
  13540. }
  13541. break;
  13542. }
  13543. }
  13544. if (finishedLooping ||
  13545. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13546. {
  13547. processed++;
  13548. return ret;
  13549. }
  13550. loopInputBuilder->appendOwn(ret);
  13551. }
  13552. switch (activityKind)
  13553. {
  13554. case TAKloopdataset:
  13555. {
  13556. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13557. {
  13558. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13559. {
  13560. if (loopInputBuilder->getcount() == 0)
  13561. {
  13562. eof = true;
  13563. return NULL;
  13564. }
  13565. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13566. // MORE - should builder be cleared here?
  13567. curStream = &arrayInput;
  13568. finishedLooping = true;
  13569. continue; // back to the input loop again
  13570. }
  13571. }
  13572. break;
  13573. }
  13574. case TAKlooprow:
  13575. if (!loopInputBuilder->getcount())
  13576. {
  13577. finishedLooping = true;
  13578. eof = true;
  13579. return NULL;
  13580. }
  13581. break;
  13582. }
  13583. if (loopInputBuilder->getcount())
  13584. emptyIterations = 0;
  13585. else
  13586. {
  13587. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13588. emptyIterations++;
  13589. if (emptyIterations > maxEmptyLoopIterations)
  13590. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13591. if (emptyIterations % 32 == 0)
  13592. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13593. }
  13594. checkAbort();
  13595. try
  13596. {
  13597. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13598. resultStream.setown(results->createIterator(0));
  13599. if (flags & IHThorLoopArg::LFnewloopagain)
  13600. {
  13601. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13602. OwnedConstRoxieRow row = againResult->nextRow();
  13603. assertex(row);
  13604. //Result is a row which contains a single boolean field.
  13605. if (!((const bool *)row.get())[0])
  13606. finishedLooping = true;
  13607. }
  13608. }
  13609. catch (IException *E)
  13610. {
  13611. throw makeWrappedException(E);
  13612. }
  13613. curStream = resultStream.get();
  13614. loopCounter++;
  13615. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13616. finishedLooping = true;
  13617. }
  13618. }
  13619. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13620. {
  13621. try
  13622. {
  13623. loopGraph->beforeExecute();
  13624. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13625. loopInputBuilder->clear();
  13626. loopGraph->setInputResult(1, inputRowsResult);
  13627. createCounterResult(loopGraph, counter);
  13628. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13629. loopGraph->afterExecute();
  13630. return ret.getClear();
  13631. }
  13632. catch (...)
  13633. {
  13634. CTXLOG("Exception thrown in loop body - cleaning up");
  13635. loopGraph->afterExecute();
  13636. throw;
  13637. }
  13638. }
  13639. };
  13640. //=================================================================================
  13641. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13642. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13643. {
  13644. public:
  13645. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13646. : meta(_meta), input(_input)
  13647. {
  13648. eof = false;
  13649. }
  13650. virtual const void * nextRow()
  13651. {
  13652. if (eof)
  13653. return NULL;
  13654. const void * ret = input.dequeue();
  13655. if (!ret)
  13656. eof = true;
  13657. return ret;
  13658. }
  13659. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13660. protected:
  13661. SafeRowQueue & input;
  13662. IOutputMetaData * meta;
  13663. bool eof;
  13664. };
  13665. class CRoxieServerParallelLoopActivity;
  13666. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13667. {
  13668. public:
  13669. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13670. activity(_activity), counter(_counter)
  13671. {
  13672. }
  13673. virtual const void * nextRow();
  13674. protected:
  13675. CRoxieServerParallelLoopActivity * activity;
  13676. unsigned counter;
  13677. };
  13678. class LoopExecutorThread : public RestartableThread
  13679. {
  13680. protected:
  13681. Owned<CSafeRoxieInput> safeInput;
  13682. CRoxieServerParallelLoopActivity * activity;
  13683. bool eof;
  13684. CriticalSection crit;
  13685. unsigned flags;
  13686. SafeRowQueue tempResults[2];
  13687. unsigned savedParentExtractSize;
  13688. const byte * savedParentExtract;
  13689. IArrayOf<IActivityGraph> cachedGraphs;
  13690. IRoxieSlaveContext *ctx;
  13691. public:
  13692. LoopExecutorThread()
  13693. : RestartableThread("LoopExecutorThread")
  13694. {
  13695. activity = NULL;
  13696. eof = false;
  13697. flags = 0;
  13698. ctx = NULL;
  13699. savedParentExtract = NULL;
  13700. savedParentExtractSize = 0;
  13701. }
  13702. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13703. {
  13704. activity = _activity;
  13705. flags = _flags;
  13706. // 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.
  13707. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13708. }
  13709. void connectInputStreams(bool consumerOrdered)
  13710. {
  13711. safeInput->connectInputStreams(ctx, consumerOrdered);
  13712. }
  13713. IFinalRoxieInput *queryInput() const
  13714. {
  13715. return safeInput;
  13716. }
  13717. void onCreate(IRoxieSlaveContext * _ctx);
  13718. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13719. void stop();
  13720. void reset();
  13721. virtual int run();
  13722. protected:
  13723. void executeLoop();
  13724. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13725. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13726. };
  13727. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13728. {
  13729. friend class LoopFilterPseudoInput;
  13730. friend class LoopExecutorThread;
  13731. QueueOf<const void, true> ready;
  13732. CriticalSection helperCS;
  13733. CriticalSection cs;
  13734. unsigned defaultNumParallel;
  13735. LoopExecutorThread executor;
  13736. IProbeManager* probeManager;
  13737. CriticalSection canAccess;
  13738. CriticalSection scrit;
  13739. InterruptableSemaphore readySpace;
  13740. InterruptableSemaphore recordsReady;
  13741. protected:
  13742. bool includeInLoop(unsigned counter, const void * row)
  13743. {
  13744. CriticalBlock b(helperCS);
  13745. return helper.sendToLoop(counter, row);
  13746. }
  13747. public:
  13748. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13749. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13750. readySpace(parallelLoopFlowLimit)
  13751. {
  13752. probeManager = _probeManager;
  13753. defaultNumParallel = 0;
  13754. }
  13755. virtual void onCreate(IHThorArg *_colocalParent)
  13756. {
  13757. CRoxieServerActivity::onCreate(_colocalParent);
  13758. executor.onCreate(ctx);
  13759. }
  13760. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13761. {
  13762. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13763. readySpace.reinit(parallelLoopFlowLimit);
  13764. recordsReady.reinit();
  13765. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13766. defaultNumParallel = helper.defaultParallelIterations();
  13767. if (!defaultNumParallel)
  13768. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13769. //MORE: If numIterations <= number of parallel iterations[1],
  13770. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13771. //being transferred via a queue
  13772. executor.start(parentExtractSize, parentExtract, paused);
  13773. }
  13774. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13775. {
  13776. if (idx)
  13777. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13778. executor.setInput(this, _sourceIdx, _in, flags);
  13779. }
  13780. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13781. {
  13782. executor.connectInputStreams(consumerOrdered);
  13783. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13784. }
  13785. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13786. {
  13787. if (idx==0)
  13788. return executor.queryInput();
  13789. else
  13790. return NULL;
  13791. }
  13792. virtual void stop()
  13793. {
  13794. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13795. readySpace.interrupt();
  13796. recordsReady.interrupt();
  13797. executor.join(); // MORE - may not be needed given stop/reset split
  13798. CRoxieServerLoopActivity::stop();
  13799. }
  13800. virtual void reset()
  13801. {
  13802. while (ready.ordinality())
  13803. ReleaseRoxieRow(ready.dequeue());
  13804. executor.reset();
  13805. CRoxieServerActivity::reset();
  13806. }
  13807. virtual const void * nextRow()
  13808. {
  13809. ActivityTimer t(totalCycles, timeActivities);
  13810. for (;;)
  13811. {
  13812. if (eof)
  13813. return NULL;
  13814. recordsReady.wait();
  13815. CriticalBlock procedure(canAccess);
  13816. if (ready.ordinality())
  13817. {
  13818. const void *result = ready.dequeue();
  13819. readySpace.signal();
  13820. if (result)
  13821. processed++;
  13822. return result;
  13823. }
  13824. else
  13825. eof = true;
  13826. }
  13827. }
  13828. unsigned getNumParallel(unsigned iter)
  13829. {
  13830. return defaultNumParallel;
  13831. }
  13832. inline void enqueueResult(const void * row)
  13833. {
  13834. try
  13835. {
  13836. while(!readySpace.wait(1000))
  13837. {
  13838. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13839. }
  13840. }
  13841. catch (...)
  13842. {
  13843. ReleaseRoxieRow(row);
  13844. throw;
  13845. }
  13846. CriticalBlock b2(canAccess);
  13847. ready.enqueue(row);
  13848. recordsReady.signal();
  13849. }
  13850. inline void finishResults()
  13851. {
  13852. recordsReady.signal();
  13853. }
  13854. virtual bool fireException(IException *e)
  13855. {
  13856. readySpace.interrupt(LINK(e));
  13857. recordsReady.interrupt(e);
  13858. return true;
  13859. }
  13860. IActivityGraph * createChildGraphInstance()
  13861. {
  13862. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13863. }
  13864. IActivityGraph * queryChildGraph()
  13865. {
  13866. return ctx->queryChildGraph(loopGraphId);
  13867. }
  13868. };
  13869. //=================================================================================
  13870. const void * LoopFilterPseudoInput::nextRow()
  13871. {
  13872. for (;;)
  13873. {
  13874. const void * next = stream->nextRow();
  13875. if (!next || activity->includeInLoop(counter, next))
  13876. return next;
  13877. activity->enqueueResult(next);
  13878. }
  13879. }
  13880. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13881. {
  13882. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13883. ctx = _ctx;
  13884. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13885. }
  13886. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13887. {
  13888. savedParentExtractSize = parentExtractSize;
  13889. savedParentExtract = parentExtract;
  13890. eof = false;
  13891. StringBuffer logPrefix("[");
  13892. ctx->getLogPrefix(logPrefix).append("] ");
  13893. RestartableThread::start(logPrefix);
  13894. }
  13895. int LoopExecutorThread::run()
  13896. {
  13897. try
  13898. {
  13899. executeLoop();
  13900. }
  13901. catch (IException *e)
  13902. {
  13903. activity->fireException(e);
  13904. }
  13905. catch (...)
  13906. {
  13907. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13908. }
  13909. return 0;
  13910. }
  13911. void LoopExecutorThread::stop()
  13912. {
  13913. safeInput->stop();
  13914. RestartableThread::join();
  13915. }
  13916. void LoopExecutorThread::reset()
  13917. {
  13918. safeInput->reset();
  13919. }
  13920. void LoopExecutorThread::executeLoop()
  13921. {
  13922. unsigned iterations = 0;
  13923. unsigned counter = 0;
  13924. unsigned outputIndex = 0;
  13925. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13926. for (;;)
  13927. {
  13928. if (activity->activityKind == TAKloopcount)
  13929. {
  13930. if (counter == activity->maxIterations)
  13931. break;
  13932. }
  13933. else
  13934. {
  13935. //This condition isn't quite right because it needs to be whether the filtered
  13936. //input is empty. May be ok if we include that in the semantics,
  13937. if (tempResults[1-outputIndex].ordinality() == 0)
  13938. break;
  13939. }
  13940. unsigned numParallel = activity->getNumParallel(iterations);
  13941. Linked<IFinalRoxieInput> curInput;
  13942. if (iterations == 0)
  13943. curInput.set(safeInput);
  13944. else
  13945. {
  13946. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13947. inputQueue.enqueue(NULL);
  13948. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13949. }
  13950. SafeRowQueue * curOutput = NULL;
  13951. if (counter+numParallel > activity->maxIterations)
  13952. numParallel = activity->maxIterations - counter;
  13953. else if (counter+numParallel < activity->maxIterations)
  13954. curOutput = &tempResults[outputIndex];
  13955. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13956. outputIndex = 1-outputIndex;
  13957. counter += numParallel;
  13958. iterations++;
  13959. }
  13960. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13961. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13962. while (inputQueue.ordinality())
  13963. {
  13964. const void * next = inputQueue.dequeue();
  13965. activity->enqueueResult(next);
  13966. }
  13967. activity->finishResults();
  13968. }
  13969. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  13970. {
  13971. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  13972. Linked<IFinalRoxieInput> curInput = input;
  13973. unsigned i;
  13974. for (i= 0; i != numIterations; i++)
  13975. {
  13976. unsigned thisCounter = counter+i+1;
  13977. IFinalRoxieInput * filtered = curInput;
  13978. if (flags & IHThorLoopArg::LFfiltered)
  13979. {
  13980. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  13981. newFiltered->setInput(inputIdx, curInput);
  13982. filtered = newFiltered;
  13983. savedInputs.append(*filtered);
  13984. inputIdx = 0;
  13985. }
  13986. //graph is kept, so new curInput will be guaranteed to exist
  13987. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  13988. inputIdx = 0;
  13989. }
  13990. Owned<IStrandJunction> curJunction;
  13991. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  13992. Owned<IException> failure;
  13993. try
  13994. {
  13995. curInput->start(savedParentExtractSize, savedParentExtract, false);
  13996. if (spillOutput)
  13997. {
  13998. for (;;)
  13999. {
  14000. const void * next = curStream->nextRow();
  14001. if (!next)
  14002. break;
  14003. spillOutput->enqueue(next);
  14004. }
  14005. }
  14006. else
  14007. {
  14008. for (;;)
  14009. {
  14010. const void * next = curStream->nextRow();
  14011. if (!next)
  14012. break;
  14013. activity->enqueueResult(next);
  14014. }
  14015. }
  14016. }
  14017. catch (IException *E)
  14018. {
  14019. ctx->notifyAbort(E);
  14020. failure.setown(E);
  14021. }
  14022. for (i= 0; i != numIterations; i++)
  14023. {
  14024. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14025. loopGraph->afterExecute();
  14026. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  14027. loopGraph->querySetInputResult(1, 0, nullptr);
  14028. }
  14029. curStream->stop();
  14030. curInput->reset();
  14031. if (failure)
  14032. throw failure.getClear();
  14033. }
  14034. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  14035. {
  14036. if (!cachedGraphs.isItem(i))
  14037. cachedGraphs.append(*activity->createChildGraphInstance());
  14038. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14039. loopGraph->beforeExecute();
  14040. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  14041. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  14042. activity->createCounterResult(loopGraph, counter);
  14043. return loopGraph->selectOutput(0);
  14044. }
  14045. //=================================================================================
  14046. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  14047. {
  14048. public:
  14049. IMPLEMENT_IINTERFACE
  14050. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  14051. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  14052. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  14053. virtual void toXML(const byte * self, IXmlWriter & out) { }
  14054. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  14055. virtual unsigned getMetaFlags() { return 0; }
  14056. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  14057. virtual void destruct(byte * self) {}
  14058. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14059. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14060. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  14061. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  14062. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14063. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14064. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  14065. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  14066. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  14067. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); } // could provide a static implementation if needed
  14068. };
  14069. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  14070. {
  14071. unsigned loopGraphId;
  14072. unsigned flags;
  14073. Linked<IOutputMetaData> counterMeta;
  14074. public:
  14075. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14076. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14077. {
  14078. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  14079. flags = helper->getFlags();
  14080. counterMeta.setown(new CCounterRowMetaData);
  14081. }
  14082. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14083. {
  14084. if (flags & IHThorLoopArg::LFparallel)
  14085. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14086. else
  14087. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14088. }
  14089. };
  14090. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14091. {
  14092. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14093. }
  14094. //=================================================================================
  14095. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  14096. {
  14097. protected:
  14098. IHThorGraphLoopArg &helper;
  14099. unsigned maxIterations;
  14100. unsigned flags;
  14101. rtlRowBuilder GraphExtractBuilder;
  14102. unsigned loopGraphId;
  14103. Linked<IOutputMetaData> counterMeta;
  14104. public:
  14105. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14106. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14107. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  14108. {
  14109. flags = helper.getFlags();
  14110. maxIterations = 0;
  14111. }
  14112. virtual bool needsAllocator() const { return true; }
  14113. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14114. {
  14115. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14116. int iterations = (int) helper.numIterations();
  14117. maxIterations = (iterations >= 0) ? iterations : 0;
  14118. if (maxIterations > maxGraphLoopIterations)
  14119. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  14120. if (maxIterations != 0)
  14121. {
  14122. GraphExtractBuilder.clear();
  14123. helper.createParentExtract(GraphExtractBuilder);
  14124. }
  14125. }
  14126. virtual void stop()
  14127. {
  14128. CRoxieServerActivity::stop();
  14129. GraphExtractBuilder.clear();
  14130. }
  14131. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  14132. {
  14133. if (flags & IHThorGraphLoopArg::GLFcounter)
  14134. {
  14135. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  14136. *((thor_loop_counter_t *)counterRow) = counter;
  14137. RtlLinkedDatasetBuilder builder(rowAllocator);
  14138. builder.appendOwn(counterRow);
  14139. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  14140. graph->setInputResult(0, counterResult);
  14141. }
  14142. }
  14143. };
  14144. //=================================================================================
  14145. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  14146. {
  14147. Owned<IActivityGraph> GraphQuery;
  14148. Owned<IRoxieServerChildGraph> loopGraph;
  14149. Linked<IEngineRowStream> resultStream;
  14150. bool evaluated;
  14151. public:
  14152. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14153. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  14154. {
  14155. evaluated = false;
  14156. }
  14157. virtual void onCreate(IHThorArg *_colocalParent)
  14158. {
  14159. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14160. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  14161. }
  14162. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14163. {
  14164. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  14165. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  14166. loopGraph.set(GraphQuery->queryLoopGraph());
  14167. evaluated = false;
  14168. }
  14169. virtual void stop()
  14170. {
  14171. if (loopGraph)
  14172. loopGraph->clearGraphLoopResults();
  14173. CRoxieServerGraphLoopActivity::stop();
  14174. }
  14175. virtual const void * nextRow()
  14176. {
  14177. ActivityTimer t(totalCycles, timeActivities);
  14178. if (!evaluated)
  14179. {
  14180. executeEntireGraph();
  14181. evaluated = true;
  14182. }
  14183. const void * ret = resultStream->nextRow();
  14184. if (ret)
  14185. processed++;
  14186. return ret;
  14187. }
  14188. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  14189. {
  14190. try
  14191. {
  14192. loopGraph->beforeExecute();
  14193. createCounterResult(loopGraph, counter);
  14194. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  14195. loopGraph->afterExecute();
  14196. }
  14197. catch (...)
  14198. {
  14199. CTXLOG("Exception thrown in graph body - cleaning up");
  14200. loopGraph->afterExecute();
  14201. throw;
  14202. }
  14203. }
  14204. void createInitialGraphInput()
  14205. {
  14206. loopGraph->clearGraphLoopResults();
  14207. RtlLinkedDatasetBuilder builder(rowAllocator);
  14208. inputStream->readAll(builder);
  14209. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  14210. loopGraph->setGraphLoopResult(0, result);
  14211. }
  14212. void executeEntireGraph()
  14213. {
  14214. createInitialGraphInput();
  14215. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  14216. {
  14217. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  14218. }
  14219. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  14220. }
  14221. };
  14222. //=================================================================================
  14223. struct GraphOutputSplitterArg : public CThorSplitArg
  14224. {
  14225. public:
  14226. virtual unsigned numBranches()
  14227. {
  14228. return 0;
  14229. }
  14230. virtual IOutputMetaData * queryOutputMeta()
  14231. {
  14232. return NULL;// get it from the parent..
  14233. }
  14234. };
  14235. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  14236. class CGraphIterationInfo : public CInterface
  14237. {
  14238. private:
  14239. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  14240. unsigned sourceIdx;
  14241. Linked<IRoxieServerActivity> sourceAct;
  14242. Linked<IFinalRoxieInput> sourceInput;
  14243. unsigned numUses;
  14244. unsigned iteration;
  14245. public:
  14246. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  14247. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  14248. {
  14249. numUses = 0;
  14250. }
  14251. inline void noteUsed()
  14252. {
  14253. numUses++;
  14254. }
  14255. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14256. {
  14257. if (numUses > 1)
  14258. {
  14259. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  14260. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  14261. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  14262. splitter->onCreate(NULL);
  14263. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14264. if (probeManager)
  14265. {
  14266. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14267. probes.append(*LINK(inputProbe));
  14268. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14269. sourceIdx = 0;
  14270. }
  14271. sourceAct.setown(splitter);
  14272. sourceAct->setInput(0, sourceIdx, input);
  14273. sourceIdx = 0;
  14274. sourceInput.clear();
  14275. }
  14276. }
  14277. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14278. {
  14279. // MORE - not really necessary to create splitters in separate pass, is it?
  14280. if (factory) // we created a splitter....
  14281. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14282. IFinalRoxieInput *ret = sourceInput;
  14283. if (probeManager)
  14284. {
  14285. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14286. probes.append(*LINK(inputProbe));
  14287. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14288. // MORE - do we need to connect the stream in the probe?
  14289. }
  14290. if (factory) // we created a splitter....
  14291. sourceIdx++;
  14292. return ret;
  14293. }
  14294. };
  14295. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14296. {
  14297. Owned<IActivityGraph> childGraph;
  14298. IFinalRoxieInput * resultInput;
  14299. IEngineRowStream * resultStream;
  14300. Owned<IStrandJunction> resultJunction;
  14301. CIArrayOf<CGraphIterationInfo> outputs;
  14302. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14303. Owned<CExtractMapperInput> inputExtractMapper;
  14304. IProbeManager *probeManager;
  14305. Owned<IStatisticGatherer> childStats;
  14306. unsigned createLoopCounter;
  14307. IArrayOf<IRoxieProbe> probes;
  14308. public:
  14309. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14310. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14311. {
  14312. inputExtractMapper.setown(new CExtractMapperInput);
  14313. resultInput = NULL;
  14314. resultStream = NULL;
  14315. createLoopCounter = 0;
  14316. if (ctx && ctx->collectingDetailedStatistics())
  14317. {
  14318. StatsScopeId rootScope(SSTnone, 0U);
  14319. childStats.setown(createStatisticsGatherer(SCTroxie, "", rootScope));
  14320. }
  14321. }
  14322. virtual void onCreate(IHThorArg *_colocalParent)
  14323. {
  14324. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14325. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14326. }
  14327. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14328. {
  14329. CRoxieServerGraphLoopActivity::gatherStatistics(statsBuilder);
  14330. if (statsBuilder && childStats)
  14331. {
  14332. //Merge any stats collected from executed graphs into the full statistics
  14333. Owned<IStatisticCollection> childCollection = childStats->getResult();
  14334. childCollection->mergeInto(*statsBuilder);
  14335. }
  14336. }
  14337. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14338. {
  14339. //Input needs to be handled very carefully.....
  14340. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14341. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14342. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14343. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14344. assertex(idx == 0);
  14345. inputExtractMapper->setInput(_sourceIdx, _in);
  14346. }
  14347. virtual void connectInputStreams(bool consumerOrdered)
  14348. {
  14349. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14350. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14351. }
  14352. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14353. {
  14354. if (idx==0)
  14355. return inputExtractMapper->queryInput();
  14356. else
  14357. return NULL;
  14358. }
  14359. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14360. {
  14361. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14362. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14363. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14364. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14365. startJunction(resultJunction);
  14366. }
  14367. virtual void stop()
  14368. {
  14369. if (resultStream)
  14370. resultStream->stop();
  14371. CRoxieServerGraphLoopActivity::stop();
  14372. }
  14373. virtual void reset()
  14374. {
  14375. if (resultInput)
  14376. resultInput->reset();
  14377. resetJunction(resultJunction);
  14378. resultInput = NULL;
  14379. resultStream = NULL;
  14380. resultJunction.clear();
  14381. ForEachItemIn(i, iterationGraphs)
  14382. iterationGraphs.item(i).gatherStatistics(childStats);
  14383. outputs.kill();
  14384. iterationGraphs.kill(); // must be done after all activities killed
  14385. if (probeManager)
  14386. {
  14387. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14388. probes.kill();
  14389. }
  14390. CRoxieServerGraphLoopActivity::reset();
  14391. }
  14392. virtual const void * nextRow()
  14393. {
  14394. ActivityTimer t(totalCycles, timeActivities);
  14395. const void * ret = resultStream->nextRow();
  14396. if (ret)
  14397. processed++;
  14398. return ret;
  14399. }
  14400. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14401. {
  14402. //result(0) is the input to the graph.
  14403. resultInput = inputExtractMapper;
  14404. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14405. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14406. {
  14407. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14408. graph->beforeExecute();
  14409. iterationGraphs.append(*graph);
  14410. graph->gatherIterationUsage(*this);
  14411. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14412. outputs.append(*iteration);
  14413. }
  14414. createLoopCounter = 0;
  14415. createSplitters(probeManager, probes);
  14416. ForEachItemIn(i2, iterationGraphs)
  14417. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14418. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14419. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14420. }
  14421. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14422. {
  14423. ForEachItemIn(i, outputs)
  14424. {
  14425. CGraphIterationInfo & next = outputs.item(i);
  14426. next.createSplitter(ctx, probeManager, probes);
  14427. }
  14428. }
  14429. //IRoxieServerLoopResultProcessor
  14430. virtual void noteUseIteration(unsigned _whichIteration)
  14431. {
  14432. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14433. if (whichIteration >= 0)
  14434. {
  14435. if (!outputs.isItem(whichIteration))
  14436. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14437. outputs.item(whichIteration).noteUsed();
  14438. }
  14439. }
  14440. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14441. {
  14442. if (outputs.isItem(whichIteration))
  14443. {
  14444. CGraphIterationInfo & next = outputs.item(whichIteration);
  14445. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14446. }
  14447. return NULL;
  14448. }
  14449. };
  14450. //=================================================================================
  14451. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14452. {
  14453. unsigned loopGraphId;
  14454. unsigned flags;
  14455. Linked<IOutputMetaData> counterMeta;
  14456. public:
  14457. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14458. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14459. {
  14460. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14461. flags = helper->getFlags();
  14462. counterMeta.setown(new CCounterRowMetaData);
  14463. }
  14464. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14465. {
  14466. if (kind == TAKparallelgraphloop)
  14467. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14468. else
  14469. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14470. }
  14471. };
  14472. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14473. {
  14474. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14475. }
  14476. //=====================================================================================================
  14477. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14478. {
  14479. class OutputAdaptor : public CExtractMapperInput
  14480. {
  14481. bool stopped;
  14482. public:
  14483. CRoxieServerLibraryCallActivity *parent;
  14484. IOutputMetaData * meta = nullptr;
  14485. unsigned oid;
  14486. unsigned processed;
  14487. unsigned numStarts = 0;
  14488. public:
  14489. OutputAdaptor()
  14490. {
  14491. parent = NULL;
  14492. oid = 0;
  14493. init();
  14494. }
  14495. ~OutputAdaptor()
  14496. {
  14497. if (traceStartStop)
  14498. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14499. }
  14500. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14501. {
  14502. parent = _parent;
  14503. meta = _meta;
  14504. oid = _oid;
  14505. }
  14506. void init()
  14507. {
  14508. processed = 0;
  14509. stopped = false;
  14510. }
  14511. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14512. {
  14513. parent->start(oid, parentExtractSize, parentExtract, paused);
  14514. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14515. numStarts++;
  14516. }
  14517. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14518. {
  14519. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14520. if (!oid) // Only need to set up once
  14521. {
  14522. parent->connectInputStreams(true); // To handle dependencies etc
  14523. }
  14524. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14525. }
  14526. //This override should not really be needed, but input is set up too late for the call to connect strands
  14527. virtual IOutputMetaData * queryOutputMeta() const
  14528. {
  14529. return meta;
  14530. }
  14531. virtual void stop()
  14532. {
  14533. if (!stopped)
  14534. {
  14535. stopped = true;
  14536. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14537. CExtractMapperInput::stop();
  14538. }
  14539. };
  14540. virtual void reset()
  14541. {
  14542. parent->reset(oid);
  14543. CExtractMapperInput::reset();
  14544. init();
  14545. };
  14546. virtual void checkAbort()
  14547. {
  14548. parent->checkAbort();
  14549. }
  14550. };
  14551. IHThorLibraryCallArg &helper;
  14552. unsigned numInputs;
  14553. unsigned numOutputs;
  14554. unsigned numActiveOutputs;
  14555. bool started;
  14556. OutputAdaptor* outputAdaptors;
  14557. CExtractMapperInput * * inputAdaptors;
  14558. bool * inputUsed;
  14559. bool * outputUsed;
  14560. Owned<IException> error;
  14561. CriticalSection crit;
  14562. rtlRowBuilder libraryExtractBuilder;
  14563. Owned<IActivityGraph> libraryGraph;
  14564. const LibraryCallFactoryExtra & extra;
  14565. public:
  14566. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14567. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14568. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14569. {
  14570. numInputs = _numInputs;
  14571. numOutputs = _numOutputs;
  14572. numActiveOutputs = numOutputs;
  14573. inputAdaptors = new CExtractMapperInput*[numInputs];
  14574. inputUsed = new bool[numInputs];
  14575. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14576. {
  14577. inputAdaptors[i1] = new CExtractMapperInput;
  14578. inputUsed[i1] = false;
  14579. }
  14580. outputAdaptors = new OutputAdaptor[numOutputs];
  14581. outputUsed = new bool[numOutputs];
  14582. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14583. {
  14584. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14585. outputUsed[i2] = false;
  14586. }
  14587. started = false;
  14588. }
  14589. ~CRoxieServerLibraryCallActivity()
  14590. {
  14591. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14592. ::Release(inputAdaptors[i1]);
  14593. delete [] inputAdaptors;
  14594. delete [] inputUsed;
  14595. delete [] outputAdaptors;
  14596. delete [] outputUsed;
  14597. }
  14598. virtual void onCreate(IHThorArg *_colocalParent)
  14599. {
  14600. CRoxieServerActivity::onCreate(_colocalParent);
  14601. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14602. libraryGraph->onCreate(_colocalParent);
  14603. //Now map the inputs and outputs to the adapters
  14604. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14605. for (unsigned i1=0; i1<numInputs; i1++)
  14606. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14607. for (unsigned i2=0; i2<numOutputs; i2++)
  14608. {
  14609. unsigned outputIndex = extra.outputs.item(i2);
  14610. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14611. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14612. outputAdaptors[i2].connectInputStreams(ctx, true);
  14613. }
  14614. }
  14615. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14616. {
  14617. CriticalBlock b(crit);
  14618. if (error)
  14619. throw error.getLink();
  14620. if (collectFactoryStatistics)
  14621. factory->noteStarted(oid);
  14622. if (!started)
  14623. {
  14624. // even though it is not complete, we don't want to run this again if it fails.
  14625. started = true;
  14626. //see notes on splitter above
  14627. try
  14628. {
  14629. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14630. }
  14631. catch (IException *E)
  14632. {
  14633. #ifdef TRACE_SPLIT
  14634. CTXLOG("spill %d caught exception in start", activityId);
  14635. #endif
  14636. error.set(E);
  14637. throw;
  14638. }
  14639. catch (...)
  14640. {
  14641. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14642. error.set(E);
  14643. throw E;
  14644. }
  14645. //recreate the parent extract, and use it to reinitialize the graphs...
  14646. libraryExtractBuilder.clear();
  14647. helper.createParentExtract(libraryExtractBuilder);
  14648. // 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
  14649. // some inputs before we see start on others.
  14650. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14651. {
  14652. if (inputUsed[i1])
  14653. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14654. else
  14655. inputAdaptors[i1]->queryInput()->stopall();
  14656. }
  14657. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14658. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14659. //call stop on all the unused inputs.
  14660. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14661. graph->beforeExecute();
  14662. ForEachItemIn(i3, extra.unusedOutputs)
  14663. {
  14664. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14665. output->stopall();
  14666. }
  14667. }
  14668. }
  14669. virtual void stop(unsigned oid)
  14670. {
  14671. CriticalBlock b(crit);
  14672. if (--numActiveOutputs == 0)
  14673. {
  14674. //call stop on all the unused inputs.
  14675. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14676. graph->beforeExecute();
  14677. ForEachItemIn(i3, extra.unusedOutputs)
  14678. {
  14679. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14680. output->stopall();
  14681. }
  14682. CRoxieServerActivity::stop();
  14683. }
  14684. }
  14685. void reset(unsigned oid)
  14686. {
  14687. started = false;
  14688. error.clear();
  14689. numActiveOutputs = numOutputs;
  14690. if (state != STATEreset) // make sure input is only reset once
  14691. {
  14692. CRoxieServerActivity::reset();
  14693. libraryGraph->reset();
  14694. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14695. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14696. {
  14697. if (!inputUsed[i1])
  14698. inputAdaptors[i1]->reset();
  14699. }
  14700. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14701. ForEachItemIn(i3, extra.unusedOutputs)
  14702. {
  14703. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14704. output->reset();
  14705. }
  14706. }
  14707. };
  14708. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14709. {
  14710. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14711. }
  14712. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14713. {
  14714. if (idx < numInputs && inputAdaptors[idx])
  14715. return inputAdaptors[idx]->queryInput();
  14716. else
  14717. return NULL;
  14718. }
  14719. public:
  14720. virtual const void *nextRow()
  14721. {
  14722. throwUnexpected(); // Internal logic error - we are not anybody's input
  14723. }
  14724. virtual IOutputMetaData * queryOutputMeta() const
  14725. {
  14726. throwUnexpected(); // should be called on outputs instead
  14727. }
  14728. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14729. {
  14730. assertex(idx!=(unsigned)-1);
  14731. assertex(!outputUsed[idx]);
  14732. outputUsed[idx] = true;
  14733. return &outputAdaptors[idx];
  14734. }
  14735. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14736. {
  14737. if (libraryGraph)
  14738. libraryGraph->gatherStatistics(statsBuilder);
  14739. CRoxieServerActivity::gatherStatistics(statsBuilder);
  14740. }
  14741. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  14742. {
  14743. for (unsigned i = 0; i < numOutputs; i++)
  14744. addEdgeStats(statsBuilder, i, outputAdaptors[i].numStarts, outputAdaptors[i].processed, 0);
  14745. }
  14746. };
  14747. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14748. {
  14749. ForEachItemIn(i1, _other.outputs)
  14750. outputs.append(_other.outputs.item(i1));
  14751. ForEachItemIn(i2, _other.unusedOutputs)
  14752. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14753. maxOutputs = _other.maxOutputs;
  14754. graphid = _other.graphid;
  14755. libraryName.set(_other.libraryName);
  14756. embeddedGraphName.set(_other.embeddedGraphName);
  14757. interfaceHash = _other.interfaceHash;
  14758. embedded = _other.embedded;
  14759. }
  14760. void LibraryCallFactoryExtra::calcUnused()
  14761. {
  14762. for (unsigned i=0; i < maxOutputs; i++)
  14763. if (!outputs.contains(i))
  14764. unusedOutputs.append(i);
  14765. }
  14766. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14767. {
  14768. private:
  14769. CRoxieServerMultiInputInfo inputs;
  14770. LibraryCallFactoryExtra extra;
  14771. public:
  14772. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14773. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14774. {
  14775. extra.set(_extra);
  14776. extra.calcUnused();
  14777. setNumOutputs(extra.outputs.ordinality());
  14778. }
  14779. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14780. {
  14781. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14782. }
  14783. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14784. {
  14785. inputs.set(idx, source, sourceidx);
  14786. }
  14787. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14788. {
  14789. return inputs.get(idx, sourceidx);
  14790. }
  14791. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14792. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14793. {
  14794. addXrefLibraryInfo(reply, extra.libraryName);
  14795. }
  14796. };
  14797. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14798. {
  14799. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14800. }
  14801. //=====================================================================================================
  14802. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14803. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14804. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14805. {
  14806. protected:
  14807. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14808. PointerArrayOf<IEngineRowStream> selectedStreams;
  14809. PointerArrayOf<IStrandJunction> selectedJunctions;
  14810. public:
  14811. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14812. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14813. {
  14814. }
  14815. virtual unsigned __int64 queryLocalCycles() const
  14816. {
  14817. __int64 localCycles = totalCycles.totalCycles;
  14818. ForEachItemIn(i, selectedInputs)
  14819. {
  14820. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14821. }
  14822. if (localCycles < 0)
  14823. localCycles = 0;
  14824. return localCycles;
  14825. }
  14826. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14827. {
  14828. if (selectedInputs.isItem(idx))
  14829. return selectedInputs.item(idx);
  14830. else
  14831. return NULL;
  14832. }
  14833. virtual void reset()
  14834. {
  14835. ForEachItemIn(i, selectedInputs)
  14836. selectedInputs.item(i)->reset();
  14837. selectedInputs.kill();
  14838. selectedStreams.kill();
  14839. selectedJunctions.kill();
  14840. CRoxieServerMultiInputBaseActivity::reset();
  14841. }
  14842. virtual const void * nextRow()
  14843. {
  14844. throwUnexpected();
  14845. }
  14846. virtual unsigned numConcreteOutputs() const
  14847. {
  14848. return selectedInputs.ordinality();
  14849. }
  14850. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14851. {
  14852. return queryInput(idx);
  14853. }
  14854. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14855. {
  14856. if (selectedStreams.isItem(whichInput))
  14857. return selectedStreams.item(whichInput);
  14858. return NULL;
  14859. }
  14860. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14861. {
  14862. if (selectedJunctions.isItem(idx))
  14863. return selectedJunctions.item(idx);
  14864. return NULL;
  14865. }
  14866. };
  14867. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14868. {
  14869. IHThorNWayInputArg & helper;
  14870. public:
  14871. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14872. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14873. {
  14874. }
  14875. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14876. {
  14877. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14878. bool selectionIsAll;
  14879. size32_t selectionLen;
  14880. rtlDataAttr selection;
  14881. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14882. selectedInputs.kill();
  14883. selectedStreams.kill();
  14884. selectedJunctions.kill();
  14885. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14886. if (selectionIsAll)
  14887. {
  14888. for (unsigned i=0; i < numInputs; i++)
  14889. {
  14890. selectedInputs.append(inputArray[i]);
  14891. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14892. selectedJunctions.append(junctionArray[i]);
  14893. }
  14894. }
  14895. else
  14896. {
  14897. const size32_t * selections = (const size32_t *)selection.getdata();
  14898. unsigned max = selectionLen/sizeof(size32_t);
  14899. for (unsigned i = 0; i < max; i++)
  14900. {
  14901. unsigned nextIndex = selections[i];
  14902. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14903. for (unsigned j=i+1; j < max; j++)
  14904. {
  14905. if (nextIndex == selections[j])
  14906. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14907. }
  14908. if (nextIndex > numInputs || nextIndex > numStreams)
  14909. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14910. selectedInputs.append(inputArray[nextIndex-1]);
  14911. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14912. selectedJunctions.append(junctionArray[nextIndex-1]);
  14913. }
  14914. }
  14915. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14916. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14917. stop();
  14918. }
  14919. };
  14920. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14921. {
  14922. public:
  14923. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14924. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14925. {
  14926. }
  14927. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14928. {
  14929. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14930. }
  14931. };
  14932. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14933. {
  14934. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14935. }
  14936. //=====================================================================================================
  14937. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14938. {
  14939. IHThorNWayGraphLoopResultReadArg & helper;
  14940. IArrayOf<IRoxieServerActivity> resultReaders;
  14941. Owned<IStrandJunction> *resultJunctions;
  14942. unsigned graphId;
  14943. bool grouped;
  14944. bool selectionIsAll;
  14945. size32_t selectionLen;
  14946. rtlDataAttr selection;
  14947. public:
  14948. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14949. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14950. {
  14951. grouped = helper.isGrouped();
  14952. graphId = _graphId;
  14953. selectionIsAll = false;
  14954. selectionLen = 0;
  14955. resultJunctions = NULL;
  14956. }
  14957. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14958. {
  14959. delete [] resultJunctions;
  14960. }
  14961. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14962. {
  14963. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14964. if (selectedInputs.ordinality() == 0)
  14965. {
  14966. initInputSelection();
  14967. unsigned max = selectionLen / sizeof(size32_t);
  14968. const size32_t * selections = (const size32_t *)selection.getdata();
  14969. IProbeManager * probeManager = NULL; // MORE!!
  14970. for (unsigned i = 0; i < max; i++)
  14971. {
  14972. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  14973. resultReaders.append(*resultInput);
  14974. selectedInputs.append(resultInput);
  14975. resultInput->onCreate(colocalParent);
  14976. resultInput->start(parentExtractSize, parentExtract, paused);
  14977. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  14978. selectedJunctions.append(resultJunctions[i]);
  14979. }
  14980. }
  14981. // I have done with my processing - note that this won't stop my inputs
  14982. stop();
  14983. }
  14984. virtual void reset()
  14985. {
  14986. resultReaders.kill();
  14987. CRoxieServerNWayInputBaseActivity::reset();
  14988. ForEachItemIn(i, selectedStreams)
  14989. resetJunction(resultJunctions[i]);
  14990. }
  14991. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  14992. {
  14993. ensureCreated();
  14994. basehelper.onStart(parentExtract, NULL);
  14995. initInputSelection();
  14996. unsigned max = selectionLen / sizeof(size32_t);
  14997. const size32_t * selections = (const size32_t *)selection.getdata();
  14998. for (unsigned i = 0; i < max; i++)
  14999. processor.noteUseIteration(selections[i]);
  15000. }
  15001. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  15002. {
  15003. //selection etc. already initialised from the gatherIterationUsage() call.
  15004. unsigned max = selectionLen / sizeof(size32_t);
  15005. const size32_t * selections = (const size32_t *)selection.getdata();
  15006. resultJunctions = new Owned<IStrandJunction> [max];
  15007. for (unsigned i = 0; i < max; i++)
  15008. {
  15009. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  15010. selectedInputs.append(in);
  15011. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  15012. selectedJunctions.append(resultJunctions[i]);
  15013. }
  15014. }
  15015. protected:
  15016. void initInputSelection()
  15017. {
  15018. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  15019. if (selectionIsAll)
  15020. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  15021. }
  15022. };
  15023. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  15024. {
  15025. unsigned graphId;
  15026. public:
  15027. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  15028. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  15029. {
  15030. }
  15031. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15032. {
  15033. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  15034. }
  15035. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15036. {
  15037. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  15038. }
  15039. };
  15040. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  15041. {
  15042. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  15043. }
  15044. //=================================================================================
  15045. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  15046. {
  15047. public:
  15048. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  15049. IMPLEMENT_IINTERFACE
  15050. protected:
  15051. virtual const void * nextInputRow()
  15052. {
  15053. #ifdef TRACE_SEEK_REQUESTS
  15054. IRoxieContextLogger * logger = input->queryActivity();
  15055. const void * ret = doNextInputRow();
  15056. {
  15057. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15058. if (!ret)
  15059. xmlwrite.outputBool(true,"eof");
  15060. else if (input->queryOutputMeta()->hasXML())
  15061. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15062. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  15063. }
  15064. return ret;
  15065. #else
  15066. return inputStream->ungroupedNextRow();
  15067. #endif
  15068. }
  15069. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15070. {
  15071. #ifdef TRACE_SEEK_REQUESTS
  15072. IRoxieContextLogger * logger = input->queryActivity();
  15073. {
  15074. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15075. if (input->queryOutputMeta()->hasXML())
  15076. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  15077. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  15078. numFields,
  15079. stepExtra.readAheadManyResults() ? "readahead " : "",
  15080. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15081. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15082. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15083. xmlwrite.str());
  15084. }
  15085. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15086. {
  15087. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15088. if (!ret)
  15089. xmlwrite.outputBool(true,"eof");
  15090. else if (input->queryOutputMeta()->hasXML())
  15091. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15092. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  15093. numFields,
  15094. stepExtra.readAheadManyResults() ? "readahead " : "",
  15095. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15096. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15097. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15098. xmlwrite.str());
  15099. }
  15100. return ret;
  15101. #else
  15102. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15103. #endif
  15104. }
  15105. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15106. {
  15107. return input->gatherConjunctions(collector);
  15108. }
  15109. virtual void resetEOF()
  15110. {
  15111. inputStream->resetEOF();
  15112. }
  15113. virtual IInputSteppingMeta * queryInputSteppingMeta()
  15114. {
  15115. return input->querySteppingMeta();
  15116. }
  15117. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15118. {
  15119. assertex(wasCompleteMatch);
  15120. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15121. }
  15122. protected:
  15123. IFinalRoxieInput * input;
  15124. IEngineRowStream * inputStream;
  15125. };
  15126. //=================================================================================
  15127. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  15128. {
  15129. public:
  15130. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15131. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15132. {
  15133. }
  15134. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15135. {
  15136. ForEachItemIn(ei, expandedInputs)
  15137. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  15138. ForEachItemIn(idx, expandedInputs)
  15139. startJunction(expandedJunctions.item(idx));
  15140. }
  15141. virtual void stop()
  15142. {
  15143. ForEachItemIn(i, expandedStreams)
  15144. expandedStreams.item(i)->stop();
  15145. CRoxieServerMultiInputBaseActivity::stop();
  15146. }
  15147. virtual void reset()
  15148. {
  15149. ForEachItemIn(idx, expandedInputs)
  15150. resetJunction(expandedJunctions.item(idx));
  15151. expandedInputs.kill();
  15152. expandedStreams.kill();
  15153. expandedJunctions.kill();
  15154. CRoxieServerMultiInputBaseActivity::reset();
  15155. }
  15156. protected:
  15157. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  15158. PointerArrayOf<IEngineRowStream> expandedStreams;
  15159. PointerArrayOf<IStrandJunction> expandedJunctions;
  15160. };
  15161. //=================================================================================
  15162. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  15163. {
  15164. public:
  15165. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15166. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15167. {
  15168. }
  15169. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15170. {
  15171. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15172. for (unsigned i=0; i < numInputs; i++)
  15173. {
  15174. IFinalRoxieInput * cur = inputArray[i];
  15175. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15176. if (nWayInput)
  15177. {
  15178. nWayInput->start(parentExtractSize, parentExtract, paused);
  15179. unsigned numRealInputs = cur->numConcreteOutputs();
  15180. for (unsigned j = 0; j < numRealInputs; j++)
  15181. {
  15182. expandedInputs.append(cur->queryConcreteInput(j));
  15183. expandedStreams.append(cur->queryConcreteOutputStream(j));
  15184. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  15185. }
  15186. }
  15187. else
  15188. {
  15189. expandedInputs.append(cur);
  15190. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15191. expandedStreams.append(queryConcreteOutputStream(i));
  15192. expandedJunctions.append(queryConcreteOutputJunction(i));
  15193. }
  15194. }
  15195. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15196. }
  15197. };
  15198. //=================================================================================
  15199. class CRoxieStreamMerger : public CStreamMerger
  15200. {
  15201. public:
  15202. CRoxieStreamMerger() : CStreamMerger(true)
  15203. {
  15204. streamArray = NULL;
  15205. }
  15206. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  15207. {
  15208. CStreamMerger::initInputs(_numInputs);
  15209. streamArray = _streamArray;
  15210. }
  15211. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  15212. {
  15213. const void * next;
  15214. bool matches = true;
  15215. if (seek)
  15216. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  15217. else
  15218. next = streamArray[i]->ungroupedNextRow();
  15219. pending[i] = next;
  15220. pendingMatches[i] = matches;
  15221. return (next != NULL);
  15222. }
  15223. virtual void releaseRow(const void * row)
  15224. {
  15225. ReleaseRoxieRow(row);
  15226. }
  15227. protected:
  15228. IEngineRowStream **streamArray;
  15229. };
  15230. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  15231. {
  15232. public:
  15233. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15234. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15235. helper((IHThorNWayMergeArg &)basehelper)
  15236. {
  15237. initializedMeta = false;
  15238. }
  15239. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15240. {
  15241. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15242. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  15243. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  15244. }
  15245. virtual void stop()
  15246. {
  15247. merger.done();
  15248. CRoxieServerNaryActivity::stop();
  15249. }
  15250. virtual void reset()
  15251. {
  15252. merger.cleanup();
  15253. CRoxieServerNaryActivity::reset();
  15254. initializedMeta = false;
  15255. }
  15256. virtual const void * nextRow()
  15257. {
  15258. ActivityTimer t(totalCycles, timeActivities);
  15259. const void * next = merger.nextRow();
  15260. if (next)
  15261. processed++;
  15262. return next;
  15263. }
  15264. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15265. {
  15266. ActivityTimer t(totalCycles, timeActivities);
  15267. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15268. if (next)
  15269. processed++;
  15270. return next;
  15271. }
  15272. virtual IInputSteppingMeta * querySteppingMeta()
  15273. {
  15274. if (expandedStreams.ordinality() == 0)
  15275. return NULL;
  15276. if (!initializedMeta)
  15277. {
  15278. meta.init(helper.querySteppingMeta(), false);
  15279. ForEachItemIn(i, expandedStreams)
  15280. {
  15281. if (meta.getNumFields() == 0)
  15282. break;
  15283. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  15284. meta.intersect(inputMeta);
  15285. }
  15286. initializedMeta = true;
  15287. }
  15288. if (meta.getNumFields() == 0)
  15289. return NULL;
  15290. return &meta;
  15291. }
  15292. protected:
  15293. IHThorNWayMergeArg &helper;
  15294. CRoxieStreamMerger merger;
  15295. CSteppingMeta meta;
  15296. bool initializedMeta;
  15297. };
  15298. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15299. {
  15300. public:
  15301. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15302. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15303. {
  15304. }
  15305. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15306. {
  15307. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15308. }
  15309. };
  15310. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15311. {
  15312. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15313. }
  15314. //=================================================================================
  15315. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15316. {
  15317. public:
  15318. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15319. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
  15320. helper((IHThorNWayMergeJoinArg &)basehelper)
  15321. {
  15322. }
  15323. virtual void onCreate(IHThorArg *_colocalParent)
  15324. {
  15325. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15326. ICodeContext * codectx = ctx->queryCodeContext();
  15327. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15328. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15329. }
  15330. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15331. {
  15332. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15333. ForEachItemIn(i1, expandedInputs)
  15334. {
  15335. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15336. processor.addInput(stepInput);
  15337. }
  15338. processor.beforeProcessing(inputAllocator, outputAllocator);
  15339. }
  15340. virtual void stop()
  15341. {
  15342. processor.afterProcessing();
  15343. CRoxieServerNaryActivity::stop();
  15344. }
  15345. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15346. {
  15347. return processor.gatherConjunctions(collector);
  15348. }
  15349. virtual void resetEOF()
  15350. {
  15351. processor.queryResetEOF();
  15352. }
  15353. virtual const void * nextRow()
  15354. {
  15355. ActivityTimer t(totalCycles, timeActivities);
  15356. const void * next = processor.nextRow();
  15357. if (next)
  15358. processed++;
  15359. return next;
  15360. }
  15361. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15362. {
  15363. ActivityTimer t(totalCycles, timeActivities);
  15364. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15365. if (next)
  15366. processed++;
  15367. return next;
  15368. }
  15369. virtual IInputSteppingMeta * querySteppingMeta()
  15370. {
  15371. return processor.queryInputSteppingMeta();
  15372. }
  15373. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15374. {
  15375. CRoxieServerNaryActivity::gatherStats(merged);
  15376. if (inputAllocator)
  15377. inputAllocator->gatherStats(merged);
  15378. if (outputAllocator)
  15379. outputAllocator->gatherStats(merged);
  15380. }
  15381. protected:
  15382. IHThorNWayMergeJoinArg & helper;
  15383. CMergeJoinProcessor & processor;
  15384. Owned<IEngineRowAllocator> inputAllocator;
  15385. Owned<IEngineRowAllocator> outputAllocator;
  15386. };
  15387. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15388. {
  15389. public:
  15390. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15391. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15392. {
  15393. }
  15394. protected:
  15395. CAndMergeJoinProcessor andProcessor;
  15396. };
  15397. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15398. {
  15399. public:
  15400. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15401. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15402. {
  15403. }
  15404. protected:
  15405. CAndLeftMergeJoinProcessor andLeftProcessor;
  15406. };
  15407. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15408. {
  15409. public:
  15410. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15411. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15412. {
  15413. }
  15414. protected:
  15415. CMofNMergeJoinProcessor mofnProcessor;
  15416. };
  15417. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15418. {
  15419. public:
  15420. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15421. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15422. {
  15423. }
  15424. protected:
  15425. CProximityJoinProcessor proximityProcessor;
  15426. };
  15427. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15428. {
  15429. unsigned flags;
  15430. public:
  15431. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15432. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15433. {
  15434. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15435. flags = helper->getJoinFlags();
  15436. }
  15437. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15438. {
  15439. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15440. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15441. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15442. {
  15443. case IHThorNWayMergeJoinArg::MJFinner:
  15444. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15445. case IHThorNWayMergeJoinArg::MJFleftonly:
  15446. case IHThorNWayMergeJoinArg::MJFleftouter:
  15447. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15448. case IHThorNWayMergeJoinArg::MJFmofn:
  15449. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15450. default:
  15451. throwUnexpected();
  15452. }
  15453. }
  15454. };
  15455. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15456. {
  15457. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15458. }
  15459. //=================================================================================
  15460. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15461. {
  15462. IHThorNWaySelectArg &helper;
  15463. public:
  15464. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15465. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15466. helper((IHThorNWaySelectArg &)basehelper)
  15467. {
  15468. }
  15469. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15470. {
  15471. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15472. unsigned whichInput = helper.getInputIndex();
  15473. selectedInput = nullptr;
  15474. selectedStream = nullptr;
  15475. if (whichInput--)
  15476. {
  15477. for (unsigned i=0; i < numInputs; i++)
  15478. {
  15479. IFinalRoxieInput * cur = inputArray[i];
  15480. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15481. if (nWayInput)
  15482. {
  15483. nWayInput->start(parentExtractSize, parentExtract, paused);
  15484. unsigned numRealInputs = cur->numConcreteOutputs();
  15485. if (whichInput < numRealInputs)
  15486. {
  15487. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15488. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15489. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15490. break;
  15491. }
  15492. whichInput -= numRealInputs;
  15493. }
  15494. else
  15495. {
  15496. if (whichInput == 0)
  15497. {
  15498. expandedInputs.append(cur);
  15499. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15500. expandedStreams.append(queryConcreteOutputStream(i));
  15501. expandedJunctions.append(queryConcreteOutputJunction(i));
  15502. break;
  15503. }
  15504. whichInput -= 1;
  15505. }
  15506. }
  15507. }
  15508. if (expandedInputs.ordinality())
  15509. {
  15510. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15511. selectedInput = expandedInputs.item(0);
  15512. selectedStream = expandedStreams.item(0);
  15513. }
  15514. }
  15515. const void * nextRow()
  15516. {
  15517. ActivityTimer t(totalCycles, timeActivities);
  15518. if (!selectedStream)
  15519. return NULL;
  15520. return selectedStream->nextRow();
  15521. }
  15522. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15523. {
  15524. if (!selectedInput)
  15525. return false;
  15526. return selectedInput->gatherConjunctions(collector);
  15527. }
  15528. virtual void resetEOF()
  15529. {
  15530. if (selectedStream)
  15531. selectedStream->resetEOF();
  15532. }
  15533. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15534. {
  15535. ActivityTimer t(totalCycles, timeActivities);
  15536. if (!selectedStream)
  15537. return NULL;
  15538. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15539. }
  15540. IInputSteppingMeta * querySteppingMeta()
  15541. {
  15542. if (selectedInput)
  15543. return selectedInput->querySteppingMeta();
  15544. return NULL;
  15545. }
  15546. protected:
  15547. IFinalRoxieInput * selectedInput = nullptr;
  15548. IEngineRowStream * selectedStream = nullptr;
  15549. Owned<IStrandJunction> selectedJunction;
  15550. };
  15551. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15552. {
  15553. public:
  15554. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15555. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15556. {
  15557. }
  15558. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15559. {
  15560. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15561. }
  15562. };
  15563. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15564. {
  15565. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15566. }
  15567. //=================================================================================
  15568. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15569. {
  15570. protected:
  15571. IHThorRemoteArg &helper;
  15572. CRemoteResultAdaptor remote;
  15573. public:
  15574. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15575. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15576. helper((IHThorRemoteArg &)basehelper),
  15577. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15578. {
  15579. }
  15580. virtual const IResolvedFile *queryVarFileInfo() const
  15581. {
  15582. return NULL;
  15583. }
  15584. virtual void onCreate(IHThorArg *_colocalParent)
  15585. {
  15586. CRoxieServerActivity::onCreate(_colocalParent);
  15587. remote.onCreate(_colocalParent);
  15588. }
  15589. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15590. {
  15591. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15592. remote.onStart(parentExtractSize, parentExtract);
  15593. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15594. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15595. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15596. remote.flush();
  15597. remote.senddone();
  15598. }
  15599. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15600. {
  15601. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15602. }
  15603. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15604. {
  15605. if (idx==(unsigned)-1)
  15606. idx = 0;
  15607. return idx ? NULL: &remote;
  15608. }
  15609. virtual void reset()
  15610. {
  15611. processed = remote.processed;
  15612. remote.processed = 0;
  15613. CRoxieServerActivity::reset();
  15614. }
  15615. virtual void onLimitExceeded(bool isKeyed)
  15616. {
  15617. if (traceLevel > 4)
  15618. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15619. helper.onLimitExceeded();
  15620. }
  15621. virtual const void *createLimitFailRow(bool isKeyed)
  15622. {
  15623. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15624. }
  15625. virtual const void *nextRow()
  15626. {
  15627. throwUnexpected(); // I am nobody's input
  15628. }
  15629. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15630. {
  15631. CRoxieServerActivity::gatherStats(merged);
  15632. remote.gatherStats(merged);
  15633. }
  15634. };
  15635. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15636. {
  15637. public:
  15638. RemoteActivityId remoteId;
  15639. bool isRoot;
  15640. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15641. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15642. {
  15643. }
  15644. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15645. {
  15646. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15647. }
  15648. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15649. {
  15650. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15651. }
  15652. virtual bool isSink() const
  15653. {
  15654. //I don't think the action version of this is implemented - but this would be the code
  15655. return isRoot && !meta.queryOriginal();
  15656. }
  15657. virtual const StatisticsMapping &queryStatsMapping() const
  15658. {
  15659. return allStatistics; // Child queries...
  15660. }
  15661. };
  15662. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15663. {
  15664. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15665. }
  15666. //=================================================================================
  15667. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15668. {
  15669. IHThorIterateArg &helper;
  15670. OwnedConstRoxieRow defaultRecord;
  15671. OwnedConstRoxieRow left;
  15672. OwnedConstRoxieRow right;
  15673. unsigned counter;
  15674. public:
  15675. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15676. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15677. helper((IHThorIterateArg &)basehelper)
  15678. {
  15679. counter = 0;
  15680. }
  15681. virtual bool needsAllocator() const { return true; }
  15682. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15683. {
  15684. counter = 0;
  15685. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15686. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15687. size32_t thisSize = helper.createDefault(rowBuilder);
  15688. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15689. }
  15690. virtual void reset()
  15691. {
  15692. defaultRecord.clear();
  15693. right.clear();
  15694. left.clear();
  15695. CRoxieServerActivity::reset();
  15696. }
  15697. virtual const void * nextRow()
  15698. {
  15699. ActivityTimer t(totalCycles, timeActivities);
  15700. for (;;)
  15701. {
  15702. right.setown(inputStream->nextRow());
  15703. if (!right)
  15704. {
  15705. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15706. left.clear();
  15707. counter = 0;
  15708. if (skippedGroup) continue;
  15709. return NULL;
  15710. }
  15711. try
  15712. {
  15713. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15714. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15715. if (outSize)
  15716. {
  15717. left.setown(rowBuilder.finalizeRowClear(outSize));
  15718. processed++;
  15719. return left.getLink();
  15720. }
  15721. }
  15722. catch (IException *E)
  15723. {
  15724. throw makeWrappedException(E);
  15725. }
  15726. }
  15727. }
  15728. };
  15729. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15730. {
  15731. public:
  15732. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15733. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15734. {
  15735. }
  15736. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15737. {
  15738. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15739. }
  15740. };
  15741. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15742. {
  15743. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15744. }
  15745. //=================================================================================
  15746. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15747. {
  15748. IHThorProcessArg &helper;
  15749. OwnedConstRoxieRow curRight;
  15750. OwnedConstRoxieRow initialRight;
  15751. unsigned counter;
  15752. Owned<IEngineRowAllocator> rightRowAllocator;
  15753. public:
  15754. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15755. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15756. {
  15757. counter = 0;
  15758. }
  15759. virtual bool needsAllocator() const { return true; }
  15760. virtual void onCreate(IHThorArg *_colocalParent)
  15761. {
  15762. CRoxieServerActivity::onCreate(_colocalParent);
  15763. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15764. }
  15765. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15766. {
  15767. counter = 0;
  15768. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15769. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15770. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15771. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15772. curRight.set(initialRight);
  15773. }
  15774. virtual const void * nextRow()
  15775. {
  15776. ActivityTimer t(totalCycles, timeActivities);
  15777. try
  15778. {
  15779. for (;;)
  15780. {
  15781. const void * in = inputStream->nextRow();
  15782. if (!in)
  15783. {
  15784. bool eog = (curRight != initialRight); // processed any records?
  15785. counter = 0;
  15786. curRight.set(initialRight);
  15787. if (eog)
  15788. return NULL;
  15789. in = inputStream->nextRow();
  15790. if (!in)
  15791. return NULL;
  15792. }
  15793. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15794. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15795. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15796. ReleaseRoxieRow(in);
  15797. if (outSize)
  15798. {
  15799. //MORE: This should be returned...
  15800. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15801. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15802. processed++;
  15803. return rowBuilder.finalizeRowClear(outSize);
  15804. }
  15805. }
  15806. }
  15807. catch (IException *E)
  15808. {
  15809. throw makeWrappedException(E);
  15810. }
  15811. }
  15812. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15813. {
  15814. CRoxieServerActivity::gatherStats(merged);
  15815. if (rightRowAllocator)
  15816. rightRowAllocator->gatherStats(merged);
  15817. }
  15818. };
  15819. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15820. {
  15821. public:
  15822. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15823. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15824. {
  15825. }
  15826. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15827. {
  15828. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15829. }
  15830. };
  15831. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15832. {
  15833. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15834. }
  15835. //=================================================================================
  15836. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15837. {
  15838. IHThorGroupArg &helper;
  15839. bool endPending;
  15840. bool eof;
  15841. bool first;
  15842. unsigned numGroups;
  15843. unsigned numGroupMax;
  15844. unsigned numProcessedLastGroup;
  15845. const void *next;
  15846. public:
  15847. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15848. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15849. {
  15850. next = NULL;
  15851. endPending = false;
  15852. eof = false;
  15853. first = true;
  15854. numGroups = 0;
  15855. numGroupMax = 0;
  15856. numProcessedLastGroup = 0;
  15857. }
  15858. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15859. {
  15860. endPending = false;
  15861. eof = false;
  15862. first = true;
  15863. numGroups = 0;
  15864. numGroupMax = 0;
  15865. numProcessedLastGroup = processed;
  15866. assertex(next == NULL);
  15867. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15868. }
  15869. virtual void reset()
  15870. {
  15871. noteStatistic(StNumGroups, numGroups);
  15872. noteStatistic(StNumGroupMax, numGroupMax);
  15873. ReleaseClearRoxieRow(next);
  15874. CRoxieServerActivity::reset();
  15875. }
  15876. virtual const void * nextRow()
  15877. {
  15878. ActivityTimer t(totalCycles, timeActivities);
  15879. if (first)
  15880. {
  15881. next = inputStream->nextRow();
  15882. first = false;
  15883. }
  15884. if (eof || endPending)
  15885. {
  15886. endPending = false;
  15887. return NULL;
  15888. }
  15889. const void * prev = next;
  15890. next = inputStream->ungroupedNextRow();
  15891. if (next)
  15892. {
  15893. assertex(prev);
  15894. if (!helper.isSameGroup(prev, next))
  15895. {
  15896. noteEndOfGroup();
  15897. endPending = true;
  15898. }
  15899. }
  15900. else
  15901. {
  15902. noteEndOfGroup();
  15903. eof = true;
  15904. }
  15905. if (prev)
  15906. processed++;
  15907. return prev;
  15908. }
  15909. inline void noteEndOfGroup()
  15910. {
  15911. unsigned numThisGroup = processed - numProcessedLastGroup;
  15912. if (numThisGroup == 0)
  15913. return;
  15914. numProcessedLastGroup = processed;
  15915. if (numThisGroup > numGroupMax)
  15916. numGroupMax = numThisGroup;
  15917. numGroups++;
  15918. }
  15919. };
  15920. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15921. {
  15922. public:
  15923. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15924. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15925. {
  15926. }
  15927. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15928. {
  15929. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15930. }
  15931. virtual const StatisticsMapping &queryStatsMapping() const
  15932. {
  15933. return groupStatistics;
  15934. }
  15935. };
  15936. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15937. {
  15938. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15939. }
  15940. //=================================================================================
  15941. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15942. {
  15943. unsigned __int64 limit;
  15944. unsigned __int64 skip;
  15945. unsigned doneThisGroup;
  15946. IHThorFirstNArg &helper;
  15947. public:
  15948. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15949. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15950. {
  15951. doneThisGroup = 0;
  15952. limit = 0;
  15953. skip = 0;
  15954. }
  15955. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15956. {
  15957. doneThisGroup = 0;
  15958. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15959. limit = helper.getLimit();
  15960. skip = helper.numToSkip();
  15961. lateStart(parentExtractSize, parentExtract, limit > 0);
  15962. if (limit + skip >= limit)
  15963. limit += skip;
  15964. }
  15965. const void * nextRow()
  15966. {
  15967. ActivityTimer t(totalCycles, timeActivities);
  15968. if (eof)
  15969. return NULL;
  15970. const void *ret;
  15971. for (;;)
  15972. {
  15973. ret = inputStream->nextRow();
  15974. if (!ret)
  15975. {
  15976. if (meta.isGrouped())
  15977. {
  15978. if (doneThisGroup > skip)
  15979. {
  15980. doneThisGroup = 0;
  15981. return NULL;
  15982. }
  15983. doneThisGroup = 0;
  15984. }
  15985. ret = inputStream->nextRow();
  15986. if (!ret)
  15987. {
  15988. eof = true;
  15989. return NULL;
  15990. }
  15991. }
  15992. doneThisGroup++;
  15993. if (doneThisGroup > skip)
  15994. break;
  15995. ReleaseRoxieRow(ret);
  15996. }
  15997. if (doneThisGroup <= limit)
  15998. {
  15999. processed++;
  16000. return ret;
  16001. }
  16002. ReleaseRoxieRow(ret);
  16003. if (meta.isGrouped())
  16004. {
  16005. while ((ret = inputStream->nextRow()) != NULL)
  16006. ReleaseRoxieRow(ret);
  16007. doneThisGroup = 0;
  16008. }
  16009. else
  16010. eof = true;
  16011. return NULL;
  16012. }
  16013. };
  16014. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  16015. {
  16016. public:
  16017. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16018. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16019. {
  16020. }
  16021. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16022. {
  16023. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  16024. }
  16025. };
  16026. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16027. {
  16028. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16029. }
  16030. //=================================================================================
  16031. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  16032. {
  16033. bool done;
  16034. IHThorSelectNArg &helper;
  16035. public:
  16036. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16037. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  16038. {
  16039. done = false;
  16040. }
  16041. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16042. {
  16043. done = false;
  16044. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16045. }
  16046. const void *defaultRow()
  16047. {
  16048. if (!rowAllocator)
  16049. ensureRowAllocator(); // We delay as often not needed...
  16050. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16051. size32_t thisSize = helper.createDefault(rowBuilder);
  16052. return rowBuilder.finalizeRowClear(thisSize);
  16053. }
  16054. virtual const void * nextRow()
  16055. {
  16056. ActivityTimer t(totalCycles, timeActivities);
  16057. if (done)
  16058. return NULL;
  16059. done = true;
  16060. processed++; // always going to return a row!
  16061. unsigned __int64 index = helper.getRowToSelect();
  16062. while (--index)
  16063. {
  16064. const void * next = inputStream->ungroupedNextRow();
  16065. if (!next)
  16066. return defaultRow();
  16067. ReleaseRoxieRow(next);
  16068. }
  16069. const void * next = inputStream->ungroupedNextRow();
  16070. if (!next)
  16071. next = defaultRow();
  16072. return next;
  16073. }
  16074. };
  16075. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  16076. {
  16077. public:
  16078. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16079. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16080. {
  16081. }
  16082. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16083. {
  16084. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  16085. }
  16086. };
  16087. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16088. {
  16089. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16090. }
  16091. //=================================================================================
  16092. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  16093. {
  16094. IHThorJoinArg &helper;
  16095. ICompare *collate;
  16096. OwnedRowArray group;
  16097. bool matchedLeft;
  16098. BoolArray matchedRight;
  16099. bool eof;
  16100. bool first;
  16101. unsigned leftIndex;
  16102. unsigned rightIndex;
  16103. unsigned rightOuterIndex;
  16104. unsigned joinLimit;
  16105. unsigned atmostLimit;
  16106. unsigned atmostsTriggered;
  16107. unsigned abortLimit;
  16108. unsigned keepLimit;
  16109. unsigned joinCounter;
  16110. bool leftOuterJoin;
  16111. bool rightOuterJoin;
  16112. bool exclude;
  16113. bool limitFail;
  16114. bool limitOnFail;
  16115. bool cloneLeft;
  16116. bool forceSpill;
  16117. OwnedConstRoxieRow defaultLeft;
  16118. OwnedConstRoxieRow defaultRight;
  16119. OwnedConstRoxieRow lhs;
  16120. Owned<IException> failingLimit;
  16121. bool failingOuterAtmost;
  16122. Owned<IEngineRowAllocator> defaultAllocator;
  16123. Owned<IRHLimitedCompareHelper> limitedhelper;
  16124. Owned<CRHDualCache> dualcache;
  16125. Owned<IGroupedInput> groupedInput;
  16126. IRowStream *dualCacheInput;
  16127. bool fillGroup()
  16128. {
  16129. group.clear();
  16130. matchedLeft = false;
  16131. matchedRight.kill();
  16132. failingOuterAtmost = false;
  16133. const void * next;
  16134. unsigned groupCount = 0;
  16135. while((next = groupedInput->nextRow()) != NULL)
  16136. {
  16137. if(groupCount==abortLimit)
  16138. {
  16139. if(limitFail)
  16140. failLimit(next);
  16141. if (ctx->queryDebugContext())
  16142. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16143. if(limitOnFail)
  16144. {
  16145. assertex(!failingLimit);
  16146. try
  16147. {
  16148. failLimit(next);
  16149. }
  16150. catch(IException * except)
  16151. {
  16152. failingLimit.setown(except);
  16153. }
  16154. assertex(failingLimit != NULL);
  16155. group.append(next);
  16156. groupCount++;
  16157. break;
  16158. }
  16159. group.clear();
  16160. groupCount = 0;
  16161. while(next)
  16162. {
  16163. ReleaseRoxieRow(next);
  16164. next = groupedInput->nextRow();
  16165. }
  16166. }
  16167. else if(groupCount==atmostLimit)
  16168. {
  16169. atmostsTriggered++;
  16170. if(leftOuterJoin)
  16171. {
  16172. group.append(next);
  16173. groupCount++;
  16174. failingOuterAtmost = true;
  16175. break;
  16176. }
  16177. else
  16178. {
  16179. group.clear();
  16180. groupCount = 0;
  16181. while (next)
  16182. {
  16183. ReleaseRoxieRow(next);
  16184. next = groupedInput->nextRow();
  16185. }
  16186. }
  16187. }
  16188. else
  16189. {
  16190. group.append(next);
  16191. groupCount++;
  16192. }
  16193. }
  16194. if(group.ordinality()==0)
  16195. {
  16196. eof = true;
  16197. return false;
  16198. }
  16199. leftIndex = 0;
  16200. rightIndex = 0;
  16201. rightOuterIndex = 0;
  16202. joinCounter = 0;
  16203. joinLimit = keepLimit;
  16204. ForEachItemIn(idx, group)
  16205. matchedRight.append(false);
  16206. return true;
  16207. }
  16208. void failLimit(const void * next)
  16209. {
  16210. helper.onMatchAbortLimitExceeded();
  16211. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16212. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16213. {
  16214. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  16215. }
  16216. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  16217. }
  16218. virtual bool needsAllocator() const { return true; }
  16219. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except, unsigned flags)
  16220. {
  16221. try
  16222. {
  16223. if (cloneLeft && !except)
  16224. {
  16225. LinkRoxieRow(curLeft);
  16226. return curLeft;
  16227. }
  16228. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16229. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except, flags) : helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  16230. if (outsize)
  16231. return rowBuilder.finalizeRowClear(outsize);
  16232. else
  16233. return NULL;
  16234. }
  16235. catch (IException *E)
  16236. {
  16237. throw makeWrappedException(E);
  16238. }
  16239. }
  16240. void createDefaultLeft()
  16241. {
  16242. if (!defaultLeft)
  16243. {
  16244. if (!defaultAllocator)
  16245. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16246. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16247. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16248. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16249. }
  16250. }
  16251. void createDefaultRight()
  16252. {
  16253. if (!defaultRight)
  16254. {
  16255. if (!defaultAllocator)
  16256. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16257. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16258. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16259. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16260. }
  16261. }
  16262. public:
  16263. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  16264. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  16265. {
  16266. collate = helper.queryCompareLeftRight();
  16267. eof = false;
  16268. first = true;
  16269. keepLimit = 0;
  16270. atmostLimit = 0;
  16271. atmostsTriggered = 0;
  16272. unsigned joinFlags = helper.getJoinFlags();
  16273. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16274. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16275. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16276. exclude = (joinFlags & JFexclude) != 0;
  16277. abortLimit = 0;
  16278. joinLimit = 0;
  16279. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  16280. getLimitType(joinFlags, limitFail, limitOnFail);
  16281. if((joinFlags & JFslidingmatch) != 0)
  16282. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  16283. failingOuterAtmost = false;
  16284. matchedLeft = false;
  16285. leftIndex = 0;
  16286. rightIndex = 0;
  16287. rightOuterIndex = 0;
  16288. joinCounter = 0;
  16289. dualCacheInput = NULL;
  16290. }
  16291. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16292. {
  16293. eof = false;
  16294. first = true;
  16295. failingLimit.clear();
  16296. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16297. keepLimit = helper.getKeepLimit();
  16298. if(keepLimit == 0)
  16299. keepLimit = (unsigned)-1;
  16300. atmostsTriggered = 0;
  16301. atmostLimit = helper.getJoinLimit();
  16302. if(atmostLimit == 0)
  16303. atmostLimit = (unsigned)-1;
  16304. else
  16305. assertex(!rightOuterJoin);
  16306. abortLimit = helper.getMatchAbortLimit();
  16307. if (abortLimit == 0)
  16308. abortLimit = (unsigned)-1;
  16309. if (rightOuterJoin)
  16310. createDefaultLeft();
  16311. if (leftOuterJoin || limitOnFail)
  16312. createDefaultRight();
  16313. ICompare *compareLeft = helper.queryCompareLeft();
  16314. if (helper.isLeftAlreadySorted())
  16315. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16316. else
  16317. {
  16318. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16319. RoxieSortAlgorithm sortAlgorithm;
  16320. if (forceSpill)
  16321. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16322. else
  16323. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16324. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16325. }
  16326. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16327. { //limited match join (s[1..n])
  16328. dualcache.setown(new CRHDualCache());
  16329. dualcache->init(groupedInput);
  16330. dualCacheInput = dualcache->queryOut1();
  16331. failingOuterAtmost = false;
  16332. matchedLeft = false;
  16333. leftIndex = 0;
  16334. rightOuterIndex = 0;
  16335. joinCounter = 0;
  16336. limitedhelper.setown(createRHLimitedCompareHelper());
  16337. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16338. }
  16339. }
  16340. virtual void reset()
  16341. {
  16342. if (atmostsTriggered)
  16343. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16344. group.clear();
  16345. groupedInput.clear();
  16346. CRoxieServerActivity::reset();
  16347. defaultLeft.clear();
  16348. defaultRight.clear();
  16349. }
  16350. virtual const void * nextRow()
  16351. {
  16352. ActivityTimer t(totalCycles, timeActivities);
  16353. if (limitedhelper)
  16354. {
  16355. while(!eof) //limited match join
  16356. {
  16357. if (!group.isItem(rightIndex))
  16358. {
  16359. lhs.setown(dualCacheInput->nextRow());
  16360. if (lhs)
  16361. {
  16362. rightIndex = 0;
  16363. joinCounter = 0;
  16364. group.clear();
  16365. limitedhelper->getGroup(group,lhs);
  16366. }
  16367. else
  16368. {
  16369. eof = true;
  16370. }
  16371. }
  16372. if (group.isItem(rightIndex))
  16373. {
  16374. const void * rhs = group.item(rightIndex++);
  16375. if(helper.match(lhs, rhs))
  16376. {
  16377. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16378. if(ret)
  16379. {
  16380. processed++;
  16381. return ret;
  16382. }
  16383. }
  16384. }
  16385. }
  16386. return NULL;
  16387. }
  16388. else
  16389. {
  16390. if (first)
  16391. {
  16392. first = false;
  16393. fillGroup();
  16394. }
  16395. while(!eof)
  16396. {
  16397. if(failingOuterAtmost)
  16398. while(group.isItem(leftIndex))
  16399. {
  16400. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL, JTFmatchedleft);
  16401. if(ret)
  16402. {
  16403. processed++;
  16404. return ret;
  16405. }
  16406. }
  16407. if((joinLimit == 0) || !group.isItem(rightIndex))
  16408. {
  16409. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16410. {
  16411. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL, JTFmatchedleft);
  16412. if(ret)
  16413. {
  16414. matchedLeft = true;
  16415. processed++;
  16416. return ret;
  16417. }
  16418. }
  16419. leftIndex++;
  16420. matchedLeft = false;
  16421. rightIndex = 0;
  16422. joinCounter = 0;
  16423. joinLimit = keepLimit;
  16424. }
  16425. if(!group.isItem(leftIndex))
  16426. {
  16427. if(failingLimit || failingOuterAtmost)
  16428. {
  16429. const void * lhs;
  16430. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16431. {
  16432. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16433. ReleaseRoxieRow(lhs);
  16434. if(ret)
  16435. {
  16436. processed++;
  16437. return ret;
  16438. }
  16439. }
  16440. failingLimit.clear();
  16441. }
  16442. if(rightOuterJoin && !failingLimit)
  16443. while(group.isItem(rightOuterIndex))
  16444. if(!matchedRight.item(rightOuterIndex++))
  16445. {
  16446. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL, JTFmatchedright);
  16447. if(ret)
  16448. {
  16449. processed++;
  16450. return ret;
  16451. }
  16452. }
  16453. if(!fillGroup())
  16454. return NULL;
  16455. continue;
  16456. }
  16457. const void * lhs = group.item(leftIndex);
  16458. if(failingLimit)
  16459. {
  16460. leftIndex++;
  16461. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16462. if(ret)
  16463. {
  16464. processed++;
  16465. return ret;
  16466. }
  16467. }
  16468. else
  16469. {
  16470. const void * rhs = group.item(rightIndex++);
  16471. if(helper.match(lhs, rhs))
  16472. {
  16473. matchedLeft = true;
  16474. matchedRight.replace(true, rightIndex-1);
  16475. if(!exclude)
  16476. {
  16477. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16478. if(ret)
  16479. {
  16480. processed++;
  16481. joinLimit--;
  16482. return ret;
  16483. }
  16484. }
  16485. }
  16486. }
  16487. }
  16488. return NULL;
  16489. }
  16490. }
  16491. };
  16492. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16493. {
  16494. bool forceSpill;
  16495. public:
  16496. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16497. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16498. {
  16499. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16500. }
  16501. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16502. {
  16503. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16504. }
  16505. virtual const StatisticsMapping &queryStatsMapping() const
  16506. {
  16507. return joinStatistics;
  16508. }
  16509. };
  16510. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16511. {
  16512. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16513. }
  16514. //=====================================================================================================
  16515. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16516. {
  16517. private:
  16518. class LookupTable : public CInterface
  16519. {
  16520. public:
  16521. LookupTable(IHThorHashJoinArg &helper)
  16522. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16523. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16524. {
  16525. size = 0;
  16526. }
  16527. virtual const void *find(const void * left) const = 0;
  16528. virtual const void *findNext(const void * left) const = 0;
  16529. protected:
  16530. ICompare * leftRightCompare;
  16531. ICompare * rightCompare;
  16532. IHash * leftHash;
  16533. IHash * rightHash;
  16534. unsigned size;
  16535. };
  16536. class DedupLookupTable : public LookupTable
  16537. {
  16538. public:
  16539. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16540. : LookupTable(helper)
  16541. {
  16542. size = (4*rightRows.length())/3 + 1;
  16543. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16544. ForEachItemIn(idx, rightRows)
  16545. add(rightRows.item(idx));
  16546. }
  16547. ~DedupLookupTable()
  16548. {
  16549. roxiemem::ReleaseRoxieRowArray(size, table);
  16550. free(table);
  16551. }
  16552. virtual const void *find(const void * left) const
  16553. {
  16554. unsigned index = leftHash->hash(left) % size;
  16555. unsigned start = index;
  16556. while (table[index])
  16557. {
  16558. if(leftRightCompare->docompare(left, table[index]) == 0)
  16559. return table[index];
  16560. index++;
  16561. if (index==size)
  16562. index = 0;
  16563. if (index==start)
  16564. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16565. }
  16566. return NULL;
  16567. }
  16568. virtual const void *findNext(const void * left) const
  16569. {
  16570. return NULL;
  16571. }
  16572. protected:
  16573. void add(const void * right)
  16574. {
  16575. unsigned index = rightHash->hash(right) % size;
  16576. unsigned start = index;
  16577. while (table[index])
  16578. {
  16579. if (rightCompare->docompare(table[index], right) == 0)
  16580. {
  16581. ReleaseRoxieRow(right);
  16582. return;
  16583. }
  16584. index++;
  16585. if (index==size)
  16586. index = 0;
  16587. if (index==start)
  16588. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16589. }
  16590. table[index] = right;
  16591. }
  16592. const void * * table;
  16593. };
  16594. class FewLookupTable : public LookupTable
  16595. {
  16596. public:
  16597. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16598. : LookupTable(helper)
  16599. {
  16600. size = (4*rightRows.length())/3 + 1;
  16601. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16602. findex = fstart = BadIndex;
  16603. ForEachItemIn(idx, rightRows)
  16604. add(rightRows.item(idx));
  16605. }
  16606. ~FewLookupTable()
  16607. {
  16608. roxiemem::ReleaseRoxieRowArray(size, table);
  16609. free(table);
  16610. }
  16611. virtual const void *find(const void * left) const
  16612. {
  16613. fstart = leftHash->hash(left) % size;
  16614. findex = fstart;
  16615. return doFind(left);
  16616. }
  16617. virtual const void *findNext(const void * left) const
  16618. {
  16619. if (findex == BadIndex)
  16620. return NULL;
  16621. advance();
  16622. return doFind(left);
  16623. }
  16624. protected:
  16625. void add(const void * right)
  16626. {
  16627. unsigned start = rightHash->hash(right) % size;
  16628. unsigned index = start;
  16629. while (table[index])
  16630. {
  16631. index++;
  16632. if (index==size)
  16633. index = 0;
  16634. if (index==start)
  16635. throwUnexpected(); //table is full, should never happen
  16636. }
  16637. table[index] = right;
  16638. }
  16639. void advance() const
  16640. {
  16641. findex++;
  16642. if(findex==size)
  16643. findex = 0;
  16644. if(findex==fstart)
  16645. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16646. }
  16647. const void *doFind(const void * left) const
  16648. {
  16649. while(table[findex])
  16650. {
  16651. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16652. return table[findex];
  16653. advance();
  16654. }
  16655. findex = BadIndex;
  16656. return NULL;
  16657. }
  16658. const void * * table;
  16659. unsigned mutable fstart;
  16660. unsigned mutable findex;
  16661. static unsigned const BadIndex;
  16662. };
  16663. class ManyLookupTable : public LookupTable
  16664. {
  16665. public:
  16666. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16667. : LookupTable(helper)
  16668. {
  16669. rightRows.swapWith(rowtable);
  16670. UInt64Array groups;
  16671. unsigned numRows = rowtable.length();
  16672. if (numRows)
  16673. {
  16674. unsigned groupStart = 0;
  16675. const void *groupStartRow = rowtable.item(0);
  16676. for (unsigned i=1; i < numRows; i++)
  16677. {
  16678. const void *thisRow = rowtable.item(i);
  16679. if (rightCompare->docompare(groupStartRow, thisRow))
  16680. {
  16681. groups.append(makeint64(groupStart, i-groupStart));
  16682. groupStart = i;
  16683. groupStartRow = thisRow;
  16684. }
  16685. }
  16686. groups.append(makeint64(groupStart, numRows-groupStart));
  16687. }
  16688. size = (4*groups.length())/3 + 1;
  16689. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16690. ForEachItemIn(idx, groups)
  16691. {
  16692. unsigned __int64 group = groups.item(idx);
  16693. unsigned groupstart = high(group);
  16694. const void *row = rowtable.item(groupstart);
  16695. add(row, group);
  16696. }
  16697. }
  16698. ~ManyLookupTable()
  16699. {
  16700. roxiemem::ReleaseRoxieRows(rowtable);
  16701. free(table);
  16702. }
  16703. void add(const void *row, unsigned __int64 group)
  16704. {
  16705. unsigned start = rightHash->hash(row) % size;
  16706. unsigned index = start;
  16707. while (table[index])
  16708. {
  16709. index++;
  16710. if (index==size)
  16711. index = 0;
  16712. if (index==start)
  16713. throwUnexpected(); //table is full, should never happen
  16714. }
  16715. table[index] = group;
  16716. }
  16717. virtual const void *find(const void * left) const
  16718. {
  16719. unsigned index = leftHash->hash(left) % size;
  16720. unsigned start = index;
  16721. while (table[index])
  16722. {
  16723. __uint64 group = table[index];
  16724. currentMatch = high(group);
  16725. const void *right = rowtable.item(currentMatch);
  16726. if (leftRightCompare->docompare(left, right) == 0)
  16727. {
  16728. currentMatch++;
  16729. matchCount = low(group) - 1;
  16730. return right;
  16731. }
  16732. index++;
  16733. if (index==size)
  16734. index = 0;
  16735. if (index==start)
  16736. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16737. }
  16738. matchCount = 0;
  16739. return NULL;
  16740. }
  16741. virtual const void *findNext(const void * left) const
  16742. {
  16743. if (!matchCount)
  16744. return NULL;
  16745. matchCount--;
  16746. return rowtable.item(currentMatch++);
  16747. }
  16748. protected:
  16749. __uint64 *table;
  16750. ConstPointerArray rowtable;
  16751. mutable unsigned currentMatch = 0;
  16752. mutable unsigned matchCount = 0;
  16753. };
  16754. IHThorHashJoinArg &helper;
  16755. bool leftOuterJoin;
  16756. bool exclude;
  16757. bool eog;
  16758. bool many;
  16759. bool dedupRHS;
  16760. bool useFewTable;
  16761. bool matchedGroup;
  16762. const void *left;
  16763. OwnedConstRoxieRow defaultRight;
  16764. Owned<LookupTable> table;
  16765. unsigned keepLimit;
  16766. unsigned atmostLimit;
  16767. unsigned atmostsTriggered;
  16768. unsigned limitLimit;
  16769. unsigned joinCounter;
  16770. bool limitFail;
  16771. bool limitOnFail;
  16772. bool hasGroupLimit;
  16773. bool isSmartJoin;
  16774. unsigned keepCount;
  16775. bool gotMatch;
  16776. bool cloneLeft;
  16777. ConstPointerArray rightGroup;
  16778. aindex_t rightGroupIndex;
  16779. Owned<IException> failingLimit;
  16780. ConstPointerArray filteredRight;
  16781. ThorActivityKind activityKind;
  16782. Owned<IEngineRowAllocator> defaultRightAllocator;
  16783. void createDefaultRight()
  16784. {
  16785. if (!defaultRight)
  16786. {
  16787. if (!defaultRightAllocator)
  16788. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16789. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16790. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16791. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16792. }
  16793. }
  16794. public:
  16795. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16796. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16797. {
  16798. unsigned joinFlags = helper.getJoinFlags();
  16799. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16800. assertex((joinFlags & JFrightouter) == 0);
  16801. exclude = (joinFlags & JFexclude) != 0;
  16802. many = (joinFlags & JFmanylookup) != 0;
  16803. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16804. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16805. left = NULL;
  16806. activityKind = factory->getKind();
  16807. eog = false;
  16808. matchedGroup = false;
  16809. gotMatch = false;
  16810. keepLimit = 0;
  16811. keepCount = 0;
  16812. joinCounter = 0;
  16813. atmostLimit = 0;
  16814. atmostsTriggered = 0;
  16815. limitLimit = 0;
  16816. rightGroupIndex = 0;
  16817. hasGroupLimit = false;
  16818. isSmartJoin = (joinFlags & JFsmart) != 0;
  16819. getLimitType(joinFlags, limitFail, limitOnFail);
  16820. }
  16821. void loadRight()
  16822. {
  16823. ConstPointerArray rightset;
  16824. try
  16825. {
  16826. const void * next;
  16827. while(true)
  16828. {
  16829. next = inputStream1->ungroupedNextRow();
  16830. if(!next)
  16831. break;
  16832. rightset.append(next);
  16833. }
  16834. if (!dedupRHS)
  16835. {
  16836. if (useFewTable)
  16837. {
  16838. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16839. }
  16840. else
  16841. {
  16842. if (!helper.isRightAlreadySorted())
  16843. {
  16844. if (helper.getJoinFlags() & JFunstable)
  16845. {
  16846. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16847. }
  16848. else
  16849. {
  16850. unsigned rightord = rightset.ordinality();
  16851. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16852. void **temp = (void **) tempAttr.bufferBase();
  16853. void **_rows = const_cast<void * *>(rightset.getArray());
  16854. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16855. }
  16856. }
  16857. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16858. }
  16859. }
  16860. else
  16861. {
  16862. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16863. }
  16864. }
  16865. catch (...)
  16866. {
  16867. roxiemem::ReleaseRoxieRows(rightset);
  16868. throw;
  16869. }
  16870. };
  16871. virtual void reset()
  16872. {
  16873. if (atmostsTriggered)
  16874. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16875. CRoxieServerTwoInputActivity::reset();
  16876. ReleaseClearRoxieRow(left);
  16877. defaultRight.clear();
  16878. table.clear();
  16879. }
  16880. virtual bool needsAllocator() const { return true; }
  16881. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16882. {
  16883. eog = false;
  16884. matchedGroup = false;
  16885. left = NULL;
  16886. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16887. keepLimit = helper.getKeepLimit();
  16888. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16889. atmostsTriggered = 0;
  16890. atmostLimit = helper.getJoinLimit();
  16891. limitLimit = helper.getMatchAbortLimit();
  16892. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16893. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16894. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16895. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16896. switch (activityKind)
  16897. {
  16898. case TAKlookupjoin:
  16899. case TAKlookupdenormalizegroup:
  16900. case TAKsmartjoin:
  16901. case TAKsmartdenormalizegroup:
  16902. if (leftOuterJoin)
  16903. createDefaultRight();
  16904. break;
  16905. }
  16906. if (limitOnFail)
  16907. createDefaultRight();
  16908. }
  16909. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16910. {
  16911. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16912. {
  16913. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16914. puller->setInput(0, _sourceIdx, _in);
  16915. _in = puller;
  16916. _sourceIdx = 0;
  16917. }
  16918. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16919. }
  16920. virtual const void * nextRow()
  16921. {
  16922. ActivityTimer t(totalCycles, timeActivities);
  16923. if(!table)
  16924. loadRight();
  16925. switch (activityKind)
  16926. {
  16927. case TAKlookupjoin:
  16928. case TAKsmartjoin:
  16929. return nextRowJoin();
  16930. case TAKlookupdenormalize:
  16931. case TAKlookupdenormalizegroup:
  16932. case TAKsmartdenormalize:
  16933. case TAKsmartdenormalizegroup:
  16934. return nextRowDenormalize();
  16935. }
  16936. throwUnexpected();
  16937. }
  16938. private:
  16939. const void * nextRowJoin()
  16940. {
  16941. if(!table)
  16942. loadRight();
  16943. while(true)
  16944. {
  16945. const void * right = NULL;
  16946. if(!left)
  16947. {
  16948. left = inputStream->nextRow();
  16949. keepCount = keepLimit;
  16950. joinCounter = 0;
  16951. if(!left)
  16952. {
  16953. if (isSmartJoin)
  16954. left = inputStream->nextRow();
  16955. if (!left)
  16956. {
  16957. if(matchedGroup || eog)
  16958. {
  16959. matchedGroup = false;
  16960. eog = true;
  16961. return NULL;
  16962. }
  16963. eog = true;
  16964. continue;
  16965. }
  16966. }
  16967. eog = false;
  16968. gotMatch = false;
  16969. right = getRightFirst();
  16970. }
  16971. else
  16972. right = getRightNext();
  16973. const void * ret = NULL;
  16974. if(failingLimit)
  16975. {
  16976. ret = joinException(left, failingLimit);
  16977. }
  16978. else
  16979. {
  16980. while(right)
  16981. {
  16982. if(helper.match(left, right))
  16983. {
  16984. gotMatch = true;
  16985. if(exclude)
  16986. break;
  16987. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  16988. if(ret)
  16989. {
  16990. processed++;
  16991. break;
  16992. }
  16993. }
  16994. right = getRightNext();
  16995. ret = NULL;
  16996. }
  16997. if(leftOuterJoin && !gotMatch)
  16998. {
  16999. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17000. gotMatch = true;
  17001. }
  17002. }
  17003. if(ret)
  17004. {
  17005. matchedGroup = true;
  17006. processed++;
  17007. if(!many || (--keepCount == 0) || failingLimit)
  17008. {
  17009. ReleaseClearRoxieRow(left);
  17010. failingLimit.clear();
  17011. }
  17012. return ret;
  17013. }
  17014. ReleaseClearRoxieRow(left);
  17015. }
  17016. }
  17017. const void * nextRowDenormalize()
  17018. {
  17019. while(true)
  17020. {
  17021. left = inputStream->nextRow();
  17022. if(!left)
  17023. {
  17024. if (!matchedGroup || isSmartJoin)
  17025. left = inputStream->nextRow();
  17026. if (!left)
  17027. {
  17028. matchedGroup = false;
  17029. return NULL;
  17030. }
  17031. }
  17032. gotMatch = false;
  17033. const void * right = getRightFirst();
  17034. const void * ret = NULL;
  17035. if (failingLimit)
  17036. ret = joinException(left, failingLimit);
  17037. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  17038. {
  17039. OwnedConstRoxieRow newLeft;
  17040. newLeft.set(left);
  17041. unsigned rowSize = 0;
  17042. unsigned leftCount = 0;
  17043. keepCount = keepLimit;
  17044. while (right)
  17045. {
  17046. try
  17047. {
  17048. if (helper.match(left, right))
  17049. {
  17050. gotMatch = true;
  17051. if (exclude)
  17052. break;
  17053. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17054. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17055. if (thisSize)
  17056. {
  17057. rowSize = thisSize;
  17058. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17059. }
  17060. if(!many || (--keepCount == 0))
  17061. break;
  17062. }
  17063. right = getRightNext();
  17064. }
  17065. catch (IException *E)
  17066. {
  17067. throw makeWrappedException(E);
  17068. }
  17069. }
  17070. if (rowSize)
  17071. ret = newLeft.getClear();
  17072. else if (leftOuterJoin && !gotMatch)
  17073. {
  17074. ret = left;
  17075. left = NULL;
  17076. }
  17077. }
  17078. else
  17079. {
  17080. filteredRight.kill();
  17081. keepCount = keepLimit;
  17082. while (right)
  17083. {
  17084. if (helper.match(left, right))
  17085. {
  17086. gotMatch = true;
  17087. if(exclude)
  17088. break;
  17089. filteredRight.append(right);
  17090. if(!many || (--keepCount == 0))
  17091. break;
  17092. }
  17093. right = getRightNext();
  17094. }
  17095. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  17096. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17097. filteredRight.kill();
  17098. }
  17099. ReleaseRoxieRow(left);
  17100. left = NULL;
  17101. failingLimit.clear();
  17102. if(ret)
  17103. {
  17104. matchedGroup = true;
  17105. processed++;
  17106. return ret;
  17107. }
  17108. }
  17109. }
  17110. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17111. {
  17112. if (cloneLeft)
  17113. {
  17114. LinkRoxieRow(left);
  17115. return left;
  17116. }
  17117. try
  17118. {
  17119. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17120. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17121. if (outSize)
  17122. return rowBuilder.finalizeRowClear(outSize);
  17123. else
  17124. return NULL;
  17125. }
  17126. catch (IException *E)
  17127. {
  17128. throw makeWrappedException(E);
  17129. }
  17130. }
  17131. const void * joinException(const void * left, IException * except)
  17132. {
  17133. try
  17134. {
  17135. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17136. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except, JTFmatchedleft);
  17137. if (outSize)
  17138. return rowBuilder.finalizeRowClear(outSize);
  17139. else
  17140. return NULL;
  17141. }
  17142. catch (IException *E)
  17143. {
  17144. throw makeWrappedException(E);
  17145. }
  17146. }
  17147. const void * denormalizeRecords(const void * left, ConstPointerArray & rows, unsigned flags)
  17148. {
  17149. try
  17150. {
  17151. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17152. unsigned numRows = rows.ordinality();
  17153. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17154. if (numRows>0)
  17155. flags |= JTFmatchedright;
  17156. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray(), flags);
  17157. if (outSize)
  17158. return rowBuilder.finalizeRowClear(outSize);
  17159. else
  17160. return NULL;
  17161. }
  17162. catch (IException *E)
  17163. {
  17164. throw makeWrappedException(E);
  17165. }
  17166. }
  17167. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  17168. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  17169. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  17170. const void *fillRightGroup()
  17171. {
  17172. rightGroup.kill();
  17173. for(const void * right = table->find(left); right; right = table->findNext(left))
  17174. {
  17175. rightGroup.append(right);
  17176. if(rightGroup.ordinality() > limitLimit)
  17177. {
  17178. if(limitFail)
  17179. failLimit();
  17180. gotMatch = true;
  17181. if (ctx->queryDebugContext())
  17182. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17183. if(limitOnFail)
  17184. {
  17185. assertex(!failingLimit);
  17186. try
  17187. {
  17188. failLimit();
  17189. }
  17190. catch(IException * e)
  17191. {
  17192. failingLimit.setown(e);
  17193. }
  17194. assertex(failingLimit != NULL);
  17195. }
  17196. else
  17197. {
  17198. rightGroup.kill();
  17199. }
  17200. break;
  17201. }
  17202. if(rightGroup.ordinality() > atmostLimit)
  17203. {
  17204. atmostsTriggered++;
  17205. rightGroup.kill();
  17206. break;
  17207. }
  17208. }
  17209. rightGroupIndex = 0;
  17210. return readRightGroup();
  17211. }
  17212. void failLimit()
  17213. {
  17214. helper.onMatchAbortLimitExceeded();
  17215. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  17216. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  17217. {
  17218. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  17219. }
  17220. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  17221. }
  17222. };
  17223. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  17224. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17225. {
  17226. public:
  17227. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17228. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17229. {
  17230. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  17231. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  17232. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  17233. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  17234. }
  17235. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17236. {
  17237. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  17238. }
  17239. virtual const StatisticsMapping &queryStatsMapping() const
  17240. {
  17241. return joinStatistics;
  17242. }
  17243. protected:
  17244. bool useFewTable;
  17245. };
  17246. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17247. {
  17248. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17249. }
  17250. //=====================================================================================================
  17251. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  17252. {
  17253. private:
  17254. IHThorAllJoinArg &helper;
  17255. bool leftOuterJoin;
  17256. bool rightOuterJoin;
  17257. bool exclude;
  17258. OwnedConstRoxieRow defaultRight;
  17259. OwnedConstRoxieRow defaultLeft;
  17260. Owned<IEngineRowAllocator> defaultRightAllocator;
  17261. Owned<IEngineRowAllocator> defaultLeftAllocator;
  17262. const void *left;
  17263. unsigned countForLeft;
  17264. ConstPointerArray rightset;
  17265. BoolArray matchedRight; // MORE - could use a bitset...
  17266. unsigned keepLimit;
  17267. bool started;
  17268. bool eog;
  17269. bool eos;
  17270. bool matchedLeft;
  17271. bool matchedGroup;
  17272. bool leftIsGrouped;
  17273. bool cloneLeft;
  17274. unsigned rightIndex;
  17275. unsigned joinCounter;
  17276. unsigned rightOrdinality;
  17277. ThorActivityKind activityKind;
  17278. ConstPointerArray filteredRight;
  17279. void createDefaultLeft()
  17280. {
  17281. if (!defaultLeft)
  17282. {
  17283. if (!defaultLeftAllocator)
  17284. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  17285. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  17286. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  17287. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  17288. }
  17289. }
  17290. void createDefaultRight()
  17291. {
  17292. if (!defaultRight)
  17293. {
  17294. if (!defaultRightAllocator)
  17295. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17296. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17297. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17298. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17299. }
  17300. }
  17301. public:
  17302. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17303. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17304. {
  17305. unsigned joinFlags = helper.getJoinFlags();
  17306. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17307. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17308. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17309. keepLimit = (unsigned) -1;
  17310. exclude = (joinFlags & JFexclude) != 0;
  17311. left = NULL;
  17312. started = true;
  17313. eog = false;
  17314. eos = false;
  17315. matchedLeft = false;
  17316. matchedGroup = false;
  17317. activityKind = factory->getKind();
  17318. rightIndex = 0;
  17319. rightOrdinality = 0;
  17320. leftIsGrouped = false;
  17321. countForLeft = 0;
  17322. joinCounter = 0;
  17323. }
  17324. virtual void reset()
  17325. {
  17326. defaultRight.clear();
  17327. defaultLeft.clear();
  17328. ReleaseRoxieRows(rightset);
  17329. matchedRight.kill();
  17330. CRoxieServerTwoInputActivity::reset();
  17331. }
  17332. virtual bool needsAllocator() const { return true; }
  17333. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17334. {
  17335. eog = false;
  17336. eos = false;
  17337. matchedLeft = false;
  17338. matchedGroup = false;
  17339. started = false;
  17340. left = NULL;
  17341. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17342. keepLimit = helper.getKeepLimit();
  17343. if(keepLimit==0)
  17344. keepLimit = (unsigned) -1;
  17345. countForLeft = keepLimit;
  17346. joinCounter = 0;
  17347. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17348. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17349. createDefaultRight();
  17350. if(rightOuterJoin)
  17351. createDefaultLeft();
  17352. }
  17353. void loadRight()
  17354. {
  17355. const void * next;
  17356. while(true)
  17357. {
  17358. next = inputStream1->ungroupedNextRow();
  17359. if(!next)
  17360. break;
  17361. rightset.append(next);
  17362. matchedRight.append(false);
  17363. }
  17364. rightIndex = 0;
  17365. joinCounter = 0;
  17366. rightOrdinality = rightset.ordinality();
  17367. }
  17368. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17369. {
  17370. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17371. {
  17372. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17373. puller->setInput(0, _sourceIdx, _in);
  17374. _in = puller;
  17375. _sourceIdx = 0;
  17376. }
  17377. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17378. }
  17379. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17380. {
  17381. // MORE - could share some code with lookup join
  17382. if (cloneLeft)
  17383. {
  17384. LinkRoxieRow(left);
  17385. return left;
  17386. }
  17387. try
  17388. {
  17389. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17390. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17391. if (outSize)
  17392. return rowBuilder.finalizeRowClear(outSize);
  17393. else
  17394. return NULL;
  17395. }
  17396. catch (IException *E)
  17397. {
  17398. throw makeWrappedException(E);
  17399. }
  17400. }
  17401. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  17402. {
  17403. try
  17404. {
  17405. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17406. unsigned numRows = rows.ordinality();
  17407. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17408. if (numRows>0)
  17409. flags |= JTFmatchedright;
  17410. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray(), flags);
  17411. if (outSize)
  17412. return rowBuilder.finalizeRowClear(outSize);
  17413. else
  17414. return NULL;
  17415. }
  17416. catch (IException *E)
  17417. {
  17418. throw makeWrappedException(E);
  17419. }
  17420. }
  17421. virtual const void *nextRow()
  17422. {
  17423. ActivityTimer t(totalCycles, timeActivities);
  17424. if(!started)
  17425. {
  17426. started = true;
  17427. left = inputStream->nextRow();
  17428. matchedLeft = false;
  17429. countForLeft = keepLimit;
  17430. joinCounter = 0;
  17431. if(left == NULL)
  17432. {
  17433. eos = true;
  17434. return NULL;
  17435. }
  17436. loadRight();
  17437. }
  17438. const void * ret;
  17439. const void * right;
  17440. if(eos)
  17441. return NULL;
  17442. while(true)
  17443. {
  17444. ret = NULL;
  17445. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17446. {
  17447. if(leftOuterJoin && left && !matchedLeft)
  17448. {
  17449. switch(activityKind)
  17450. {
  17451. case TAKalljoin:
  17452. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17453. break;
  17454. case TAKalldenormalize:
  17455. ret = left;
  17456. left = NULL;
  17457. break;
  17458. case TAKalldenormalizegroup:
  17459. filteredRight.kill();
  17460. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17461. break;
  17462. default:
  17463. throwUnexpected();
  17464. }
  17465. }
  17466. rightIndex = 0;
  17467. joinCounter = 0;
  17468. ReleaseRoxieRow(left);
  17469. left = NULL;
  17470. if(ret)
  17471. {
  17472. matchedGroup = true;
  17473. processed++;
  17474. return ret;
  17475. }
  17476. }
  17477. if(!left)
  17478. {
  17479. left = inputStream->nextRow();
  17480. matchedLeft = false;
  17481. countForLeft = keepLimit;
  17482. joinCounter = 0;
  17483. }
  17484. if(!left)
  17485. {
  17486. if(eog)
  17487. {
  17488. eos = true;
  17489. matchedGroup = false;
  17490. return NULL;
  17491. }
  17492. eog = true;
  17493. if (matchedGroup && leftIsGrouped)
  17494. {
  17495. matchedGroup = false;
  17496. return NULL;
  17497. }
  17498. matchedGroup = false;
  17499. continue;
  17500. }
  17501. eog = false;
  17502. switch(activityKind)
  17503. {
  17504. case TAKalljoin:
  17505. while(rightIndex < rightOrdinality)
  17506. {
  17507. right = rightset.item(rightIndex);
  17508. if(helper.match(left, right))
  17509. {
  17510. matchedLeft = true;
  17511. matchedRight.replace(true, rightIndex);
  17512. if(!exclude)
  17513. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17514. }
  17515. rightIndex++;
  17516. if(ret)
  17517. {
  17518. countForLeft--;
  17519. matchedGroup = true;
  17520. processed++;
  17521. return ret;
  17522. }
  17523. }
  17524. break;
  17525. case TAKalldenormalize:
  17526. {
  17527. OwnedConstRoxieRow newLeft;
  17528. newLeft.set(left);
  17529. unsigned rowSize = 0;
  17530. unsigned leftCount = 0;
  17531. while((rightIndex < rightOrdinality) && countForLeft)
  17532. {
  17533. right = rightset.item(rightIndex);
  17534. if(helper.match(left, right))
  17535. {
  17536. matchedLeft = true;
  17537. matchedRight.replace(true, rightIndex);
  17538. if(!exclude)
  17539. {
  17540. try
  17541. {
  17542. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17543. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17544. if(thisSize)
  17545. {
  17546. rowSize = thisSize;
  17547. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17548. --countForLeft;
  17549. }
  17550. }
  17551. catch (IException *e)
  17552. {
  17553. throw makeWrappedException(e);
  17554. }
  17555. }
  17556. }
  17557. rightIndex++;
  17558. }
  17559. if(rowSize)
  17560. {
  17561. processed++;
  17562. return newLeft.getClear();
  17563. }
  17564. }
  17565. break;
  17566. case TAKalldenormalizegroup:
  17567. filteredRight.kill();
  17568. while((rightIndex < rightOrdinality) && countForLeft)
  17569. {
  17570. right = rightset.item(rightIndex);
  17571. if(helper.match(left, right))
  17572. {
  17573. matchedLeft = true;
  17574. matchedRight.replace(true, rightIndex);
  17575. filteredRight.append(right);
  17576. --countForLeft;
  17577. }
  17578. ++rightIndex;
  17579. }
  17580. if(!exclude && filteredRight.ordinality())
  17581. {
  17582. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17583. filteredRight.kill();
  17584. if(ret)
  17585. {
  17586. processed++;
  17587. return ret;
  17588. }
  17589. }
  17590. break;
  17591. default:
  17592. throwUnexpected();
  17593. }
  17594. }
  17595. }
  17596. };
  17597. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17598. {
  17599. public:
  17600. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17601. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17602. {
  17603. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17604. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17605. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17606. }
  17607. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17608. {
  17609. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17610. }
  17611. virtual const StatisticsMapping &queryStatsMapping() const
  17612. {
  17613. return joinStatistics;
  17614. }
  17615. };
  17616. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17617. {
  17618. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17619. }
  17620. //=====================================================================================================
  17621. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17622. {
  17623. unsigned limit;
  17624. bool hasBest;
  17625. bool eoi;
  17626. const void **sorted;
  17627. unsigned sortedCount;
  17628. unsigned curIndex;
  17629. IHThorTopNArg &helper;
  17630. ICompare &compare;
  17631. public:
  17632. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17633. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17634. {
  17635. sorted = NULL;
  17636. sortedCount = 0;
  17637. curIndex = 0;
  17638. limit = 0;
  17639. eoi = false;
  17640. hasBest = false;
  17641. }
  17642. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17643. {
  17644. assertex(sorted == NULL);
  17645. sortedCount = 0;
  17646. curIndex = 0;
  17647. eoi = false;
  17648. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17649. limit = (unsigned) helper.getLimit();
  17650. hasBest = helper.hasBest();
  17651. lateStart(parentExtractSize, parentExtract, limit > 0);
  17652. // MORE - should we use an expanding array instead?
  17653. if (limit > 0)
  17654. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17655. }
  17656. virtual void reset()
  17657. {
  17658. if (sorted)
  17659. {
  17660. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17661. curIndex = 0;
  17662. sortedCount = 0;
  17663. ReleaseRoxieRow(sorted);
  17664. sorted = NULL;
  17665. }
  17666. CRoxieServerLateStartActivity::reset();
  17667. }
  17668. bool abortEarly()
  17669. {
  17670. if (hasBest && (sortedCount == limit))
  17671. {
  17672. int compare = helper.compareBest(sorted[sortedCount-1]);
  17673. if (compare == 0)
  17674. {
  17675. if (meta.isGrouped())
  17676. {
  17677. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17678. const void * next;
  17679. while ((next = inputStream->nextRow()) != NULL)
  17680. ReleaseRoxieRow(next);
  17681. }
  17682. else
  17683. eoi = true;
  17684. return true;
  17685. }
  17686. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17687. if (compare < 0)
  17688. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17689. }
  17690. return false;
  17691. }
  17692. void getSorted()
  17693. {
  17694. curIndex = 0;
  17695. sortedCount = 0;
  17696. if(eoi)
  17697. return;
  17698. const void * next;
  17699. while ((next = inputStream->nextRow()) != NULL)
  17700. {
  17701. if (sortedCount < limit)
  17702. {
  17703. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17704. sortedCount++;
  17705. if(abortEarly())
  17706. return;
  17707. }
  17708. else
  17709. {
  17710. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17711. {
  17712. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17713. ReleaseRoxieRow(sorted[sortedCount]);
  17714. if(abortEarly())
  17715. return;
  17716. }
  17717. else
  17718. {
  17719. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17720. }
  17721. }
  17722. }
  17723. }
  17724. virtual const void * nextRow()
  17725. {
  17726. ActivityTimer t(totalCycles, timeActivities);
  17727. if (eof)
  17728. return NULL;
  17729. if (curIndex >= sortedCount)
  17730. {
  17731. bool eog = sortedCount != 0;
  17732. getSorted();
  17733. if(sortedCount == 0)
  17734. {
  17735. eof = true;
  17736. return NULL;
  17737. }
  17738. if (eog)
  17739. return NULL;
  17740. }
  17741. processed++;
  17742. return sorted[curIndex++];
  17743. }
  17744. };
  17745. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17746. {
  17747. public:
  17748. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17749. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17750. {
  17751. }
  17752. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17753. {
  17754. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17755. }
  17756. };
  17757. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17758. {
  17759. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17760. }
  17761. //=================================================================================
  17762. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17763. {
  17764. protected:
  17765. unsigned __int64 rowLimit;
  17766. IHThorLimitArg &helper;
  17767. public:
  17768. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17769. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17770. {
  17771. rowLimit = 0;
  17772. }
  17773. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17774. {
  17775. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17776. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17777. }
  17778. virtual const void *nextRow()
  17779. {
  17780. ActivityTimer t(totalCycles, timeActivities);
  17781. const void * ret = inputStream->nextRow();
  17782. if (ret)
  17783. {
  17784. processed++;
  17785. if (processed > rowLimit)
  17786. {
  17787. ReleaseRoxieRow(ret);
  17788. if (traceLevel > 4)
  17789. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17790. helper.onLimitExceeded();
  17791. }
  17792. }
  17793. return ret;
  17794. }
  17795. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17796. {
  17797. ActivityTimer t(totalCycles, timeActivities);
  17798. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17799. if (ret)
  17800. {
  17801. if (wasCompleteMatch)
  17802. processed++;
  17803. if (processed > rowLimit)
  17804. {
  17805. ReleaseRoxieRow(ret);
  17806. if (traceLevel > 4)
  17807. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17808. helper.onLimitExceeded();
  17809. }
  17810. }
  17811. return ret;
  17812. }
  17813. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17814. {
  17815. return input->gatherConjunctions(collector);
  17816. }
  17817. virtual void resetEOF()
  17818. {
  17819. //Do not reset the rowLimit
  17820. inputStream->resetEOF();
  17821. }
  17822. IInputSteppingMeta * querySteppingMeta()
  17823. {
  17824. return input->querySteppingMeta();
  17825. }
  17826. };
  17827. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17828. {
  17829. public:
  17830. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17831. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17832. {
  17833. }
  17834. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17835. {
  17836. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17837. }
  17838. };
  17839. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17840. {
  17841. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17842. }
  17843. //=====================================================================================================
  17844. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17845. {
  17846. ConstPointerArray buff;
  17847. bool started = false;
  17848. unsigned index = 0;
  17849. bool isFail = false;
  17850. public:
  17851. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17852. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17853. {
  17854. started = false;
  17855. index = 0;
  17856. isFail = _onFail;
  17857. }
  17858. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17859. {
  17860. started = false;
  17861. index = 0;
  17862. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17863. }
  17864. virtual void reset()
  17865. {
  17866. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17867. buff.kill();
  17868. index = 0;
  17869. started = false;
  17870. CRoxieServerLimitActivity::reset();
  17871. }
  17872. virtual const void *nextRow()
  17873. {
  17874. ActivityTimer t(totalCycles, timeActivities);
  17875. if (!started)
  17876. pullInput();
  17877. if (buff.isItem(index))
  17878. {
  17879. const void * next = buff.item(index++);
  17880. if(next)
  17881. processed++;
  17882. return next;
  17883. }
  17884. return NULL;
  17885. }
  17886. protected:
  17887. void pullInput()
  17888. {
  17889. unsigned count = 0;
  17890. for (;;)
  17891. {
  17892. const void * next = inputStream->nextRow();
  17893. if (next == NULL)
  17894. {
  17895. next = inputStream->nextRow();
  17896. if(next == NULL)
  17897. break;
  17898. buff.append(NULL);
  17899. }
  17900. count++;
  17901. if (count > rowLimit)
  17902. {
  17903. ReleaseRoxieRow(next);
  17904. ReleaseRoxieRows(buff);
  17905. if (ctx->queryDebugContext())
  17906. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17907. if (isFail)
  17908. {
  17909. ensureRowAllocator();
  17910. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17911. size32_t outSize = helper.transformOnLimitExceeded(rowBuilder);
  17912. if (outSize)
  17913. buff.append(rowBuilder.finalizeRowClear(outSize));
  17914. }
  17915. break;
  17916. }
  17917. buff.append(next);
  17918. }
  17919. started = true;
  17920. }
  17921. };
  17922. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17923. {
  17924. public:
  17925. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17926. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17927. {
  17928. }
  17929. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17930. {
  17931. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17932. }
  17933. };
  17934. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17935. {
  17936. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17937. }
  17938. //=================================================================================
  17939. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17940. {
  17941. IHThorCatchArg &helper;
  17942. public:
  17943. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17944. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17945. {
  17946. }
  17947. virtual const void *nextRow()
  17948. {
  17949. ActivityTimer t(totalCycles, timeActivities);
  17950. try
  17951. {
  17952. const void *ret = inputStream->nextRow();
  17953. if (ret)
  17954. processed++;
  17955. return ret;
  17956. }
  17957. catch (IException *E)
  17958. {
  17959. E->Release();
  17960. helper.onExceptionCaught();
  17961. }
  17962. catch (...)
  17963. {
  17964. helper.onExceptionCaught();
  17965. }
  17966. throwUnexpected(); // onExceptionCaught should have thrown something
  17967. }
  17968. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17969. {
  17970. try
  17971. {
  17972. ActivityTimer t(totalCycles, timeActivities);
  17973. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17974. if (ret && wasCompleteMatch)
  17975. processed++;
  17976. return ret;
  17977. }
  17978. catch (IException *E)
  17979. {
  17980. E->Release();
  17981. helper.onExceptionCaught();
  17982. }
  17983. catch (...)
  17984. {
  17985. helper.onExceptionCaught();
  17986. }
  17987. throwUnexpected(); // onExceptionCaught should have thrown something
  17988. }
  17989. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17990. {
  17991. return input->gatherConjunctions(collector);
  17992. }
  17993. virtual void resetEOF()
  17994. {
  17995. inputStream->resetEOF(); // MORE - why not in base class?
  17996. }
  17997. IInputSteppingMeta * querySteppingMeta()
  17998. {
  17999. return input->querySteppingMeta();
  18000. }
  18001. };
  18002. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  18003. {
  18004. ConstPointerArray buff;
  18005. bool started;
  18006. unsigned index;
  18007. IHThorCatchArg &helper;
  18008. bool createRow;
  18009. public:
  18010. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  18011. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  18012. {
  18013. started = false;
  18014. index = 0;
  18015. }
  18016. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18017. {
  18018. started = false;
  18019. index = 0;
  18020. try
  18021. {
  18022. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18023. }
  18024. catch (IException *E)
  18025. {
  18026. ensureCreated();
  18027. onException(E);
  18028. started = true;
  18029. }
  18030. catch (...)
  18031. {
  18032. ensureCreated();
  18033. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18034. started = true;
  18035. }
  18036. }
  18037. virtual void reset()
  18038. {
  18039. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  18040. buff.kill();
  18041. index = 0;
  18042. started = false;
  18043. CRoxieServerActivity::reset();
  18044. }
  18045. virtual const void *nextRow()
  18046. {
  18047. ActivityTimer t(totalCycles, timeActivities);
  18048. if (!started)
  18049. pullInput();
  18050. if (buff.isItem(index))
  18051. {
  18052. const void * next = buff.item(index++);
  18053. if(next)
  18054. processed++;
  18055. return next;
  18056. }
  18057. return NULL;
  18058. }
  18059. protected:
  18060. void onException(IException *E)
  18061. {
  18062. inputStream->stop();
  18063. ReleaseRoxieRows(buff);
  18064. if (createRow)
  18065. {
  18066. ensureRowAllocator();
  18067. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18068. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  18069. if (outSize)
  18070. buff.append(rowBuilder.finalizeRowClear(outSize));
  18071. }
  18072. E->Release();
  18073. }
  18074. void pullInput()
  18075. {
  18076. try
  18077. {
  18078. bool EOGseen = false;
  18079. for (;;)
  18080. {
  18081. const void * next = inputStream->nextRow();
  18082. buff.append(next);
  18083. if (next == NULL)
  18084. {
  18085. if (EOGseen)
  18086. break;
  18087. EOGseen = true;
  18088. }
  18089. else
  18090. EOGseen = false;
  18091. }
  18092. }
  18093. catch (IException *E)
  18094. {
  18095. onException(E);
  18096. }
  18097. catch (...)
  18098. {
  18099. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18100. }
  18101. started = true;
  18102. }
  18103. };
  18104. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  18105. {
  18106. public:
  18107. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18108. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18109. {
  18110. }
  18111. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18112. {
  18113. switch (kind)
  18114. {
  18115. case TAKcatch:
  18116. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  18117. case TAKskipcatch:
  18118. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  18119. case TAKcreaterowcatch:
  18120. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  18121. default:
  18122. throwUnexpected();
  18123. }
  18124. }
  18125. };
  18126. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18127. {
  18128. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18129. }
  18130. //=================================================================================
  18131. class CRoxieServerPullActivity : public CRoxieServerActivity
  18132. {
  18133. ConstPointerArray buff;
  18134. bool started;
  18135. unsigned index;
  18136. public:
  18137. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18138. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18139. {
  18140. started = false;
  18141. index = 0;
  18142. }
  18143. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18144. {
  18145. started = false;
  18146. index = 0;
  18147. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18148. }
  18149. virtual void reset()
  18150. {
  18151. while (buff.isItem(index))
  18152. ReleaseRoxieRow(buff.item(index++));
  18153. buff.kill();
  18154. started = false;
  18155. index = 0;
  18156. CRoxieServerActivity::reset();
  18157. }
  18158. virtual const void *nextRow()
  18159. {
  18160. ActivityTimer t(totalCycles, timeActivities);
  18161. if (!started)
  18162. pullInput();
  18163. if (buff.isItem(index))
  18164. {
  18165. const void * next = buff.item(index++);
  18166. if (next)
  18167. processed++;
  18168. return next;
  18169. }
  18170. return NULL;
  18171. }
  18172. protected:
  18173. void pullInput()
  18174. {
  18175. bool EOGseen = false;
  18176. for (;;)
  18177. {
  18178. const void * next = inputStream->nextRow();
  18179. buff.append(next);
  18180. if (next == NULL)
  18181. {
  18182. if (EOGseen)
  18183. break;
  18184. EOGseen = true;
  18185. }
  18186. else
  18187. EOGseen = false;
  18188. }
  18189. started = true;
  18190. }
  18191. };
  18192. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  18193. {
  18194. public:
  18195. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18196. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18197. {
  18198. }
  18199. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18200. {
  18201. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  18202. }
  18203. };
  18204. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18205. {
  18206. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18207. }
  18208. //=================================================================================
  18209. class CRoxieServerTraceActivity : public CRoxieServerActivity
  18210. {
  18211. public:
  18212. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18213. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  18214. keepLimit(0), skip(0), sample(0)
  18215. {
  18216. assertex(meta.hasXML());
  18217. traceEnabled = defaultTraceEnabled && !isBlind();
  18218. }
  18219. virtual void onCreate(IHThorArg *_colocalParent)
  18220. {
  18221. CRoxieServerActivity::onCreate(_colocalParent);
  18222. if (ctx)
  18223. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  18224. }
  18225. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18226. {
  18227. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18228. if (traceEnabled && helper.canMatchAny())
  18229. {
  18230. keepLimit = helper.getKeepLimit();
  18231. if (keepLimit==(unsigned) -1)
  18232. keepLimit = ctx->queryOptions().traceLimit;
  18233. skip = helper.getSkip();
  18234. sample = helper.getSample();
  18235. if (sample)
  18236. sample--;
  18237. name.setown(helper.getName());
  18238. if (!name)
  18239. name.set("Row");
  18240. }
  18241. else
  18242. keepLimit = 0;
  18243. }
  18244. virtual void stop()
  18245. {
  18246. name.clear();
  18247. CRoxieServerActivity::stop();
  18248. }
  18249. virtual bool isPassThrough()
  18250. {
  18251. return true;
  18252. }
  18253. virtual const void *nextRow()
  18254. {
  18255. ActivityTimer t(totalCycles, timeActivities);
  18256. const void *row = inputStream->nextRow();
  18257. if (row)
  18258. {
  18259. onTrace(row);
  18260. processed++;
  18261. }
  18262. return row;
  18263. }
  18264. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18265. {
  18266. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  18267. ActivityTimer t(totalCycles, timeActivities);
  18268. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18269. if (row)
  18270. {
  18271. onTrace(row);
  18272. processed++;
  18273. }
  18274. return row;
  18275. }
  18276. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18277. {
  18278. return input->gatherConjunctions(collector);
  18279. }
  18280. virtual void resetEOF()
  18281. {
  18282. inputStream->resetEOF();
  18283. }
  18284. IInputSteppingMeta * querySteppingMeta()
  18285. {
  18286. return input->querySteppingMeta();
  18287. }
  18288. protected:
  18289. void onTrace(const void *row)
  18290. {
  18291. if (keepLimit && helper.isValid(row))
  18292. {
  18293. if (skip)
  18294. skip--;
  18295. else if (sample)
  18296. sample--;
  18297. else
  18298. {
  18299. CommonXmlWriter xmlwrite(XWFnoindent);
  18300. meta.toXML((const byte *) row, xmlwrite);
  18301. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18302. keepLimit--;
  18303. sample = helper.getSample();
  18304. if (sample)
  18305. sample--;
  18306. }
  18307. }
  18308. }
  18309. OwnedRoxieString name;
  18310. IHThorTraceArg &helper;
  18311. unsigned keepLimit;
  18312. unsigned skip;
  18313. unsigned sample;
  18314. bool traceEnabled;
  18315. };
  18316. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18317. {
  18318. public:
  18319. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18320. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18321. {
  18322. }
  18323. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18324. {
  18325. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18326. }
  18327. };
  18328. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18329. {
  18330. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18331. }
  18332. //=================================================================================
  18333. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18334. {
  18335. IHThorCaseArg &helper;
  18336. unsigned cond;
  18337. bool unusedStopped;
  18338. IEngineRowStream *active;
  18339. public:
  18340. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18341. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18342. {
  18343. unusedStopped = false;
  18344. cond = 0;
  18345. active = NULL;
  18346. }
  18347. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18348. {
  18349. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18350. cond = helper.getBranch();
  18351. //CHOOSE defaults to the last argument if out of range.
  18352. if (cond >= numInputs)
  18353. cond = numInputs - 1;
  18354. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18355. startJunction(junctionArray[cond]);
  18356. assertex(numInputs==numStreams);
  18357. for (unsigned idx = 0; idx < numStreams; idx++)
  18358. {
  18359. if (idx!=cond)
  18360. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18361. }
  18362. active = streamArray[cond];
  18363. unusedStopped = true;
  18364. }
  18365. virtual void stop()
  18366. {
  18367. for (unsigned idx = 0; idx < numStreams; idx++)
  18368. {
  18369. if (idx==cond || !unusedStopped)
  18370. streamArray[idx]->stop();
  18371. }
  18372. CRoxieServerMultiInputBaseActivity::stop();
  18373. }
  18374. virtual void reset()
  18375. {
  18376. unusedStopped = false;
  18377. active = NULL;
  18378. CRoxieServerMultiInputBaseActivity::reset();
  18379. }
  18380. virtual const void *nextRow()
  18381. {
  18382. ActivityTimer t(totalCycles, timeActivities);
  18383. if (active)
  18384. {
  18385. const void *ret = active->nextRow();
  18386. if (ret)
  18387. processed++;
  18388. return ret;
  18389. }
  18390. return NULL;
  18391. }
  18392. };
  18393. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18394. {
  18395. bool graphInvariant;
  18396. public:
  18397. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18398. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18399. {
  18400. graphInvariant = _graphInvariant;
  18401. }
  18402. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18403. {
  18404. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18405. }
  18406. virtual bool isGraphInvariant() const
  18407. {
  18408. return graphInvariant;
  18409. }
  18410. };
  18411. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18412. {
  18413. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18414. }
  18415. //=================================================================================
  18416. class CRoxieServerIfActivity : public CRoxieServerActivity
  18417. {
  18418. IHThorIfArg &helper;
  18419. IFinalRoxieInput *inputTrue;
  18420. IFinalRoxieInput *inputFalse;
  18421. IEngineRowStream *streamTrue;
  18422. IEngineRowStream *streamFalse;
  18423. unsigned sourceIdxFalse = 0;
  18424. unsigned sourceIdxTrue = 0;
  18425. Owned<IStrandJunction> junctionTrue;
  18426. Owned<IStrandJunction> junctionFalse;
  18427. bool cond;
  18428. bool unusedStopped;
  18429. public:
  18430. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18431. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18432. {
  18433. inputFalse = NULL;
  18434. inputTrue = NULL;
  18435. streamTrue = NULL;
  18436. streamFalse = NULL;
  18437. unusedStopped = false;
  18438. cond = false;
  18439. }
  18440. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18441. {
  18442. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18443. cond = helper.getCondition();
  18444. if (cond)
  18445. {
  18446. inputTrue->start(parentExtractSize, parentExtract, paused);
  18447. startJunction(junctionTrue);
  18448. if (streamFalse)
  18449. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18450. }
  18451. else
  18452. {
  18453. if (inputFalse)
  18454. {
  18455. inputFalse->start(parentExtractSize, parentExtract, paused);
  18456. startJunction(junctionFalse);
  18457. }
  18458. streamTrue->stop();
  18459. }
  18460. unusedStopped = true;
  18461. }
  18462. virtual void stop()
  18463. {
  18464. if (!unusedStopped || cond)
  18465. streamTrue->stop();
  18466. if (streamFalse && (!unusedStopped || !cond))
  18467. streamFalse->stop();
  18468. CRoxieServerActivity::stop();
  18469. }
  18470. virtual unsigned __int64 queryLocalCycles() const
  18471. {
  18472. __int64 localCycles = totalCycles.totalCycles;
  18473. localCycles -= inputTrue->queryTotalCycles();
  18474. if (inputFalse)
  18475. localCycles -= inputFalse->queryTotalCycles();
  18476. if (localCycles < 0)
  18477. localCycles = 0;
  18478. return localCycles;
  18479. }
  18480. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18481. {
  18482. switch (idx)
  18483. {
  18484. case 0:
  18485. return inputTrue;
  18486. case 1:
  18487. return inputFalse;
  18488. default:
  18489. return NULL;
  18490. }
  18491. }
  18492. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18493. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18494. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18495. {
  18496. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18497. if (in)
  18498. return in->queryIndexReadActivity();
  18499. return NULL;
  18500. }
  18501. virtual void reset()
  18502. {
  18503. CRoxieServerActivity::reset();
  18504. inputTrue->reset();
  18505. if (inputFalse)
  18506. inputFalse->reset();
  18507. resetJunction(junctionTrue);
  18508. resetJunction(junctionFalse);
  18509. unusedStopped = false;
  18510. }
  18511. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18512. {
  18513. if (idx==1)
  18514. {
  18515. inputFalse = _in;
  18516. sourceIdxFalse = _sourceIdx;
  18517. }
  18518. else
  18519. {
  18520. assertex(!idx);
  18521. inputTrue = _in;
  18522. sourceIdxTrue = _sourceIdx;
  18523. }
  18524. }
  18525. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18526. {
  18527. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18528. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18529. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18530. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18531. }
  18532. virtual const void *nextRow()
  18533. {
  18534. ActivityTimer t(totalCycles, timeActivities);
  18535. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18536. if (in)
  18537. {
  18538. const void * ret;
  18539. if ((ret = in->nextRow()) != NULL)
  18540. processed++;
  18541. return ret;
  18542. }
  18543. return NULL;
  18544. }
  18545. };
  18546. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18547. {
  18548. unsigned input2;
  18549. unsigned input2idx;
  18550. bool graphInvariant;
  18551. public:
  18552. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18553. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18554. {
  18555. graphInvariant = _graphInvariant;
  18556. input2 = (unsigned)-1;
  18557. input2idx = (unsigned)-1;
  18558. }
  18559. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18560. {
  18561. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18562. }
  18563. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18564. {
  18565. if (idx==1)
  18566. {
  18567. input2 = source;
  18568. input2idx = sourceidx;
  18569. }
  18570. else
  18571. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18572. }
  18573. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18574. {
  18575. switch (idx)
  18576. {
  18577. case 1:
  18578. sourceidx = input2idx;
  18579. return input2;
  18580. case 0:
  18581. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18582. default:
  18583. return (unsigned) -1;
  18584. }
  18585. }
  18586. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18587. virtual bool isGraphInvariant() const
  18588. {
  18589. return graphInvariant;
  18590. }
  18591. };
  18592. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18593. {
  18594. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18595. }
  18596. //=================================================================================
  18597. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18598. {
  18599. CriticalSection ecrit;
  18600. Owned<IException> exception;
  18601. bool executed;
  18602. public:
  18603. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18604. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18605. {
  18606. executed = false;
  18607. }
  18608. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18609. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18610. {
  18611. CriticalBlock b(ecrit);
  18612. if (exception)
  18613. throw(exception.getLink());
  18614. if (!executed)
  18615. {
  18616. try
  18617. {
  18618. executed = true;
  18619. start(parentExtractSize, parentExtract, false);
  18620. doExecuteAction(parentExtractSize, parentExtract);
  18621. stop();
  18622. }
  18623. catch (IException * E)
  18624. {
  18625. ctx->notifyAbort(E);
  18626. abort();
  18627. exception.set(E);
  18628. throw;
  18629. }
  18630. }
  18631. }
  18632. virtual void reset()
  18633. {
  18634. executed = false;
  18635. exception.clear();
  18636. CRoxieServerActivity::reset();
  18637. }
  18638. virtual const void *nextRow()
  18639. {
  18640. throwUnexpected(); // I am nobody's input
  18641. }
  18642. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18643. {
  18644. return NULL;
  18645. }
  18646. };
  18647. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18648. {
  18649. IHThorIfArg &helper;
  18650. public:
  18651. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18652. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18653. {
  18654. }
  18655. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18656. {
  18657. bool cond;
  18658. {
  18659. ActivityTimer t(totalCycles, timeActivities);
  18660. cond = helper.getCondition();
  18661. }
  18662. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18663. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18664. }
  18665. };
  18666. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18667. {
  18668. bool isRoot;
  18669. public:
  18670. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18671. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18672. {
  18673. }
  18674. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18675. {
  18676. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18677. }
  18678. virtual bool isSink() const
  18679. {
  18680. return isRoot;
  18681. }
  18682. };
  18683. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18684. {
  18685. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18686. }
  18687. //=================================================================================
  18688. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18689. {
  18690. public:
  18691. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18692. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18693. {
  18694. }
  18695. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18696. {
  18697. #ifdef PARALLEL_EXECUTE
  18698. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18699. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18700. #else
  18701. ForEachItemIn(idx, dependencies)
  18702. {
  18703. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18704. }
  18705. #endif
  18706. }
  18707. };
  18708. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18709. {
  18710. bool isRoot;
  18711. public:
  18712. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18713. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18714. {
  18715. assertex(!isRoot); // non-internal should be expanded out..
  18716. }
  18717. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18718. {
  18719. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18720. }
  18721. virtual bool isSink() const
  18722. {
  18723. return isRoot;
  18724. }
  18725. };
  18726. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18727. {
  18728. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18729. }
  18730. //=================================================================================
  18731. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18732. {
  18733. IHThorSequentialArg &helper;
  18734. public:
  18735. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18736. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18737. {
  18738. }
  18739. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18740. {
  18741. unsigned numBranches = helper.numBranches();
  18742. for (unsigned branch=1; branch <= numBranches; branch++)
  18743. executeDependencies(parentExtractSize, parentExtract, branch);
  18744. }
  18745. };
  18746. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18747. {
  18748. bool isRoot;
  18749. public:
  18750. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18751. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18752. {
  18753. }
  18754. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18755. {
  18756. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18757. }
  18758. virtual bool isSink() const
  18759. {
  18760. return isRoot;
  18761. }
  18762. };
  18763. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18764. {
  18765. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18766. }
  18767. //=================================================================================
  18768. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18769. {
  18770. public:
  18771. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18772. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18773. {
  18774. savedExtractSize = 0;
  18775. savedExtract = NULL;
  18776. eofseen = false;
  18777. eogseen = false;
  18778. }
  18779. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18780. {
  18781. savedExtractSize = parentExtractSize;
  18782. savedExtract = parentExtract;
  18783. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18784. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18785. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18786. eofseen = false;
  18787. eogseen = false;
  18788. }
  18789. virtual void stop()
  18790. {
  18791. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18792. {
  18793. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18794. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18795. }
  18796. else if (state != STATEstopped)
  18797. {
  18798. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18799. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18800. }
  18801. CRoxieServerActivity::stop();
  18802. }
  18803. virtual const void *nextRow()
  18804. {
  18805. try
  18806. {
  18807. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18808. const void *ret = inputStream->nextRow();
  18809. if (!ret)
  18810. {
  18811. if (eogseen)
  18812. eofseen = true;
  18813. else
  18814. eogseen = true;
  18815. }
  18816. else
  18817. eogseen = false;
  18818. return ret;
  18819. }
  18820. catch (...)
  18821. {
  18822. aborted = true;
  18823. throw;
  18824. }
  18825. }
  18826. protected:
  18827. const byte *savedExtract;
  18828. unsigned savedExtractSize;
  18829. bool eofseen;
  18830. bool eogseen;
  18831. };
  18832. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18833. {
  18834. public:
  18835. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18836. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18837. {
  18838. }
  18839. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18840. {
  18841. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18842. }
  18843. };
  18844. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18845. {
  18846. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18847. }
  18848. //=================================================================================
  18849. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18850. {
  18851. public:
  18852. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18853. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18854. {
  18855. savedExtractSize = 0;
  18856. savedExtract = NULL;
  18857. }
  18858. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18859. {
  18860. savedExtractSize = parentExtractSize;
  18861. savedExtract = parentExtract;
  18862. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18863. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18864. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18865. }
  18866. virtual void stop()
  18867. {
  18868. if (state != STATEstopped)
  18869. {
  18870. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18871. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18872. }
  18873. CRoxieServerActionBaseActivity::stop();
  18874. }
  18875. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18876. {
  18877. executeDependencies(parentExtractSize, parentExtract, 1);
  18878. }
  18879. protected:
  18880. unsigned savedExtractSize;
  18881. const byte *savedExtract;
  18882. };
  18883. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18884. {
  18885. public:
  18886. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18887. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18888. {
  18889. }
  18890. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18891. {
  18892. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18893. }
  18894. virtual bool isSink() const
  18895. {
  18896. return isRoot;
  18897. }
  18898. private:
  18899. bool isRoot;
  18900. };
  18901. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18902. {
  18903. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18904. }
  18905. //=================================================================================
  18906. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18907. {
  18908. INlpParseAlgorithm * algorithm;
  18909. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18910. {
  18911. protected:
  18912. IHThorParseArg &helper;
  18913. INlpParser * parser;
  18914. INlpResultIterator * rowIter;
  18915. const void * in;
  18916. char * curSearchText;
  18917. size32_t curSearchTextLen;
  18918. bool processRecord(const void * inRec)
  18919. {
  18920. if (helper.searchTextNeedsFree())
  18921. rtlFree(curSearchText);
  18922. curSearchTextLen = 0;
  18923. curSearchText = NULL;
  18924. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18925. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18926. }
  18927. public:
  18928. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18929. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18930. {
  18931. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18932. rowIter = parser->queryResultIter();
  18933. in = NULL;
  18934. curSearchText = NULL;
  18935. curSearchTextLen = 0;
  18936. }
  18937. ~ParseProcessor()
  18938. {
  18939. ::Release(parser);
  18940. }
  18941. virtual void start()
  18942. {
  18943. StrandProcessor::start();
  18944. numProcessedLastGroup = 0;
  18945. curSearchTextLen = 0;
  18946. curSearchText = NULL;
  18947. in = NULL;
  18948. parser->reset();
  18949. }
  18950. virtual void reset()
  18951. {
  18952. if (helper.searchTextNeedsFree())
  18953. rtlFree(curSearchText);
  18954. curSearchText = NULL;
  18955. ReleaseClearRoxieRow(in);
  18956. StrandProcessor::reset();
  18957. }
  18958. virtual const void * nextRow()
  18959. {
  18960. ActivityTimer t(totalCycles, timeActivities);
  18961. for (;;)
  18962. {
  18963. if (rowIter->isValid())
  18964. {
  18965. OwnedConstRoxieRow out = rowIter->getRow();
  18966. rowIter->next();
  18967. processed++;
  18968. return out.getClear();
  18969. }
  18970. ReleaseClearRoxieRow(in);
  18971. in = inputStream->nextRow();
  18972. if (!in)
  18973. {
  18974. if (processed == numProcessedLastGroup)
  18975. in = inputStream->nextRow();
  18976. if (!in)
  18977. {
  18978. processed = numProcessedLastGroup;
  18979. return NULL;
  18980. }
  18981. in = inputStream->nextRow();
  18982. if (!in)
  18983. return NULL;
  18984. }
  18985. processRecord(in);
  18986. rowIter->first();
  18987. }
  18988. }
  18989. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  18990. {
  18991. try
  18992. {
  18993. return helper.transform(self, curRecord, results, walker);
  18994. }
  18995. catch (IException *E)
  18996. {
  18997. throw parent.makeWrappedException(E);
  18998. }
  18999. }
  19000. };
  19001. public:
  19002. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  19003. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  19004. {
  19005. }
  19006. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19007. {
  19008. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  19009. onStartStrands();
  19010. }
  19011. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  19012. {
  19013. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  19014. }
  19015. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  19016. };
  19017. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  19018. {
  19019. Owned<INlpParseAlgorithm> algorithm;
  19020. Owned<IHThorParseArg> helper;
  19021. StrandOptions strandOptions;
  19022. public:
  19023. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19024. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  19025. {
  19026. helper.setown((IHThorParseArg *) helperFactory());
  19027. algorithm.setown(createThorParser(rc, *helper));
  19028. optStableInput = false;
  19029. }
  19030. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19031. {
  19032. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  19033. }
  19034. };
  19035. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19036. {
  19037. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  19038. }
  19039. //=====================================================================================================
  19040. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  19041. {
  19042. IHThorWorkUnitWriteArg &helper;
  19043. bool isReread;
  19044. bool grouped;
  19045. IRoxieServerContext *serverContext;
  19046. public:
  19047. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  19048. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  19049. {
  19050. grouped = (helper.getFlags() & POFgrouped) != 0;
  19051. serverContext = NULL;
  19052. }
  19053. virtual void onCreate(IHThorArg *_colocalParent)
  19054. {
  19055. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19056. serverContext = ctx->queryServerContext();
  19057. if (!serverContext)
  19058. {
  19059. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  19060. }
  19061. }
  19062. virtual bool needsAllocator() const { return true; }
  19063. virtual void onExecute()
  19064. {
  19065. int sequence = helper.getSequence();
  19066. const char *storedName = helper.queryName();
  19067. if (!storedName)
  19068. storedName = "Dataset";
  19069. MemoryBuffer result;
  19070. bool saveInContext = (int) sequence < 0 || isReread;
  19071. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  19072. meta.set(input->queryOutputMeta());
  19073. Owned<IOutputRowSerializer> rowSerializer;
  19074. Owned<IXmlWriter> xmlwriter;
  19075. bool appendRaw = false;
  19076. IHpccProtocolResultsWriter *results = NULL;
  19077. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  19078. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  19079. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  19080. if ((int) sequence >= 0)
  19081. {
  19082. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  19083. if (results)
  19084. {
  19085. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  19086. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  19087. }
  19088. }
  19089. size32_t outputLimitBytes = 0;
  19090. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  19091. if (workunit)
  19092. {
  19093. size32_t outputLimit;
  19094. if (helper.getFlags() & POFmaxsize)
  19095. outputLimit = helper.getMaxSize();
  19096. else
  19097. {
  19098. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  19099. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  19100. }
  19101. if (outputLimit>defaultDaliResultOutputMax)
  19102. 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);
  19103. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  19104. outputLimitBytes = outputLimit * 0x100000;
  19105. }
  19106. if (workunit != NULL || (results && (protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW)))
  19107. {
  19108. ensureRowAllocator();
  19109. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  19110. }
  19111. __int64 initialProcessed = processed;
  19112. RtlLinkedDatasetBuilder builder(rowAllocator);
  19113. for (;;)
  19114. {
  19115. const void *row = inputStream->nextRow();
  19116. if (saveInContext)
  19117. {
  19118. if (row || grouped)
  19119. builder.append(row);
  19120. }
  19121. if (grouped && (processed != initialProcessed))
  19122. {
  19123. if (workunit)
  19124. result.append(row == NULL);
  19125. if (results)
  19126. {
  19127. if ((protocolFlags & HPCC_PROTOCOL_NATIVE_RAW) && nativeResults)
  19128. {
  19129. char val = (char)(row == NULL);
  19130. nativeResults->appendRaw(sequence, 1, &val);
  19131. }
  19132. else if (xmlwriter)
  19133. {
  19134. xmlwriter->outputBeginNested("Row", false);
  19135. xmlwriter->outputCString("1", "@__GroupBreak__");
  19136. xmlwriter->outputEndNested("Row");
  19137. }
  19138. }
  19139. }
  19140. if (!row)
  19141. {
  19142. row = inputStream->nextRow();
  19143. if (!row)
  19144. break;
  19145. if (saveInContext)
  19146. builder.append(row);
  19147. }
  19148. processed++;
  19149. if (workunit)
  19150. {
  19151. CThorDemoRowSerializer serializerTarget(result);
  19152. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19153. }
  19154. if ((int) sequence >= 0)
  19155. {
  19156. if (appendRaw && nativeResults)
  19157. {
  19158. // MORE - should be able to serialize straight to the response...
  19159. MemoryBuffer rowbuff;
  19160. CThorDemoRowSerializer serializerTarget(rowbuff);
  19161. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19162. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  19163. }
  19164. else if (xmlwriter)
  19165. {
  19166. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  19167. helper.serializeXml((byte *) row, *xmlwriter);
  19168. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  19169. results->finalizeXmlRow(sequence);
  19170. }
  19171. else if (nativeResults)
  19172. {
  19173. SimpleOutputWriter x;
  19174. helper.serializeXml((byte *) row, x);
  19175. x.newline();
  19176. nativeResults->appendSimpleRow(sequence, x.str());
  19177. }
  19178. }
  19179. ReleaseRoxieRow(row);
  19180. if (outputLimitBytes && result.length() > outputLimitBytes)
  19181. {
  19182. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  19183. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  19184. const char *name = helper.queryName();
  19185. if (name)
  19186. errMsg.append("name=").append(name);
  19187. else
  19188. errMsg.append("sequence=").append(helper.getSequence());
  19189. errMsg.append(")");
  19190. throw MakeStringExceptionDirect(0, errMsg.str());
  19191. }
  19192. }
  19193. if (xmlwriter)
  19194. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  19195. if (saveInContext)
  19196. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19197. if (workunit)
  19198. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  19199. }
  19200. };
  19201. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  19202. {
  19203. bool isReread;
  19204. public:
  19205. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19206. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19207. {
  19208. isReread = usageCount > 0;
  19209. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  19210. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19211. }
  19212. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19213. {
  19214. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  19215. }
  19216. };
  19217. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19218. {
  19219. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19220. }
  19221. //=====================================================================================================
  19222. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  19223. {
  19224. IHThorDictionaryWorkUnitWriteArg &helper;
  19225. IRoxieServerContext *serverContext;
  19226. public:
  19227. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  19228. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  19229. {
  19230. serverContext = NULL;
  19231. }
  19232. virtual void onCreate(IHThorArg *_colocalParent)
  19233. {
  19234. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19235. serverContext = ctx->queryServerContext();
  19236. if (!serverContext)
  19237. {
  19238. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  19239. }
  19240. }
  19241. virtual bool needsAllocator() const { return true; }
  19242. virtual void onExecute()
  19243. {
  19244. int sequence = helper.getSequence();
  19245. const char *storedName = helper.queryName();
  19246. assertex(storedName && *storedName);
  19247. assertex(sequence < 0);
  19248. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  19249. for (;;)
  19250. {
  19251. const void *row = inputStream->ungroupedNextRow();
  19252. if (!row)
  19253. break;
  19254. builder.appendOwn(row);
  19255. processed++;
  19256. }
  19257. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19258. }
  19259. };
  19260. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  19261. {
  19262. public:
  19263. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19264. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19265. {
  19266. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  19267. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19268. }
  19269. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19270. {
  19271. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  19272. }
  19273. };
  19274. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19275. {
  19276. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19277. }
  19278. //=================================================================================
  19279. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  19280. {
  19281. IHThorRemoteResultArg &helper;
  19282. public:
  19283. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  19284. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  19285. {
  19286. }
  19287. virtual void onExecute()
  19288. {
  19289. OwnedConstRoxieRow row = inputStream->nextRow();
  19290. helper.sendResult(row); // should be only one row or something has gone wrong!
  19291. }
  19292. };
  19293. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19294. {
  19295. public:
  19296. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19297. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19298. {
  19299. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19300. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19301. }
  19302. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19303. {
  19304. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19305. }
  19306. };
  19307. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19308. {
  19309. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19310. }
  19311. //=================================================================================
  19312. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19313. {
  19314. IHThorXmlParseArg &helper;
  19315. Owned<IXMLParse> xmlParser;
  19316. const void * in;
  19317. char * srchStr;
  19318. unsigned numProcessedLastGroup;
  19319. bool srchStrNeedsFree;
  19320. Owned<IColumnProvider> lastMatch;
  19321. public:
  19322. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19323. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19324. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19325. helper((IHThorXmlParseArg &)basehelper)
  19326. {
  19327. srchStrNeedsFree = helper.searchTextNeedsFree();
  19328. numProcessedLastGroup = 0;
  19329. srchStr = NULL;
  19330. in = NULL;
  19331. }
  19332. ~CRoxieServerXmlParseActivity()
  19333. {
  19334. }
  19335. virtual bool needsAllocator() const { return true; }
  19336. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19337. {
  19338. numProcessedLastGroup = 0;
  19339. srchStr = NULL;
  19340. in = NULL;
  19341. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19342. }
  19343. virtual void reset()
  19344. {
  19345. if (helper.searchTextNeedsFree())
  19346. rtlFree(srchStr);
  19347. srchStr = NULL;
  19348. ReleaseClearRoxieRow(in);
  19349. xmlParser.clear();
  19350. CRoxieServerActivity::reset();
  19351. }
  19352. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19353. {
  19354. lastMatch.set(&entry);
  19355. }
  19356. virtual const void *nextRow()
  19357. {
  19358. ActivityTimer t(totalCycles, timeActivities);
  19359. for (;;)
  19360. {
  19361. if(xmlParser)
  19362. {
  19363. for (;;)
  19364. {
  19365. if(!xmlParser->next())
  19366. {
  19367. if (srchStrNeedsFree)
  19368. {
  19369. rtlFree(srchStr);
  19370. srchStr = NULL;
  19371. }
  19372. xmlParser.clear();
  19373. break;
  19374. }
  19375. if(lastMatch)
  19376. {
  19377. try
  19378. {
  19379. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19380. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19381. lastMatch.clear();
  19382. if (outSize)
  19383. {
  19384. processed++;
  19385. return rowBuilder.finalizeRowClear(outSize);
  19386. }
  19387. }
  19388. catch (IException *E)
  19389. {
  19390. throw makeWrappedException(E);
  19391. }
  19392. }
  19393. }
  19394. }
  19395. ReleaseClearRoxieRow(in);
  19396. in = inputStream->nextRow();
  19397. if(!in)
  19398. {
  19399. if(numProcessedLastGroup == processed)
  19400. in = inputStream->nextRow();
  19401. if(!in)
  19402. {
  19403. numProcessedLastGroup = processed;
  19404. return NULL;
  19405. }
  19406. }
  19407. size32_t srchLen;
  19408. helper.getSearchText(srchLen, srchStr, in);
  19409. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19410. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19411. }
  19412. }
  19413. };
  19414. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19415. {
  19416. public:
  19417. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19418. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19419. {
  19420. }
  19421. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19422. {
  19423. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19424. }
  19425. };
  19426. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19427. {
  19428. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19429. }
  19430. //=====================================================================================================
  19431. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19432. {
  19433. protected:
  19434. IHThorDiskReadBaseArg &helper;
  19435. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  19436. IHThorCompoundExtra * compoundHelper;
  19437. RemoteActivityId remoteId; // Note we copy it rather than reference
  19438. Owned<CSkippableRemoteResultAdaptor> remote;
  19439. unsigned numParts;
  19440. unsigned __int64 rowLimit;
  19441. unsigned __int64 stopAfter;
  19442. Linked<IInMemoryIndexManager> manager;
  19443. Linked<ITranslatorSet> translators;
  19444. ScoredRowFilter postFilter;
  19445. Owned<IDirectReader> reader;
  19446. bool eof;
  19447. bool variableFileName;
  19448. bool isOpt;
  19449. bool sorted;
  19450. bool maySkip;
  19451. bool isLocal;
  19452. bool forceRemote;
  19453. bool isGrouped = false;
  19454. CachedOutputMetaData diskSize;
  19455. Owned<const IResolvedFile> varFileInfo;
  19456. inline bool useRemote()
  19457. {
  19458. return remote != NULL && (forceRemote || numParts > 1);
  19459. }
  19460. public:
  19461. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19462. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19463. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19464. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19465. helper((IHThorDiskReadBaseArg &)basehelper),
  19466. numParts(_numParts),
  19467. remoteId(_remoteId),
  19468. manager(_manager),
  19469. translators(_translators),
  19470. isLocal(_isLocal),
  19471. sorted(_sorted),
  19472. maySkip(_maySkip)
  19473. {
  19474. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19475. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19476. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19477. compoundHelper = NULL;
  19478. eof = false;
  19479. rowLimit = (unsigned __int64) -1;
  19480. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19481. diskSize.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19482. isGrouped = diskSize.isGrouped();
  19483. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19484. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19485. }
  19486. virtual const IResolvedFile *queryVarFileInfo() const
  19487. {
  19488. return varFileInfo;
  19489. }
  19490. virtual void onCreate(IHThorArg *_colocalParent)
  19491. {
  19492. CRoxieServerActivity::onCreate(_colocalParent);
  19493. if (remote)
  19494. remote->onCreate(_colocalParent);
  19495. }
  19496. virtual bool needsAllocator() const { return true; }
  19497. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19498. {
  19499. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19500. if (compoundHelper)
  19501. {
  19502. rowLimit = compoundHelper->getRowLimit();
  19503. stopAfter = compoundHelper->getChooseNLimit();
  19504. }
  19505. if (!helper.canMatchAny())
  19506. eof = true;
  19507. else
  19508. {
  19509. if (variableFileName)
  19510. {
  19511. OwnedRoxieString fileName(helper.getFileName());
  19512. varFileInfo.setown(resolveLFNFlat(fileName, isOpt));
  19513. numParts = 0;
  19514. if (varFileInfo)
  19515. numParts = varFileInfo->getNumParts();
  19516. }
  19517. if (!numParts)
  19518. {
  19519. eof = true;
  19520. }
  19521. else if (useRemote())
  19522. {
  19523. remote->onStart(parentExtractSize, parentExtract);
  19524. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19525. unsigned fileNo = 0;
  19526. // Translation into a message per channel done elsewhere....
  19527. remote->getMem(0, fileNo, 0);
  19528. remote->flush();
  19529. remote->senddone();
  19530. }
  19531. else
  19532. {
  19533. if (variableFileName)
  19534. {
  19535. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19536. unsigned expectedFormatCrc = helper.getDiskFormatCrc();
  19537. unsigned projectedFormatCrc = helper.getProjectedFormatCrc();
  19538. translators.setown(varFileInfo->getTranslators(projectedFormatCrc, helper.queryProjectedDiskRecordSize(), expectedFormatCrc, helper.queryDiskRecordSize(), getEnableFieldTranslation(), false));
  19539. manager.setown(varFileInfo->getIndexManager(isOpt, channel, translators->queryActualLayout(0), false));
  19540. }
  19541. assertex(manager != NULL);
  19542. postFilter.clear();
  19543. helper.createSegmentMonitors(this);
  19544. const IKeyTranslator *keyTranslator = translators->queryKeyTranslator(0); // any part would do - in-memory requires all actuals to have same layout
  19545. if (keyTranslator)
  19546. keyTranslator->translate(postFilter);
  19547. reader.setown(manager->selectKey(postFilter, translators, *this));
  19548. if (!reader)
  19549. reader.setown(manager->createReader(postFilter, isGrouped, 0, 0, 1, translators));
  19550. assertex(reader);
  19551. helper.setCallback(reader);
  19552. }
  19553. }
  19554. }
  19555. virtual void append(IKeySegmentMonitor *segment)
  19556. {
  19557. segment->Release();
  19558. throwUnexpected();
  19559. }
  19560. virtual void append(FFoption option, const IFieldFilter * filter)
  19561. {
  19562. if (filter->isWild())
  19563. filter->Release();
  19564. else
  19565. postFilter.addFilter(*filter);
  19566. }
  19567. virtual void stop()
  19568. {
  19569. if (useRemote())
  19570. remote->onStop();
  19571. CRoxieServerActivity::stop();
  19572. }
  19573. virtual void reset()
  19574. {
  19575. if (useRemote())
  19576. {
  19577. processed = remote->processed;
  19578. remote->processed = 0;
  19579. remote->onReset();
  19580. }
  19581. varFileInfo.clear();
  19582. eof = false;
  19583. reader.clear();
  19584. CRoxieServerActivity::reset();
  19585. }
  19586. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19587. {
  19588. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19589. }
  19590. virtual void onLimitExceeded(bool isKeyed)
  19591. {
  19592. if (traceLevel > 4)
  19593. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19594. assertex(compoundHelper);
  19595. if (isKeyed) // MORE does this exist for diskread? should it?
  19596. {
  19597. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19598. {
  19599. if (ctx->queryDebugContext())
  19600. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19601. throw makeLimitSkipException(true);
  19602. }
  19603. else
  19604. {
  19605. UNIMPLEMENTED;
  19606. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19607. }
  19608. }
  19609. else
  19610. {
  19611. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19612. {
  19613. if (ctx->queryDebugContext())
  19614. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19615. throw makeLimitSkipException(false);
  19616. }
  19617. else
  19618. compoundHelper->onLimitExceeded();
  19619. }
  19620. }
  19621. virtual const void * createLimitFailRow(bool isKeyed)
  19622. {
  19623. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19624. assertex(limitTransformExtra);
  19625. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19626. if (outSize)
  19627. return rowBuilder.finalizeRowClear(outSize);
  19628. return NULL;
  19629. }
  19630. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19631. {
  19632. CRoxieServerActivity::gatherStats(merged);
  19633. if (remote)
  19634. remote->gatherStats(merged);
  19635. }
  19636. };
  19637. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19638. {
  19639. IHThorDiskReadArg * readHelper;
  19640. ConstPointerArray readrows;
  19641. bool readAheadDone;
  19642. unsigned readIndex;
  19643. unsigned lastGroupProcessed;
  19644. bool someInGroup = false;
  19645. public:
  19646. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19647. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19648. {
  19649. compoundHelper = (IHThorDiskReadArg *)&helper;
  19650. readHelper = (IHThorDiskReadArg *)&helper;
  19651. limitTransformExtra = readHelper;
  19652. readAheadDone = false;
  19653. readIndex = 0;
  19654. lastGroupProcessed = processed;
  19655. }
  19656. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19657. {
  19658. rowLimit = compoundHelper->getRowLimit();
  19659. stopAfter = compoundHelper->getChooseNLimit();
  19660. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19661. readAheadDone = false;
  19662. readIndex = 0;
  19663. lastGroupProcessed = processed;
  19664. someInGroup = false;
  19665. }
  19666. virtual void reset()
  19667. {
  19668. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19669. readrows.kill();
  19670. readAheadDone = false;
  19671. readIndex = 0;
  19672. lastGroupProcessed = processed;
  19673. someInGroup = false;
  19674. CRoxieServerDiskReadBaseActivity::reset();
  19675. }
  19676. virtual const void *nextRow()
  19677. {
  19678. ActivityTimer t(totalCycles, timeActivities);
  19679. if (eof)
  19680. return NULL;
  19681. else if (useRemote())
  19682. return remote->nextRow();
  19683. else if (maySkip)
  19684. {
  19685. if (!readAheadDone)
  19686. {
  19687. unsigned preprocessed = 0;
  19688. while (!eof)
  19689. {
  19690. const void *row = _nextRow();
  19691. if (row)
  19692. preprocessed++;
  19693. if (preprocessed > rowLimit)
  19694. {
  19695. ReleaseRoxieRow(row);
  19696. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19697. readrows.kill();
  19698. readIndex = 0;
  19699. eof = true;
  19700. if (ctx->queryDebugContext())
  19701. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19702. if (helper.getFlags() & TDRlimitskips)
  19703. return NULL;
  19704. else if (helper.getFlags() & TDRlimitcreates)
  19705. return createLimitFailRow(false);
  19706. else
  19707. throwUnexpected();
  19708. }
  19709. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19710. {
  19711. eof = true;
  19712. ReleaseRoxieRow(row);
  19713. break;
  19714. }
  19715. readrows.append(row);
  19716. }
  19717. readAheadDone = true;
  19718. }
  19719. if (readrows.isItem(readIndex))
  19720. {
  19721. const void *ret = readrows.item(readIndex++);
  19722. if (ret)
  19723. processed++;
  19724. return ret;
  19725. }
  19726. else
  19727. {
  19728. eof = true;
  19729. return NULL;
  19730. }
  19731. }
  19732. else
  19733. {
  19734. const void *ret = _nextRow();
  19735. if (ret)
  19736. {
  19737. processed++;
  19738. if (processed > rowLimit)
  19739. {
  19740. if (traceLevel > 4)
  19741. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19742. ReleaseRoxieRow(ret);
  19743. compoundHelper->onLimitExceeded();
  19744. throwUnexpected(); // onLimitExceeded is not supposed to return
  19745. }
  19746. if (processed > stopAfter) // MORE - bit of a strange place to check
  19747. {
  19748. eof = true;
  19749. ReleaseRoxieRow(ret);
  19750. return NULL;
  19751. }
  19752. }
  19753. return ret;
  19754. }
  19755. }
  19756. const void *_nextRow()
  19757. {
  19758. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19759. unsigned transformedSize = 0;
  19760. for (;;)
  19761. {
  19762. const byte *nextRec = reader->nextRow();
  19763. if (nextRec)
  19764. {
  19765. someInGroup = true;
  19766. if (likely(readHelper->canMatch(nextRec)))
  19767. {
  19768. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19769. reader->finishedRow();
  19770. if (transformedSize)
  19771. break;
  19772. }
  19773. else
  19774. reader->finishedRow();
  19775. }
  19776. else if (isGrouped)
  19777. {
  19778. if (lastGroupProcessed != processed)
  19779. {
  19780. someInGroup = false;
  19781. lastGroupProcessed = processed;
  19782. return nullptr;
  19783. }
  19784. else if (!someInGroup)
  19785. {
  19786. eof = true;
  19787. return nullptr;
  19788. }
  19789. }
  19790. else
  19791. {
  19792. eof = true;
  19793. return nullptr;
  19794. }
  19795. }
  19796. return rowBuilder.finalizeRowClear(transformedSize);
  19797. }
  19798. };
  19799. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19800. {
  19801. IHThorXmlReadArg * readHelper;
  19802. Owned<IXmlToRowTransformer> rowTransformer;
  19803. Owned<IXMLParse> xmlParser;
  19804. Owned<IColumnProvider> lastMatch;
  19805. unsigned __int64 fileoffset;
  19806. IDirectStreamReader *streamReader = nullptr;
  19807. public:
  19808. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19809. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19810. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19811. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19812. {
  19813. compoundHelper = NULL;
  19814. readHelper = (IHThorXmlReadArg *)&helper;
  19815. fileoffset = 0;
  19816. }
  19817. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19818. {
  19819. rowLimit = readHelper->getRowLimit();
  19820. stopAfter = readHelper->getChooseNLimit();
  19821. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19822. if (!useRemote())
  19823. {
  19824. rowTransformer.set(readHelper->queryTransformer());
  19825. assertex(reader != NULL);
  19826. streamReader = reader->queryDirectStreamReader();
  19827. assertex(streamReader != NULL);
  19828. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19829. if (factory->getKind()==TAKjsonread)
  19830. xmlParser.setown(createJSONParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19831. else
  19832. xmlParser.setown(createXMLParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19833. }
  19834. }
  19835. virtual void reset()
  19836. {
  19837. CRoxieServerDiskReadBaseActivity::reset();
  19838. rowTransformer.clear();
  19839. xmlParser.clear();
  19840. }
  19841. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19842. {
  19843. fileoffset = startOffset;
  19844. lastMatch.set(&entry);
  19845. }
  19846. //interface IThorDiskCallback
  19847. virtual unsigned __int64 getFilePosition(const void * row)
  19848. {
  19849. return fileoffset;
  19850. }
  19851. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19852. {
  19853. return streamReader->makeFilePositionLocal(fileoffset);
  19854. }
  19855. virtual const char * queryLogicalFilename(const void * row)
  19856. {
  19857. return reader->queryLogicalFilename(row);
  19858. }
  19859. virtual const byte * lookupBlob(unsigned __int64 id) { UNIMPLEMENTED; }
  19860. virtual const void *nextRow()
  19861. {
  19862. ActivityTimer t(totalCycles, timeActivities);
  19863. if (eof)
  19864. return NULL;
  19865. else if (useRemote())
  19866. return remote->nextRow();
  19867. assertex(xmlParser != NULL);
  19868. try
  19869. {
  19870. while (!eof)
  19871. {
  19872. //call to next() will callback on the IXmlSelect interface
  19873. bool gotNext = false;
  19874. gotNext = xmlParser->next();
  19875. if(!gotNext)
  19876. eof = true;
  19877. else if (lastMatch)
  19878. {
  19879. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19880. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19881. lastMatch.clear();
  19882. fileoffset = 0;
  19883. if (sizeGot)
  19884. {
  19885. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19886. if (processed > rowLimit)
  19887. {
  19888. if (traceLevel > 4)
  19889. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19890. readHelper->onLimitExceeded();
  19891. throwUnexpected(); // onLimitExceeded is not supposed to return
  19892. }
  19893. processed++;
  19894. if (processed > stopAfter) // MORE - bit of a strange place to check
  19895. {
  19896. eof = true;
  19897. return NULL;
  19898. }
  19899. return ret.getClear();
  19900. }
  19901. }
  19902. }
  19903. return NULL;
  19904. }
  19905. catch(IException *E)
  19906. {
  19907. throw makeWrappedException(E);
  19908. }
  19909. }
  19910. };
  19911. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19912. {
  19913. IHThorCsvReadArg *readHelper;
  19914. ICsvParameters * csvInfo;
  19915. unsigned headerLines;
  19916. unsigned maxDiskSize;
  19917. CSVSplitter csvSplitter;
  19918. unsigned __int64 localOffset;
  19919. IDirectStreamReader *streamReader = nullptr;
  19920. const char *quotes;
  19921. const char *separators;
  19922. const char *terminators;
  19923. const char *escapes;
  19924. size32_t maxRowSize;
  19925. public:
  19926. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19927. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators,
  19928. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19929. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators),
  19930. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19931. {
  19932. compoundHelper = NULL;
  19933. readHelper = (IHThorCsvReadArg *)&helper;
  19934. rowLimit = readHelper->getRowLimit();
  19935. stopAfter = readHelper->getChooseNLimit();
  19936. csvInfo = readHelper->queryCsvParameters();
  19937. maxDiskSize = csvInfo->queryMaxSize();
  19938. localOffset = 0;
  19939. headerLines = 0;
  19940. }
  19941. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19942. {
  19943. rowLimit = readHelper->getRowLimit();
  19944. stopAfter = readHelper->getChooseNLimit();
  19945. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19946. if (!useRemote())
  19947. {
  19948. if (!eof)
  19949. {
  19950. assertex(reader != nullptr);
  19951. streamReader = reader->queryDirectStreamReader();
  19952. assertex(streamReader != nullptr);
  19953. headerLines = csvInfo->queryHeaderLen();
  19954. if (headerLines && isLocal && streamReader->queryFilePart() != 1)
  19955. 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...
  19956. if (varFileInfo)
  19957. {
  19958. const IPropertyTree *options = varFileInfo->queryProperties();
  19959. if (options)
  19960. {
  19961. quotes = options->queryProp("@csvQuote");
  19962. separators = options->queryProp("@csvSeparate");
  19963. terminators = options->queryProp("@csvTerminate");
  19964. escapes = options->queryProp("@csvEscape");
  19965. }
  19966. }
  19967. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  19968. }
  19969. }
  19970. }
  19971. virtual const void *nextRow()
  19972. {
  19973. ActivityTimer t(totalCycles, timeActivities);
  19974. if (eof)
  19975. return NULL;
  19976. else if (useRemote())
  19977. return remote->nextRow();
  19978. try
  19979. {
  19980. while (!eof)
  19981. {
  19982. size32_t thisLineLength = csvSplitter.splitLine(streamReader, maxRowSize);
  19983. if (!thisLineLength)
  19984. break;
  19985. if (headerLines)
  19986. {
  19987. headerLines--;
  19988. streamReader->skip(thisLineLength);
  19989. }
  19990. else
  19991. {
  19992. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19993. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  19994. streamReader->skip(thisLineLength);
  19995. if (transformedSize)
  19996. {
  19997. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  19998. if (processed > rowLimit)
  19999. {
  20000. readHelper->onLimitExceeded();
  20001. throwUnexpected(); // onLimitExceeded is not supposed to return
  20002. }
  20003. processed++;
  20004. if (processed > stopAfter) // MORE - bit of a strange place to check
  20005. {
  20006. eof = true;
  20007. return NULL;
  20008. }
  20009. return ret.getClear();
  20010. }
  20011. }
  20012. }
  20013. return NULL;
  20014. }
  20015. catch(IException *E)
  20016. {
  20017. throw makeWrappedException(E);
  20018. }
  20019. }
  20020. virtual void reset()
  20021. {
  20022. CRoxieServerDiskReadBaseActivity::reset();
  20023. csvSplitter.reset();
  20024. localOffset = 0;
  20025. }
  20026. virtual unsigned __int64 getFilePosition(const void * row)
  20027. {
  20028. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  20029. }
  20030. virtual unsigned __int64 getLocalFilePosition(const void * row)
  20031. {
  20032. UNIMPLEMENTED;
  20033. }
  20034. };
  20035. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  20036. {
  20037. IHThorDiskNormalizeArg *normalizeHelper;
  20038. bool firstPending;
  20039. public:
  20040. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20041. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager, _translators)
  20042. {
  20043. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  20044. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  20045. limitTransformExtra = normalizeHelper;
  20046. firstPending = true;
  20047. }
  20048. virtual void reset()
  20049. {
  20050. firstPending = true;
  20051. CRoxieServerDiskReadBaseActivity::reset();
  20052. }
  20053. virtual const void *nextRow()
  20054. {
  20055. ActivityTimer t(totalCycles, timeActivities);
  20056. if (eof)
  20057. return NULL;
  20058. else if (useRemote())
  20059. return remote->nextRow();
  20060. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20061. unsigned transformedSize = 0;
  20062. for (;;)
  20063. {
  20064. while (firstPending)
  20065. {
  20066. const byte *nextRec = reader->nextRow();
  20067. if (!nextRec)
  20068. {
  20069. eof = true;
  20070. return NULL;
  20071. }
  20072. if (normalizeHelper->first(nextRec))
  20073. firstPending = false;
  20074. reader->finishedRow();
  20075. }
  20076. transformedSize = normalizeHelper->transform(rowBuilder);
  20077. firstPending = !normalizeHelper->next();
  20078. if (transformedSize)
  20079. break;
  20080. }
  20081. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  20082. processed++;
  20083. if (processed > rowLimit)
  20084. {
  20085. compoundHelper->onLimitExceeded();
  20086. throwUnexpected(); // onLimitExceeded is not supposed to return
  20087. }
  20088. if (processed > stopAfter) // MORE - bit of a strange place to check
  20089. {
  20090. eof = true;
  20091. return NULL;
  20092. }
  20093. return recBuffer.getClear();
  20094. }
  20095. };
  20096. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  20097. {
  20098. protected:
  20099. bool done;
  20100. public:
  20101. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20102. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager, _translators),
  20103. done(false)
  20104. {
  20105. }
  20106. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20107. {
  20108. done = false;
  20109. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20110. }
  20111. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  20112. {
  20113. if (idx==(unsigned)-1)
  20114. idx = 0;
  20115. return idx ? NULL: this;
  20116. }
  20117. };
  20118. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  20119. {
  20120. IHThorDiskCountArg & countHelper;
  20121. unsigned __int64 choosenLimit;
  20122. unsigned __int64 getSkippedCount()
  20123. {
  20124. unsigned flags = countHelper.getFlags();
  20125. if (flags & TDRlimitskips)
  20126. return 0;
  20127. else if (flags & TDRlimitcreates)
  20128. return 1;
  20129. else
  20130. {
  20131. countHelper.onLimitExceeded();
  20132. throwUnexpected(); // onLimitExceeded should always throw exception
  20133. }
  20134. }
  20135. public:
  20136. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20137. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20138. countHelper((IHThorDiskCountArg &)basehelper)
  20139. {
  20140. choosenLimit = 0;
  20141. }
  20142. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20143. {
  20144. choosenLimit = countHelper.getChooseNLimit();
  20145. rowLimit = countHelper.getRowLimit();
  20146. // keyedLimit = countHelper->getKeyedLimit(); // more - should there be one?
  20147. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20148. }
  20149. virtual const void *nextRow()
  20150. {
  20151. ActivityTimer t(totalCycles, timeActivities);
  20152. if (done) return NULL;
  20153. done = true;
  20154. unsigned __int64 totalCount = 0;
  20155. if (helper.canMatchAny() && !eof)
  20156. {
  20157. if (useRemote())
  20158. {
  20159. for (;;)
  20160. {
  20161. const void * next = remote->nextRow();
  20162. if (!next)
  20163. break;
  20164. if (meta.getFixedSize() == 1)
  20165. totalCount += *(byte *)next;
  20166. else
  20167. totalCount += *(unsigned __int64 *)next;
  20168. ReleaseRoxieRow(next);
  20169. if (totalCount > rowLimit)
  20170. {
  20171. totalCount = getSkippedCount();
  20172. break;
  20173. }
  20174. else if (totalCount >= choosenLimit)
  20175. {
  20176. totalCount = choosenLimit;
  20177. break;
  20178. }
  20179. }
  20180. }
  20181. else
  20182. {
  20183. for (;;)
  20184. {
  20185. const byte *nextRec = reader->nextRow();
  20186. if (!nextRec)
  20187. break;
  20188. totalCount += countHelper.numValid(nextRec);
  20189. reader->finishedRow();
  20190. if (totalCount > rowLimit)
  20191. {
  20192. totalCount = getSkippedCount();
  20193. break;
  20194. }
  20195. else if (totalCount >= choosenLimit)
  20196. {
  20197. totalCount = choosenLimit;
  20198. break;
  20199. }
  20200. }
  20201. }
  20202. }
  20203. processed++;
  20204. size32_t rowSize = meta.getFixedSize();
  20205. void * result = rowAllocator->createRow();
  20206. if (rowSize == 1)
  20207. *(byte *)result = (byte)totalCount;
  20208. else
  20209. {
  20210. assertex(rowSize == sizeof(unsigned __int64));
  20211. *(unsigned __int64 *)result = totalCount;
  20212. }
  20213. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20214. }
  20215. };
  20216. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20217. {
  20218. IHThorCompoundAggregateExtra & aggregateHelper;
  20219. public:
  20220. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20221. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20222. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20223. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20224. {
  20225. }
  20226. const void * gatherMerged()
  20227. {
  20228. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20229. size32_t finalSize = 0;
  20230. if (useRemote())
  20231. {
  20232. const void * firstRow = remote->nextRow();
  20233. if (!firstRow)
  20234. {
  20235. rowBuilder.ensureRow();
  20236. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20237. }
  20238. else
  20239. {
  20240. // NOTE need to clone this because going to modify below, could special case 1 row only
  20241. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20242. ReleaseRoxieRow(firstRow);
  20243. }
  20244. for (;;)
  20245. {
  20246. const void * next = remote->nextRow();
  20247. if (!next)
  20248. break;
  20249. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20250. ReleaseRoxieRow(next);
  20251. }
  20252. }
  20253. else
  20254. {
  20255. aggregateHelper.clearAggregate(rowBuilder);
  20256. if (helper.canMatchAny() && !eof)
  20257. {
  20258. for (;;)
  20259. {
  20260. const byte *nextRec = reader->nextRow();
  20261. if (!nextRec)
  20262. break;
  20263. aggregateHelper.processRow(rowBuilder, nextRec);
  20264. reader->finishedRow();
  20265. }
  20266. }
  20267. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20268. }
  20269. return rowBuilder.finalizeRowClear(finalSize);
  20270. }
  20271. virtual const void *nextRow()
  20272. {
  20273. ActivityTimer t(totalCycles, timeActivities);
  20274. if (done) return NULL;
  20275. const void * ret = gatherMerged();
  20276. processed++;
  20277. done = true;
  20278. return ret;
  20279. }
  20280. };
  20281. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20282. {
  20283. IHThorDiskGroupAggregateArg & aggregateHelper;
  20284. RowAggregator resultAggregator;
  20285. bool gathered;
  20286. public:
  20287. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20288. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20289. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20290. resultAggregator(aggregateHelper, aggregateHelper),
  20291. gathered(false)
  20292. {
  20293. }
  20294. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20295. {
  20296. gathered= false;
  20297. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20298. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  20299. }
  20300. virtual void reset()
  20301. {
  20302. resultAggregator.reset();
  20303. CRoxieServerDiskAggregateBaseActivity::reset();
  20304. }
  20305. void gatherMerged()
  20306. {
  20307. if (useRemote())
  20308. {
  20309. for (;;)
  20310. {
  20311. const void * next = remote->nextRow();
  20312. if (!next)
  20313. break;
  20314. resultAggregator.mergeElement(next);
  20315. ReleaseRoxieRow(next);
  20316. }
  20317. }
  20318. else
  20319. {
  20320. if (helper.canMatchAny() && !eof)
  20321. {
  20322. Owned<IInMemoryFileProcessor> processor = createGroupAggregateRecordProcessor(resultAggregator, aggregateHelper, reader);
  20323. processor->doQuery(NULL, 0, 0, 0);
  20324. }
  20325. }
  20326. gathered = true;
  20327. }
  20328. virtual const void *nextRow()
  20329. {
  20330. ActivityTimer t(totalCycles, timeActivities);
  20331. if (done)
  20332. return NULL;
  20333. if (!gathered)
  20334. gatherMerged();
  20335. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20336. if (next)
  20337. {
  20338. processed++;
  20339. return next->finalizeRowClear();
  20340. }
  20341. done = true;
  20342. return NULL;
  20343. }
  20344. };
  20345. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20346. {
  20347. public:
  20348. RemoteActivityId remoteId;
  20349. bool isLocal;
  20350. bool sorted;
  20351. bool maySkip;
  20352. bool variableFileName;
  20353. Owned<ITranslatorSet> translators;
  20354. Owned<IInMemoryIndexManager> manager;
  20355. Owned<const IResolvedFile> datafile;
  20356. const char *quotes;
  20357. const char *separators;
  20358. const char *terminators;
  20359. const char *escapes;
  20360. size32_t maxCsvRowSize;
  20361. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20362. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20363. {
  20364. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20365. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20366. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20367. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20368. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20369. quotes = separators = terminators = escapes = NULL;
  20370. if (!variableFileName)
  20371. {
  20372. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20373. OwnedRoxieString fileName(helper->getFileName());
  20374. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20375. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20376. if (isLocal || isSimple)
  20377. {
  20378. if (datafile)
  20379. {
  20380. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20381. unsigned expectedFormatCrc = helper->getDiskFormatCrc();
  20382. unsigned projectedFormatCrc = helper->getProjectedFormatCrc();
  20383. translators.setown(datafile->getTranslators(projectedFormatCrc, helper->queryProjectedDiskRecordSize(), expectedFormatCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  20384. manager.setown(datafile->getIndexManager(isOpt, channel, translators->queryActualLayout(0), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false)));
  20385. const IPropertyTree *options = datafile->queryProperties();
  20386. if (options)
  20387. {
  20388. quotes = options->queryProp("@csvQuote");
  20389. separators = options->queryProp("@csvSeparate");
  20390. terminators = options->queryProp("@csvTerminate");
  20391. escapes = options->queryProp("@csvEscape");
  20392. }
  20393. }
  20394. else
  20395. manager.setown(createInMemoryIndexManager(helper->queryProjectedDiskRecordSize()->queryRecordAccessor(true), true, nullptr));
  20396. }
  20397. }
  20398. switch (kind)
  20399. {
  20400. case TAKcsvread:
  20401. {
  20402. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20403. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20404. if (workunit)
  20405. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20406. break;
  20407. }
  20408. default:
  20409. maxCsvRowSize = 0; // unused
  20410. }
  20411. }
  20412. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20413. {
  20414. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20415. switch (kind)
  20416. {
  20417. case TAKcsvread:
  20418. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators,
  20419. quotes, separators, terminators, escapes, maxCsvRowSize);
  20420. case TAKxmlread:
  20421. case TAKjsonread:
  20422. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20423. case TAKdiskread:
  20424. case TAKspillread:
  20425. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20426. case TAKdisknormalize:
  20427. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager, translators);
  20428. case TAKdiskcount:
  20429. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20430. case TAKdiskaggregate:
  20431. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20432. case TAKdiskgroupaggregate:
  20433. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20434. }
  20435. throwUnexpected();
  20436. }
  20437. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20438. {
  20439. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20440. }
  20441. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20442. {
  20443. if (datafile)
  20444. addXrefFileInfo(reply, datafile);
  20445. else
  20446. {
  20447. // Temporarily resolve the file
  20448. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20449. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20450. {
  20451. OwnedRoxieString fileName(helper->getFileName());
  20452. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20453. if (temp)
  20454. addXrefFileInfo(reply, temp);
  20455. }
  20456. }
  20457. }
  20458. virtual const StatisticsMapping &queryStatsMapping() const
  20459. {
  20460. return diskStatistics;
  20461. }
  20462. };
  20463. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20464. {
  20465. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20466. }
  20467. //=================================================================================
  20468. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20469. {
  20470. public:
  20471. Owned<IKeyArray> keySet;
  20472. Owned<ITranslatorSet> translators;
  20473. RemoteActivityId remoteId;
  20474. bool isSimple;
  20475. bool isLocal;
  20476. bool maySkip;
  20477. bool sorted;
  20478. bool variableFileName;
  20479. unsigned maxSeekLookahead;
  20480. Owned<const IResolvedFile> indexfile;
  20481. CRoxieServerSideCache *cache;
  20482. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20483. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20484. {
  20485. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20486. unsigned flags = indexHelper->getFlags();
  20487. sorted = (flags & TIRunordered) == 0;
  20488. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20489. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20490. if (!variableFileName)
  20491. {
  20492. bool isOpt = (flags & TIRoptional) != 0;
  20493. OwnedRoxieString indexName(indexHelper->getFileName());
  20494. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  20495. if (indexfile)
  20496. {
  20497. unsigned projectedCrc = indexHelper->getProjectedFormatCrc();
  20498. unsigned expectedCrc = indexHelper->getDiskFormatCrc();
  20499. IOutputMetaData *projectedMeta = indexHelper->queryProjectedDiskRecordSize();
  20500. IOutputMetaData *expectedMeta = indexHelper->queryDiskRecordSize();
  20501. translators.setown(indexfile->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  20502. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  20503. }
  20504. }
  20505. isSimple = isLocal;
  20506. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20507. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20508. {
  20509. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20510. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20511. isSimple = true;
  20512. }
  20513. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20514. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20515. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20516. }
  20517. ~CRoxieServerBaseIndexActivityFactory()
  20518. {
  20519. delete cache;
  20520. }
  20521. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20522. {
  20523. if (indexfile)
  20524. addXrefFileInfo(reply, indexfile);
  20525. else
  20526. {
  20527. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20528. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20529. {
  20530. OwnedRoxieString indexName(indexHelper->getFileName());
  20531. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  20532. if (temp)
  20533. addXrefFileInfo(reply, temp);
  20534. }
  20535. }
  20536. }
  20537. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20538. {
  20539. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20540. }
  20541. virtual IRoxieServerSideCache *queryServerSideCache() const
  20542. {
  20543. return cache;
  20544. }
  20545. virtual const StatisticsMapping &queryStatsMapping() const
  20546. {
  20547. return indexStatistics;
  20548. }
  20549. };
  20550. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20551. {
  20552. protected:
  20553. IHThorIndexReadBaseArg &indexHelper;
  20554. IHThorSteppedSourceExtra *steppedExtra;
  20555. Linked<IKeyArray> keySet;
  20556. Linked<ITranslatorSet> translators;
  20557. CSkippableRemoteResultAdaptor remote;
  20558. CIndexTransformCallback callback;
  20559. bool sorted;
  20560. bool variableFileName;
  20561. bool variableInfoPending;
  20562. bool isOpt;
  20563. bool isLocal;
  20564. unsigned __int64 rowLimit;
  20565. unsigned __int64 keyedLimit;
  20566. unsigned __int64 choosenLimit;
  20567. unsigned accepted;
  20568. unsigned rejected;
  20569. unsigned seekGEOffset;
  20570. Owned<IKeyManager> tlk;
  20571. Owned<const IResolvedFile> varFileInfo;
  20572. const RemoteActivityId &remoteId;
  20573. void setVariableFileInfo()
  20574. {
  20575. OwnedRoxieString indexName(indexHelper.getFileName());
  20576. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  20577. if (varFileInfo)
  20578. {
  20579. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  20580. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  20581. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  20582. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  20583. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  20584. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  20585. }
  20586. variableInfoPending = false;
  20587. }
  20588. public:
  20589. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20590. bool _sorted, bool _isLocal, bool _maySkip)
  20591. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20592. keySet(_factory->keySet),
  20593. translators(_factory->translators),
  20594. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20595. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20596. remoteId(_remoteId),
  20597. sorted(_sorted),
  20598. isLocal(_isLocal)
  20599. {
  20600. indexHelper.setCallback(&callback);
  20601. steppedExtra = indexHelper.querySteppingExtra();
  20602. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20603. variableInfoPending = false;
  20604. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20605. seekGEOffset = 0;
  20606. // started = false;
  20607. rejected = accepted = 0;
  20608. rowLimit = choosenLimit = keyedLimit = 0;
  20609. }
  20610. virtual const IResolvedFile *queryVarFileInfo() const
  20611. {
  20612. return varFileInfo;
  20613. }
  20614. virtual void onCreate(IHThorArg *_colocalParent)
  20615. {
  20616. CRoxieServerActivity::onCreate(_colocalParent);
  20617. remote.onCreate(_colocalParent);
  20618. }
  20619. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20620. {
  20621. accepted = 0;
  20622. rejected = 0;
  20623. rowLimit = (unsigned __int64) -1;
  20624. keyedLimit = (unsigned __int64 ) -1;
  20625. choosenLimit = I64C(0x7fffffffffffffff);
  20626. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20627. remote.onStart(parentExtractSize, parentExtract);
  20628. variableInfoPending = variableFileName;
  20629. }
  20630. void processAllKeys()
  20631. {
  20632. try
  20633. {
  20634. bool noLocal = factory->queryQueryFactory().queryOptions().disableLocalOptimizations || seekGEOffset > 0;
  20635. if (indexHelper.canMatchAny())
  20636. {
  20637. if (variableInfoPending)
  20638. setVariableFileInfo();
  20639. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20640. if (keySet)
  20641. {
  20642. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20643. // 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
  20644. // However order is probably better to iterate fileno's inside partnos
  20645. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20646. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20647. {
  20648. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20649. if (thisBase)
  20650. {
  20651. unsigned fileNo = 0;
  20652. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20653. if (!thisKey->isTopLevelKey())
  20654. {
  20655. if (keyedLimit != (unsigned __int64) -1)
  20656. {
  20657. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20658. {
  20659. Owned<IKeyManager> countKey;
  20660. countKey.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20661. countKey->setLayoutTranslator(translators->queryTranslator(fileNo));
  20662. createSegmentMonitors(countKey);
  20663. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20664. if (count > keyedLimit)
  20665. {
  20666. if (traceLevel > 4)
  20667. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20668. onLimitExceeded(true);
  20669. }
  20670. }
  20671. }
  20672. }
  20673. if (seekGEOffset && !thisKey->isTopLevelKey())
  20674. {
  20675. tlk.setown(createSingleKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  20676. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20677. }
  20678. else
  20679. {
  20680. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors()));
  20681. if (!thisKey->isTopLevelKey())
  20682. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20683. else
  20684. tlk->setLayoutTranslator(nullptr);
  20685. }
  20686. createSegmentMonitors(tlk);
  20687. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20688. {
  20689. StringBuffer out;
  20690. tlk->describeFilter(out);
  20691. CTXLOG("Using filter %s", out.str());
  20692. if (ctx->queryProbeManager())
  20693. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20694. }
  20695. tlk->reset();
  20696. for (;;) // for each file part
  20697. {
  20698. //block for TransformCallbackAssociation
  20699. {
  20700. TransformCallbackAssociation associate(callback, tlk);
  20701. if (thisKey->isTopLevelKey())
  20702. {
  20703. if (thisKey->isFullySorted())
  20704. {
  20705. while (tlk->lookup(false))
  20706. {
  20707. unsigned slavePart = (unsigned)extractFpos(tlk);
  20708. if (slavePart)
  20709. {
  20710. accepted++;
  20711. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20712. if (sorted && numChannels>1)
  20713. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20714. }
  20715. }
  20716. }
  20717. else
  20718. {
  20719. unsigned slavePart = tlk->getPartition(); // Returns 0 if no partition info, or filter cannot be partitioned
  20720. remote.getMem(slavePart, fileNo, 0);
  20721. }
  20722. }
  20723. else
  20724. {
  20725. // Single - part key. We process locally unless smart-stepping is involved, in which case we need to ensure that
  20726. // we do the proper two-stage merge.
  20727. // Unfortunately processSingleKey will not use the merger we carefully set up before,
  20728. // so we disable the local processing in that case
  20729. if (noLocal)
  20730. remote.getMem(1, fileNo, 0); // 1 because it's a single part key
  20731. else if (processSingleKey(thisKey, translators->queryTranslator(fileNo)))
  20732. break;
  20733. }
  20734. }
  20735. if (++fileNo < thisBase->numParts())
  20736. {
  20737. thisKey = thisBase->queryPart(fileNo);
  20738. tlk->setKey(thisKey);
  20739. if (!thisKey->isTopLevelKey())
  20740. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20741. else
  20742. tlk->setLayoutTranslator(nullptr);
  20743. tlk->reset();
  20744. }
  20745. else
  20746. break;
  20747. }
  20748. tlk->releaseSegmentMonitors();
  20749. tlk->setKey(NULL);
  20750. }
  20751. }
  20752. }
  20753. }
  20754. remote.flush();
  20755. remote.senddone();
  20756. }
  20757. catch (IException *E)
  20758. {
  20759. remote.setException(E);
  20760. }
  20761. }
  20762. virtual void createSegmentMonitors(IKeyManager *key)
  20763. {
  20764. indexHelper.createSegmentMonitors(key);
  20765. key->finishSegmentMonitors();
  20766. }
  20767. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) = 0;
  20768. virtual void reset()
  20769. {
  20770. if (accepted)
  20771. noteStatistic(StNumIndexAccepted, accepted);
  20772. if (rejected)
  20773. noteStatistic(StNumIndexRejected, rejected);
  20774. remote.onReset();
  20775. CRoxieServerActivity::reset();
  20776. if (varFileInfo)
  20777. {
  20778. keySet.clear();
  20779. varFileInfo.clear();
  20780. }
  20781. variableInfoPending = false;
  20782. }
  20783. virtual void stop()
  20784. {
  20785. remote.onStop();
  20786. CRoxieServerActivity::stop();
  20787. }
  20788. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20789. {
  20790. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20791. }
  20792. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  20793. {
  20794. CRoxieServerActivity::gatherStats(merged);
  20795. remote.gatherStats(merged);
  20796. }
  20797. };
  20798. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20799. {
  20800. protected:
  20801. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  20802. public:
  20803. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20804. bool _sorted, bool _isLocal, bool _maySkip)
  20805. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip)
  20806. {
  20807. }
  20808. virtual void reset()
  20809. {
  20810. remote.onReset();
  20811. CRoxieServerIndexActivity::reset();
  20812. }
  20813. virtual const void *nextRow()
  20814. {
  20815. ActivityTimer t(totalCycles, timeActivities);
  20816. try
  20817. {
  20818. const void *ret = remote.nextRow();
  20819. if (ret)
  20820. processed++;
  20821. return ret;
  20822. }
  20823. catch (IException *E)
  20824. {
  20825. throw makeWrappedException(E);
  20826. }
  20827. }
  20828. protected:
  20829. virtual const void * createLimitFailRow(bool isKeyed)
  20830. {
  20831. ensureRowAllocator();
  20832. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20833. assertex(limitTransformExtra);
  20834. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20835. if (outSize)
  20836. return rowBuilder.finalizeRowClear(outSize);
  20837. return NULL;
  20838. }
  20839. };
  20840. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20841. {
  20842. protected:
  20843. IHThorIndexReadArg & readHelper;
  20844. ISteppingMeta *rawMeta = nullptr;
  20845. CSteppingMeta steppingMeta;
  20846. unsigned * seekSizes = nullptr;
  20847. bool optimizeSteppedPostFilter;
  20848. ISteppingMeta * projectedMeta = nullptr;
  20849. unsigned maxSeekLookahead;
  20850. public:
  20851. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20852. bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20853. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  20854. readHelper((IHThorIndexReadArg &)basehelper)
  20855. {
  20856. limitTransformExtra = &readHelper;
  20857. rawMeta = readHelper.queryRawSteppingMeta();
  20858. unsigned flags = indexHelper.getFlags();
  20859. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20860. seekSizes = NULL;
  20861. maxSeekLookahead = _maxSeekLookahead;
  20862. if (rawMeta)
  20863. {
  20864. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20865. unsigned maxFields = rawMeta->getNumFields();
  20866. seekGEOffset = fields[0].offset;
  20867. seekSizes = new unsigned[maxFields];
  20868. seekSizes[0] = fields[0].size;
  20869. for (unsigned i=1; i < maxFields; i++)
  20870. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20871. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20872. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20873. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20874. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20875. steppingMeta.init(useMeta, hasPostFilter);
  20876. }
  20877. }
  20878. ~CRoxieServerIndexReadActivity()
  20879. {
  20880. delete [] seekSizes;
  20881. }
  20882. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20883. {
  20884. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20885. steppingMeta.setDistributed();
  20886. if (steppedExtra)
  20887. steppingMeta.setExtra(steppedExtra);
  20888. rowLimit = readHelper.getRowLimit();
  20889. keyedLimit = readHelper.getKeyedLimit();
  20890. choosenLimit = readHelper.getChooseNLimit();
  20891. if (!paused)
  20892. processAllKeys();
  20893. }
  20894. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20895. {
  20896. public:
  20897. IMPLEMENT_IINTERFACE;
  20898. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20899. {
  20900. Link();
  20901. return const_cast<LazyLocalKeyReader*> (this);
  20902. }
  20903. virtual const void *getMessageHeader(unsigned &length) const
  20904. {
  20905. length = 0;
  20906. return NULL;
  20907. }
  20908. virtual const void *getMessageMetadata(unsigned &length) const
  20909. {
  20910. length = 0;
  20911. return NULL;
  20912. }
  20913. virtual void discard() const
  20914. {
  20915. // nothing to do.
  20916. }
  20917. unsigned keyedCount;
  20918. unsigned matched;
  20919. bool EOFseen;
  20920. Owned<IKeyIndexSet> keySet;
  20921. Owned<IKeyManager> tlk;
  20922. CRoxieServerIndexReadActivity &owner;
  20923. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, const IDynamicTransform * trans)
  20924. : owner(_owner)
  20925. {
  20926. keyedCount = 0;
  20927. matched = 0;
  20928. EOFseen = false;
  20929. keySet.setown(createKeyIndexSet());
  20930. keySet->addIndex(LINK(key));
  20931. if (owner.seekGEOffset)
  20932. tlk.setown(createKeyMerger(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet, owner.seekGEOffset, &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20933. else
  20934. tlk.setown(createLocalKeyManager(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet->queryPart(0), &owner, owner.indexHelper.hasNewSegmentMonitors()));
  20935. if (!key->isTopLevelKey())
  20936. tlk->setLayoutTranslator(trans);
  20937. owner.indexHelper.createSegmentMonitors(tlk);
  20938. tlk->finishSegmentMonitors();
  20939. tlk->reset();
  20940. }
  20941. virtual const void *getNext(int length)
  20942. {
  20943. TransformCallbackAssociation associate(owner.callback, tlk);
  20944. while (tlk->lookup(true))
  20945. {
  20946. keyedCount++;
  20947. if (keyedCount > owner.keyedLimit)
  20948. {
  20949. owner.onLimitExceeded(true); // Should throw exception
  20950. throwUnexpected();
  20951. }
  20952. size32_t transformedSize;
  20953. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  20954. byte const * keyRow = tlk->queryKeyBuffer();
  20955. if (likely(owner.readHelper.canMatch(keyRow)))
  20956. {
  20957. try
  20958. {
  20959. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  20960. owner.callback.finishedRow();
  20961. }
  20962. catch (IException *E)
  20963. {
  20964. throw owner.makeWrappedException(E);
  20965. }
  20966. if (transformedSize)
  20967. {
  20968. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  20969. matched++;
  20970. if (matched > owner.rowLimit)
  20971. {
  20972. owner.onLimitExceeded(false); // Should throw exception
  20973. throwUnexpected();
  20974. }
  20975. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  20976. {
  20977. break;
  20978. }
  20979. owner.accepted++;
  20980. return result.getClear();
  20981. }
  20982. else
  20983. owner.rejected++;
  20984. }
  20985. else
  20986. {
  20987. owner.callback.finishedRow(); // since filter might have accessed a blob
  20988. owner.rejected++;
  20989. }
  20990. }
  20991. EOFseen = true;
  20992. return NULL;
  20993. }
  20994. virtual bool atEOF() const
  20995. {
  20996. return EOFseen;
  20997. }
  20998. virtual bool isSerialized() const
  20999. {
  21000. return false;
  21001. }
  21002. };
  21003. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21004. {
  21005. ensureRowAllocator();
  21006. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  21007. return false;
  21008. }
  21009. virtual void onLimitExceeded(bool isKeyed)
  21010. {
  21011. if (traceLevel > 4)
  21012. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21013. if (isKeyed)
  21014. {
  21015. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21016. {
  21017. if (ctx->queryDebugContext())
  21018. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21019. throw makeLimitSkipException(true);
  21020. }
  21021. else
  21022. readHelper.onKeyedLimitExceeded();
  21023. }
  21024. else
  21025. {
  21026. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21027. {
  21028. if (ctx->queryDebugContext())
  21029. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21030. throw makeLimitSkipException(false);
  21031. }
  21032. else
  21033. readHelper.onLimitExceeded();
  21034. }
  21035. }
  21036. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  21037. {
  21038. out.append((unsigned short) numFields);
  21039. out.append((unsigned short) seekLen);
  21040. out.append((unsigned short) stepExtra.queryFlags());
  21041. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  21042. if (seeks)
  21043. {
  21044. unsigned lookahead = 40000/seekLen;
  21045. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  21046. lookahead = maxSeekLookahead;
  21047. seeks->ensureFilled(seek, numFields, lookahead);
  21048. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  21049. unsigned serialized = 1; // rawseek is always serialized...
  21050. unsigned patchLength = out.length();
  21051. out.append(serialized); // NOTE - we come back and patch with the actual value...
  21052. out.append(seekLen, rawSeek);
  21053. if (seeks->ordinality())
  21054. {
  21055. const void *lastSeek = rawSeek;
  21056. byte *nextSeek = NULL;
  21057. if (projectedMeta)
  21058. nextSeek = (byte *) alloca(seekLen);
  21059. for (unsigned i = 0; i < seeks->ordinality(); i++)
  21060. {
  21061. if (projectedMeta)
  21062. {
  21063. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  21064. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21065. }
  21066. else
  21067. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  21068. int diff = memcmp(nextSeek, lastSeek, seekLen);
  21069. if (diff > 0)
  21070. {
  21071. serialized++;
  21072. out.append(seekLen, nextSeek);
  21073. lastSeek = (const byte *) out.reserve(0) - seekLen;
  21074. }
  21075. }
  21076. unsigned length = out.length();
  21077. out.setWritePos(patchLength);
  21078. out.append(serialized);
  21079. out.setWritePos(length);
  21080. }
  21081. }
  21082. else
  21083. {
  21084. out.append(false);
  21085. out.append(1);
  21086. out.append(seekLen, rawSeek);
  21087. }
  21088. }
  21089. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21090. {
  21091. ActivityTimer t(totalCycles, timeActivities);
  21092. try
  21093. {
  21094. unsigned seeklen = 0;
  21095. const void *rawSeek = NULL;
  21096. if (seek && numFields)
  21097. {
  21098. seeklen = seekSizes[numFields-1];
  21099. rawSeek = (const byte *)seek + seekGEOffset;
  21100. if (projectedMeta)
  21101. {
  21102. byte * temp = (byte *) alloca(seeklen);
  21103. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  21104. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21105. rawSeek = (byte *)temp;
  21106. }
  21107. }
  21108. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  21109. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  21110. processed++;
  21111. return ret;
  21112. }
  21113. catch (IException *E)
  21114. {
  21115. throw makeWrappedException(E);
  21116. }
  21117. }
  21118. virtual IInputSteppingMeta * querySteppingMeta()
  21119. {
  21120. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21121. return &steppingMeta;
  21122. return NULL;
  21123. }
  21124. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21125. {
  21126. if (variableInfoPending)
  21127. setVariableFileInfo();
  21128. return this;
  21129. }
  21130. virtual IKeyArray *getKeySet() const
  21131. {
  21132. return keySet.getLink();
  21133. }
  21134. virtual const IResolvedFile *getVarFileInfo() const
  21135. {
  21136. return varFileInfo.getLink();
  21137. }
  21138. virtual ITranslatorSet *getTranslators() const override
  21139. {
  21140. return translators.getLink();
  21141. }
  21142. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21143. {
  21144. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21145. }
  21146. virtual IRoxieServerActivity *queryActivity() { return this; }
  21147. virtual const RemoteActivityId& queryRemoteId() const
  21148. {
  21149. return remoteId;
  21150. }
  21151. };
  21152. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  21153. {
  21154. IHThorIndexReadArg & indexHelper;
  21155. IHThorSteppedSourceExtra * steppedExtra;
  21156. bool eof;
  21157. Linked<IKeyArray>keySet;
  21158. Owned<IKeyIndexSet>keyIndexSet;
  21159. Owned<IKeyManager> tlk;
  21160. Linked<ITranslatorSet> translators;
  21161. CIndexTransformCallback callback;
  21162. unsigned __int64 keyedLimit;
  21163. unsigned rowLimit;
  21164. unsigned chooseNLimit;
  21165. unsigned accepted;
  21166. unsigned rejected;
  21167. unsigned keyedCount;
  21168. ISteppingMeta * rawMeta;
  21169. ISteppingMeta * projectedMeta;
  21170. size32_t seekGEOffset;
  21171. unsigned * seekSizes;
  21172. CSteppingMeta steppingMeta;
  21173. Owned<const IResolvedFile> varFileInfo;
  21174. const RemoteActivityId &remoteId;
  21175. bool firstRead;
  21176. bool variableFileName;
  21177. bool variableInfoPending;
  21178. bool isOpt;
  21179. bool isLocal;
  21180. bool optimizeSteppedPostFilter;
  21181. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  21182. void initKeySet()
  21183. {
  21184. if (keySet->length() > 1 || rawMeta != NULL)
  21185. {
  21186. if (translators->isTranslatingKeyed())
  21187. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Keyed Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  21188. if (!translators->hasConsistentTranslation())
  21189. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Mixture of layout translation is not available when merging key parts or smart-stepping");
  21190. }
  21191. keyIndexSet.setown(createKeyIndexSet());
  21192. for (unsigned part = 0; part < keySet->length(); part++)
  21193. {
  21194. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  21195. if (kib)
  21196. {
  21197. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  21198. {
  21199. IKeyIndex *k = kib->queryPart(subpart);
  21200. if (k)
  21201. {
  21202. assertex(!k->isTopLevelKey());
  21203. keyIndexSet->addIndex(LINK(k));
  21204. }
  21205. }
  21206. }
  21207. }
  21208. }
  21209. void setVariableFileInfo()
  21210. {
  21211. OwnedRoxieString indexName(indexHelper.getFileName());
  21212. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  21213. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  21214. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  21215. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  21216. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  21217. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  21218. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  21219. initKeySet();
  21220. variableInfoPending = false;
  21221. }
  21222. void onEOF()
  21223. {
  21224. callback.setManager(NULL);
  21225. eof = true;
  21226. tlk.clear();
  21227. }
  21228. public:
  21229. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21230. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21231. indexHelper((IHThorIndexReadArg &)basehelper),
  21232. translators(_factory->translators),
  21233. keySet(_factory->keySet),
  21234. isLocal(_isLocal),
  21235. remoteId(_remoteId)
  21236. {
  21237. rowLimit = 0;
  21238. keyedLimit = 0;
  21239. chooseNLimit = 0;
  21240. indexHelper.setCallback(&callback);
  21241. steppedExtra = indexHelper.querySteppingExtra();
  21242. unsigned flags = indexHelper.getFlags();
  21243. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21244. variableInfoPending = false;
  21245. isOpt = (flags & TIRoptional) != 0;
  21246. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21247. firstRead = true;
  21248. accepted = 0;
  21249. rejected = 0;
  21250. keyedCount = 0;
  21251. eof = false;
  21252. rawMeta = indexHelper.queryRawSteppingMeta();
  21253. projectedMeta = indexHelper.queryProjectedSteppingMeta();
  21254. seekGEOffset = 0;
  21255. seekSizes = NULL;
  21256. if (rawMeta)
  21257. {
  21258. // MORE - should check all keys in maxFields list can actually be keyed.
  21259. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21260. unsigned maxFields = rawMeta->getNumFields();
  21261. seekGEOffset = fields[0].offset;
  21262. seekSizes = new unsigned[maxFields];
  21263. seekSizes[0] = fields[0].size;
  21264. for (unsigned i=1; i < maxFields; i++)
  21265. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21266. bool hasPostFilter = indexHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21267. if (projectedMeta)
  21268. steppingMeta.init(projectedMeta, hasPostFilter);
  21269. else
  21270. steppingMeta.init(rawMeta, hasPostFilter);
  21271. }
  21272. }
  21273. virtual const IResolvedFile *queryVarFileInfo() const
  21274. {
  21275. return varFileInfo;
  21276. }
  21277. ~CRoxieServerSimpleIndexReadActivity()
  21278. {
  21279. delete [] seekSizes;
  21280. }
  21281. virtual bool needsAllocator() const { return true; }
  21282. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21283. {
  21284. firstRead = true;
  21285. accepted = 0;
  21286. rejected = 0;
  21287. keyedCount = 0;
  21288. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21289. if (steppedExtra)
  21290. steppingMeta.setExtra(steppedExtra);
  21291. eof = !indexHelper.canMatchAny();
  21292. if (variableFileName)
  21293. variableInfoPending = true;
  21294. else
  21295. {
  21296. variableInfoPending = false;
  21297. if (!keyIndexSet)
  21298. initKeySet();
  21299. }
  21300. }
  21301. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21302. {
  21303. if (variableInfoPending)
  21304. setVariableFileInfo();
  21305. return this;
  21306. }
  21307. virtual IKeyArray *getKeySet() const
  21308. {
  21309. return keySet.getLink();
  21310. }
  21311. virtual const IResolvedFile *getVarFileInfo() const
  21312. {
  21313. return varFileInfo.getLink();
  21314. }
  21315. virtual ITranslatorSet *getTranslators() const override
  21316. {
  21317. return translators.getLink();
  21318. }
  21319. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21320. {
  21321. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21322. }
  21323. virtual IRoxieServerActivity *queryActivity() { return this; }
  21324. virtual const RemoteActivityId& queryRemoteId() const
  21325. {
  21326. return remoteId;
  21327. }
  21328. const void *nextRow()
  21329. {
  21330. bool matched = true;
  21331. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21332. }
  21333. unsigned __int64 checkCount(unsigned __int64 limit)
  21334. {
  21335. unsigned numParts = keyIndexSet->numParts();
  21336. unsigned __int64 result = 0;
  21337. for (unsigned i = 0; i < numParts; i++)
  21338. {
  21339. Owned<IKeyManager> countTlk = createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(i), this, indexHelper.hasNewSegmentMonitors());
  21340. countTlk->setLayoutTranslator(translators->queryTranslator(i));
  21341. indexHelper.createSegmentMonitors(countTlk);
  21342. countTlk->finishSegmentMonitors();
  21343. result += countTlk->checkCount(limit-result);
  21344. if (result > limit)
  21345. break;
  21346. }
  21347. return result;
  21348. }
  21349. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21350. {
  21351. ActivityTimer t(totalCycles, timeActivities);
  21352. if (eof)
  21353. return NULL;
  21354. if (firstRead)
  21355. {
  21356. if (variableInfoPending)
  21357. setVariableFileInfo();
  21358. rowLimit = (unsigned) indexHelper.getRowLimit();
  21359. chooseNLimit = (unsigned) indexHelper.getChooseNLimit();
  21360. unsigned numParts = keyIndexSet->numParts();
  21361. if (!numParts)
  21362. {
  21363. onEOF();
  21364. return NULL;
  21365. }
  21366. if (numParts > 1 || seekGEOffset)
  21367. {
  21368. tlk.setown(createKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet, seekGEOffset, this, indexHelper.hasNewSegmentMonitors()));
  21369. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21370. }
  21371. else
  21372. {
  21373. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(0), this, indexHelper.hasNewSegmentMonitors()));
  21374. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21375. }
  21376. indexHelper.createSegmentMonitors(tlk);
  21377. tlk->finishSegmentMonitors();
  21378. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21379. {
  21380. StringBuffer out;
  21381. tlk->describeFilter(out);
  21382. CTXLOG("Using filter %s", out.str());
  21383. if (ctx->queryProbeManager())
  21384. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21385. }
  21386. tlk->reset();
  21387. callback.setManager(tlk);
  21388. keyedLimit = indexHelper.getKeyedLimit();
  21389. if (keyedLimit != (unsigned __int64) -1)
  21390. {
  21391. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21392. {
  21393. unsigned __int64 count = checkCount(keyedLimit);
  21394. if (count > keyedLimit)
  21395. {
  21396. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21397. indexHelper.onKeyedLimitExceeded();
  21398. const void * ret = NULL;
  21399. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21400. ret = createKeyedLimitOnFailRow();
  21401. onEOF();
  21402. return ret;
  21403. }
  21404. keyedLimit = (unsigned __int64) -1;
  21405. }
  21406. }
  21407. firstRead = false;
  21408. }
  21409. if (accepted == chooseNLimit)
  21410. {
  21411. onEOF();
  21412. return NULL;
  21413. }
  21414. const byte * rawSeek = NULL;
  21415. unsigned seekSize = 0;
  21416. if (seek)
  21417. {
  21418. seekSize = seekSizes[numFields-1];
  21419. rawSeek = (const byte *)seek + seekGEOffset;
  21420. if (projectedMeta)
  21421. {
  21422. byte *temp = (byte *) alloca(seekSize);
  21423. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21424. indexHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21425. rawSeek = (byte *)temp;
  21426. }
  21427. #ifdef _DEBUG
  21428. // StringBuffer seekStr;
  21429. // for (unsigned i = 0; i < seekSize; i++)
  21430. // {
  21431. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21432. // }
  21433. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21434. #endif
  21435. }
  21436. const byte * originalRawSeek = rawSeek;
  21437. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21438. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21439. {
  21440. checkAbort();
  21441. keyedCount++;
  21442. if (keyedCount > keyedLimit)
  21443. {
  21444. indexHelper.onKeyedLimitExceeded();
  21445. break;
  21446. }
  21447. byte const * keyRow = tlk->queryKeyBuffer();
  21448. if (likely(indexHelper.canMatch(keyRow)))
  21449. {
  21450. #ifdef _DEBUG
  21451. // StringBuffer recstr;
  21452. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21453. // for (unsigned i = 0; i < size; i++)
  21454. // {
  21455. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21456. // }
  21457. // DBGLOG("nextRowGE Got %s", recstr.str());
  21458. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21459. assertex(!"smart seek failure");
  21460. #endif
  21461. size32_t transformedSize;
  21462. rowBuilder.ensureRow();
  21463. try
  21464. {
  21465. transformedSize =indexHelper.transform(rowBuilder, keyRow);
  21466. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21467. //then return a mismatch record - so the join code can start seeking on the other input.
  21468. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21469. {
  21470. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21471. {
  21472. transformedSize = indexHelper.unfilteredTransform(rowBuilder, keyRow);
  21473. if (transformedSize != 0)
  21474. wasCompleteMatch = false;
  21475. }
  21476. }
  21477. callback.finishedRow();
  21478. }
  21479. catch (IException *E)
  21480. {
  21481. throw makeWrappedException(E);
  21482. }
  21483. if (transformedSize)
  21484. {
  21485. accepted++;
  21486. if (accepted > rowLimit)
  21487. {
  21488. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21489. {
  21490. throwUnexpected(); // should not have used simple variant if maySkip set...
  21491. }
  21492. if (traceLevel > 4)
  21493. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21494. indexHelper.onLimitExceeded();
  21495. break;
  21496. }
  21497. processed++;
  21498. #ifdef _DEBUG
  21499. // const byte *ret = (const byte *) out.get();
  21500. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21501. // queryOutputMeta()->toXML(ret, xmlwrite);
  21502. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21503. #endif
  21504. return rowBuilder.finalizeRowClear(transformedSize);
  21505. }
  21506. else
  21507. rejected++;
  21508. }
  21509. else
  21510. {
  21511. callback.finishedRow(); // since filter might have accessed a blob
  21512. rejected++;
  21513. }
  21514. rawSeek = NULL;
  21515. }
  21516. onEOF();
  21517. return NULL;
  21518. }
  21519. virtual void reset()
  21520. {
  21521. onEOF();
  21522. if (accepted)
  21523. noteStatistic(StNumIndexAccepted, accepted);
  21524. if (rejected)
  21525. noteStatistic(StNumIndexRejected, rejected);
  21526. if (variableFileName)
  21527. {
  21528. varFileInfo.clear();
  21529. translators.clear();
  21530. }
  21531. variableInfoPending = false;
  21532. CRoxieServerActivity::reset();
  21533. }
  21534. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21535. {
  21536. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21537. }
  21538. virtual IInputSteppingMeta * querySteppingMeta()
  21539. {
  21540. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21541. return &steppingMeta;
  21542. return NULL;
  21543. }
  21544. protected:
  21545. const void * createKeyedLimitOnFailRow()
  21546. {
  21547. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21548. size32_t outSize = indexHelper.transformOnKeyedLimitExceeded(rowBuilder);
  21549. if (outSize)
  21550. return rowBuilder.finalizeRowClear(outSize);
  21551. return NULL;
  21552. }
  21553. };
  21554. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21555. {
  21556. public:
  21557. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21558. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21559. {
  21560. }
  21561. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21562. {
  21563. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21564. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21565. else if (isSimple && !maySkip)
  21566. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21567. else
  21568. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip, maxSeekLookahead);
  21569. }
  21570. };
  21571. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21572. {
  21573. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21574. }
  21575. //--------------------------------------------------------------------------------------------------------------------------
  21576. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21577. {
  21578. bool done;
  21579. public:
  21580. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21581. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21582. {
  21583. done = false;
  21584. }
  21585. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21586. {
  21587. done = false;
  21588. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21589. }
  21590. virtual bool needsAllocator() const { return true; }
  21591. virtual const void *nextRow()
  21592. {
  21593. ActivityTimer t(totalCycles, timeActivities);
  21594. if (done) return NULL;
  21595. done = true;
  21596. size32_t rowSize = meta.getFixedSize();
  21597. void * nullRow = rowAllocator->createRow();
  21598. if (rowSize == 1)
  21599. *(byte *)nullRow = 0;
  21600. else
  21601. {
  21602. assertex(rowSize == sizeof(unsigned __int64));
  21603. *(unsigned __int64 *)nullRow = 0;
  21604. }
  21605. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21606. }
  21607. };
  21608. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21609. {
  21610. IHThorIndexCountArg & countHelper;
  21611. bool done;
  21612. public:
  21613. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21614. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21615. countHelper((IHThorIndexCountArg &)basehelper),
  21616. done(false)
  21617. {
  21618. }
  21619. virtual bool needsAllocator() const { return true; }
  21620. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21621. {
  21622. done = false;
  21623. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21624. choosenLimit = countHelper.getChooseNLimit();
  21625. rowLimit = countHelper.getRowLimit();
  21626. keyedLimit = countHelper.getKeyedLimit();
  21627. if (!paused)
  21628. processAllKeys();
  21629. }
  21630. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21631. {
  21632. unsigned __int64 count = 0;
  21633. if (countHelper.hasFilter())
  21634. {
  21635. while (tlk->lookup(true))
  21636. {
  21637. try
  21638. {
  21639. count += countHelper.numValid(tlk->queryKeyBuffer());
  21640. callback.finishedRow();
  21641. }
  21642. catch (IException *E)
  21643. {
  21644. throw makeWrappedException(E);
  21645. }
  21646. accepted++;
  21647. if (count >= choosenLimit) // MORE - what about limit?
  21648. break;
  21649. }
  21650. }
  21651. else
  21652. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21653. if (count)
  21654. {
  21655. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  21656. if (count > choosenLimit)
  21657. count = choosenLimit;
  21658. void * recBuffer = rowAllocator->createRow();
  21659. if (meta.getFixedSize() == 1)
  21660. *(byte *)recBuffer = (byte)count;
  21661. else
  21662. {
  21663. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21664. *(unsigned __int64 *)recBuffer = count;
  21665. }
  21666. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21667. result->append(recBuffer);
  21668. remote.injectResult(result.getClear());
  21669. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21670. if (count >= choosenLimit)
  21671. return true;
  21672. }
  21673. return false;
  21674. }
  21675. virtual void onLimitExceeded(bool isKeyed)
  21676. {
  21677. if (traceLevel > 4)
  21678. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21679. if (isKeyed)
  21680. {
  21681. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21682. {
  21683. if (ctx->queryDebugContext())
  21684. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21685. throw makeLimitSkipException(true);
  21686. }
  21687. else
  21688. {
  21689. countHelper.onKeyedLimitExceeded();
  21690. }
  21691. }
  21692. else
  21693. {
  21694. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21695. {
  21696. if (ctx->queryDebugContext())
  21697. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21698. throw makeLimitSkipException(false);
  21699. }
  21700. else
  21701. {
  21702. countHelper.onLimitExceeded();
  21703. }
  21704. }
  21705. }
  21706. virtual const void *createLimitFailRow(bool isKeyed)
  21707. {
  21708. throwUnexpected();
  21709. }
  21710. virtual const void *nextRow()
  21711. {
  21712. ActivityTimer t(totalCycles, timeActivities);
  21713. if (done) return NULL;
  21714. done = true;
  21715. unsigned __int64 totalCount = 0;
  21716. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21717. try
  21718. {
  21719. for (;;)
  21720. {
  21721. const void * next = remote.nextRow();
  21722. if (!next)
  21723. break;
  21724. if (meta.getFixedSize() == 1)
  21725. totalCount += *(byte *)next;
  21726. else
  21727. totalCount += *(unsigned __int64 *) next;
  21728. ReleaseRoxieRow(next);
  21729. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21730. break;
  21731. }
  21732. if (totalCount > rowLimit)
  21733. {
  21734. unsigned flags = indexHelper.getFlags();
  21735. if (flags & TIRlimitskips)
  21736. totalCount = 0;
  21737. else if (flags & TIRlimitcreates)
  21738. totalCount = 1;
  21739. else
  21740. countHelper.onLimitExceeded();
  21741. }
  21742. else if (totalCount > choosenLimit)
  21743. totalCount = choosenLimit;
  21744. }
  21745. catch (IException *E)
  21746. {
  21747. if (QUERYINTERFACE(E, LimitSkipException))
  21748. {
  21749. totalCount = 0;
  21750. unsigned flags = indexHelper.getFlags();
  21751. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21752. {
  21753. if (flags & TIRkeyedlimitcreates)
  21754. totalCount++;
  21755. }
  21756. else
  21757. {
  21758. if (flags & TIRlimitcreates)
  21759. totalCount++;
  21760. }
  21761. if (totalCount > choosenLimit)
  21762. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21763. E->Release();
  21764. }
  21765. else
  21766. throw ;
  21767. }
  21768. processed++;
  21769. void * result = rowAllocator->createRow();
  21770. if (meta.getFixedSize() == 1)
  21771. *(byte *)result = (byte)totalCount;
  21772. else
  21773. {
  21774. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21775. *(unsigned __int64 *)result = totalCount;
  21776. }
  21777. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21778. }
  21779. };
  21780. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21781. {
  21782. public:
  21783. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21784. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21785. {
  21786. }
  21787. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21788. {
  21789. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21790. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21791. // else if (isSimple)
  21792. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21793. else
  21794. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21795. }
  21796. };
  21797. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21798. {
  21799. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21800. }
  21801. //--------------------------------------------------------------------------------------------------------------------------
  21802. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21803. {
  21804. IHThorIndexAggregateArg &aggregateHelper;
  21805. bool done;
  21806. public:
  21807. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21808. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21809. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21810. {
  21811. done = false;
  21812. }
  21813. virtual bool needsAllocator() const { return true; }
  21814. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21815. {
  21816. done = false;
  21817. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21818. }
  21819. virtual const void *nextRow()
  21820. {
  21821. ActivityTimer t(totalCycles, timeActivities);
  21822. if (done) return NULL;
  21823. done = true;
  21824. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21825. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21826. return rowBuilder.finalizeRowClear(thisSize);
  21827. }
  21828. };
  21829. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21830. {
  21831. IHThorCompoundAggregateExtra & aggregateHelper;
  21832. bool done;
  21833. public:
  21834. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21835. const RemoteActivityId &_remoteId, bool _isLocal)
  21836. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21837. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21838. done(false)
  21839. {
  21840. }
  21841. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21842. {
  21843. done = false;
  21844. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21845. if (!paused)
  21846. processAllKeys();
  21847. }
  21848. virtual bool needsAllocator() const { return true; }
  21849. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21850. {
  21851. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21852. while (tlk->lookup(true))
  21853. {
  21854. if (!rowBuilder.exists())
  21855. {
  21856. rowBuilder.ensureRow();
  21857. aggregateHelper.clearAggregate(rowBuilder);
  21858. }
  21859. try
  21860. {
  21861. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer());
  21862. callback.finishedRow();
  21863. }
  21864. catch (IException *E)
  21865. {
  21866. throw makeWrappedException(E);
  21867. }
  21868. accepted++;
  21869. }
  21870. if (aggregateHelper.processedAnyRows())
  21871. {
  21872. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21873. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21874. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  21875. result->append(recBuffer);
  21876. remote.injectResult(result.getClear());
  21877. }
  21878. return false;
  21879. }
  21880. virtual void onLimitExceeded(bool isKeyed)
  21881. {
  21882. if (traceLevel > 4)
  21883. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21884. throwUnexpected();
  21885. }
  21886. virtual const void *createLimitFailRow(bool isKeyed)
  21887. {
  21888. throwUnexpected();
  21889. }
  21890. const void * gatherMerged()
  21891. {
  21892. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21893. const void * firstRow = remote.nextRow();
  21894. size32_t finalSize = 0;
  21895. if (!firstRow)
  21896. {
  21897. rowBuilder.ensureRow();
  21898. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21899. }
  21900. else
  21901. {
  21902. // NOTE need to clone this because going to modify below, could special case 1 row only
  21903. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21904. ReleaseRoxieRow(firstRow);
  21905. }
  21906. for (;;)
  21907. {
  21908. const void * next = remote.nextRow();
  21909. if (!next)
  21910. break;
  21911. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21912. ReleaseRoxieRow(next);
  21913. }
  21914. return rowBuilder.finalizeRowClear(finalSize);
  21915. }
  21916. virtual const void *nextRow()
  21917. {
  21918. ActivityTimer t(totalCycles, timeActivities);
  21919. if (done) return NULL;
  21920. const void * ret = gatherMerged();
  21921. processed++;
  21922. done = true;
  21923. return ret;
  21924. }
  21925. };
  21926. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21927. {
  21928. public:
  21929. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21930. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21931. {
  21932. }
  21933. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21934. {
  21935. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21936. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  21937. // else if (isSimple)
  21938. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21939. else
  21940. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21941. }
  21942. };
  21943. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21944. {
  21945. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21946. }
  21947. //--------------------------------------------------------------------------------------------------------------------------
  21948. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  21949. {
  21950. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  21951. RowAggregator singleAggregator;
  21952. RowAggregator resultAggregator;
  21953. unsigned groupSegCount;
  21954. bool gathered;
  21955. bool eof;
  21956. public:
  21957. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21958. const RemoteActivityId &_remoteId, bool _isLocal)
  21959. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21960. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  21961. singleAggregator(aggregateHelper, aggregateHelper),
  21962. resultAggregator(aggregateHelper, aggregateHelper),
  21963. gathered(false), eof(true)
  21964. {
  21965. groupSegCount = 0;
  21966. }
  21967. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  21968. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21969. {
  21970. eof = false;
  21971. gathered= false;
  21972. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21973. groupSegCount = 0;
  21974. if (!paused)
  21975. processAllKeys();
  21976. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  21977. }
  21978. virtual bool needsAllocator() const { return true; }
  21979. virtual void reset()
  21980. {
  21981. resultAggregator.reset();
  21982. CRoxieServerIndexActivity::reset();
  21983. }
  21984. virtual void processRow(const void * next)
  21985. {
  21986. singleAggregator.addRow(next);
  21987. }
  21988. virtual void createSegmentMonitors(IKeyManager *key)
  21989. {
  21990. ThorActivityKind kind = factory->getKind();
  21991. CRoxieServerIndexActivity::createSegmentMonitors(key);
  21992. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  21993. groupSegCount = aggregateHelper.getGroupingMaxField();
  21994. else
  21995. groupSegCount = 0;
  21996. }
  21997. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21998. {
  21999. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  22000. singleAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  22001. ThorActivityKind kind = factory->getKind();
  22002. while (tlk->lookup(true))
  22003. {
  22004. try
  22005. {
  22006. if (groupSegCount && !trans)
  22007. {
  22008. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer());
  22009. callback.finishedRow();
  22010. if (kind==TAKindexgroupcount)
  22011. {
  22012. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  22013. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  22014. }
  22015. if (!tlk->nextRange(groupSegCount))
  22016. break;
  22017. }
  22018. else
  22019. {
  22020. aggregateHelper.processRow(tlk->queryKeyBuffer(), this);
  22021. callback.finishedRow();
  22022. }
  22023. }
  22024. catch (IException *E)
  22025. {
  22026. throw makeWrappedException(E);
  22027. }
  22028. accepted++;
  22029. }
  22030. for (;;)
  22031. {
  22032. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  22033. if (!next)
  22034. break;
  22035. size32_t size = next->querySize();
  22036. result->append(next->finalizeRowClear());
  22037. }
  22038. remote.injectResult(result.getClear());
  22039. singleAggregator.reset();
  22040. return false;
  22041. }
  22042. virtual void onLimitExceeded(bool isKeyed)
  22043. {
  22044. if (traceLevel > 4)
  22045. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22046. throwUnexpected();
  22047. }
  22048. virtual const void *createLimitFailRow(bool isKeyed)
  22049. {
  22050. throwUnexpected();
  22051. }
  22052. void gatherMerged()
  22053. {
  22054. gathered = true;
  22055. for (;;)
  22056. {
  22057. const void * next = remote.nextRow();
  22058. if (!next)
  22059. break;
  22060. resultAggregator.mergeElement(next);
  22061. ReleaseRoxieRow(next);
  22062. }
  22063. }
  22064. virtual const void *nextRow()
  22065. {
  22066. ActivityTimer t(totalCycles, timeActivities);
  22067. if (eof)
  22068. return NULL;
  22069. if (!gathered)
  22070. gatherMerged();
  22071. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  22072. if (next)
  22073. {
  22074. processed++;
  22075. return next->finalizeRowClear();
  22076. }
  22077. eof = true;
  22078. return NULL;
  22079. }
  22080. };
  22081. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22082. {
  22083. public:
  22084. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22085. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22086. {
  22087. }
  22088. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22089. {
  22090. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22091. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22092. // else if (isSimple)
  22093. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22094. else
  22095. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22096. }
  22097. };
  22098. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22099. {
  22100. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22101. }
  22102. //--------------------------------------------------------------------------------------------------------------------------
  22103. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  22104. {
  22105. IHThorIndexNormalizeArg & readHelper;
  22106. public:
  22107. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  22108. bool _sorted, bool _isLocal)
  22109. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, false),
  22110. readHelper((IHThorIndexNormalizeArg &)basehelper)
  22111. {
  22112. limitTransformExtra = &readHelper;
  22113. }
  22114. virtual bool needsAllocator() const { return true; }
  22115. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22116. {
  22117. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  22118. rowLimit = readHelper.getRowLimit();
  22119. keyedLimit = readHelper.getKeyedLimit();
  22120. choosenLimit = readHelper.getChooseNLimit();
  22121. if (!paused)
  22122. processAllKeys();
  22123. }
  22124. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22125. {
  22126. unsigned keyedCount = 0;
  22127. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22128. while (tlk->lookup(true))
  22129. {
  22130. keyedCount++;
  22131. if (keyedCount > keyedLimit)
  22132. {
  22133. if (traceLevel > 4)
  22134. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22135. onLimitExceeded(true);
  22136. break;
  22137. }
  22138. size32_t transformedSize;
  22139. if (readHelper.first(tlk->queryKeyBuffer()))
  22140. {
  22141. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  22142. do
  22143. {
  22144. if (accepted>=choosenLimit)
  22145. break;
  22146. rowBuilder.ensureRow();
  22147. try
  22148. {
  22149. transformedSize = readHelper.transform(rowBuilder);
  22150. }
  22151. catch (IException *E)
  22152. {
  22153. throw makeWrappedException(E);
  22154. }
  22155. if (transformedSize)
  22156. {
  22157. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22158. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22159. accepted++;
  22160. }
  22161. else
  22162. rejected++;
  22163. } while (readHelper.next());
  22164. remote.injectResult(result.getClear());
  22165. callback.finishedRow();
  22166. if (accepted>=choosenLimit)
  22167. return true;
  22168. }
  22169. }
  22170. return false;
  22171. }
  22172. virtual void onLimitExceeded(bool isKeyed)
  22173. {
  22174. if (traceLevel > 4)
  22175. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22176. if (isKeyed)
  22177. {
  22178. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22179. {
  22180. if (ctx->queryDebugContext())
  22181. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22182. throw makeLimitSkipException(true);
  22183. }
  22184. else
  22185. readHelper.onKeyedLimitExceeded();
  22186. }
  22187. else
  22188. {
  22189. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  22190. {
  22191. if (ctx->queryDebugContext())
  22192. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22193. throw makeLimitSkipException(false);
  22194. }
  22195. else
  22196. readHelper.onLimitExceeded();
  22197. }
  22198. }
  22199. virtual const void *createLimitFailRow(bool isKeyed)
  22200. {
  22201. UNIMPLEMENTED;
  22202. }
  22203. };
  22204. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22205. {
  22206. public:
  22207. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22208. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22209. {
  22210. }
  22211. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22212. {
  22213. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22214. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22215. else
  22216. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal);
  22217. }
  22218. };
  22219. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22220. {
  22221. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22222. }
  22223. //=================================================================================
  22224. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22225. {
  22226. IHThorFetchBaseArg &helper;
  22227. Linked<IFilePartMap> map;
  22228. CRemoteResultAdaptor remote;
  22229. RecordPullerThread puller;
  22230. bool needsRHS;
  22231. bool variableFileName;
  22232. bool isOpt;
  22233. Owned<const IResolvedFile> varFileInfo;
  22234. Owned<IEngineRowAllocator> extractAllocator;
  22235. public:
  22236. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22237. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22238. {
  22239. needsRHS = helper.transformNeedsRhs();
  22240. if (needsRHS)
  22241. extractAllocator.setown(createRowAllocator(helper.queryExtractedSize()));
  22242. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22243. isOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22244. }
  22245. virtual const IResolvedFile *queryVarFileInfo() const
  22246. {
  22247. return varFileInfo;
  22248. }
  22249. virtual void onCreate(IHThorArg *_colocalParent)
  22250. {
  22251. CRoxieServerActivity::onCreate(_colocalParent);
  22252. remote.onCreate(_colocalParent);
  22253. }
  22254. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22255. {
  22256. if (idx)
  22257. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22258. puller.setInput(this, _sourceIdx, _in);
  22259. }
  22260. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22261. {
  22262. puller.connectInputStreams(ctx, consumerOrdered);
  22263. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22264. }
  22265. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22266. {
  22267. if (idx==0)
  22268. return puller.queryInput();
  22269. else
  22270. return NULL;
  22271. }
  22272. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22273. {
  22274. CRoxieServerActivity::gatherStats(merged);
  22275. remote.gatherStats(merged);
  22276. }
  22277. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22278. {
  22279. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22280. remote.onStart(parentExtractSize, parentExtract);
  22281. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22282. if (variableFileName)
  22283. {
  22284. OwnedRoxieString fname(helper.getFileName());
  22285. varFileInfo.setown(resolveLFNFlat(fname, isOpt));
  22286. if (varFileInfo)
  22287. map.setown(varFileInfo->getFileMap());
  22288. }
  22289. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22290. }
  22291. virtual void stop()
  22292. {
  22293. // Called from remote, so no need to call back to it....
  22294. puller.stop();
  22295. CRoxieServerActivity::stop();
  22296. }
  22297. virtual void reset()
  22298. {
  22299. processed = remote.processed;
  22300. remote.processed = 0;
  22301. puller.reset();
  22302. if (variableFileName)
  22303. {
  22304. varFileInfo.clear();
  22305. map.clear();
  22306. }
  22307. CRoxieServerActivity::reset();
  22308. }
  22309. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22310. {
  22311. if (idx==(unsigned)-1)
  22312. idx = 0;
  22313. return idx ? NULL : &remote;
  22314. }
  22315. virtual void processRow(const void *row)
  22316. {
  22317. // called from puller thread
  22318. offset_t rp = helper.extractPosition(row);
  22319. unsigned partNo;
  22320. if (isLocalFpos(rp))
  22321. partNo = getLocalFposPart(rp) + 1;
  22322. else
  22323. partNo = map->mapOffset(rp);
  22324. if (needsRHS)
  22325. {
  22326. RtlDynamicRowBuilder rb(extractAllocator, true);
  22327. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22328. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22329. *(offset_t *) block = rp;
  22330. block += sizeof(rp);
  22331. *(unsigned *) block = rhsSize;
  22332. block += sizeof(rhsSize);
  22333. memcpy(block, rb.row(), rhsSize);
  22334. }
  22335. else
  22336. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22337. ReleaseRoxieRow(row);
  22338. }
  22339. void processEOG()
  22340. {
  22341. #ifdef FETCH_PRESERVES_GROUPING
  22342. UNIMPLEMENTED;
  22343. #endif
  22344. // else discard is correct
  22345. }
  22346. void processGroup(const ConstPointerArray &)
  22347. {
  22348. throwUnexpected();
  22349. }
  22350. void processDone()
  22351. {
  22352. // called from puller thread
  22353. remote.flush();
  22354. remote.senddone();
  22355. }
  22356. virtual bool fireException(IException *e)
  22357. {
  22358. return remote.fireException(e);
  22359. }
  22360. virtual void onLimitExceeded(bool isKeyed)
  22361. {
  22362. if (traceLevel > 4)
  22363. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22364. if (isKeyed)
  22365. throwUnexpected();
  22366. helper.onLimitExceeded();
  22367. }
  22368. virtual const void *createLimitFailRow(bool isKeyed)
  22369. {
  22370. UNIMPLEMENTED;
  22371. }
  22372. virtual const void *nextRow()
  22373. {
  22374. throwUnexpected(); // I am nobody's input
  22375. }
  22376. };
  22377. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22378. {
  22379. RemoteActivityId remoteId;
  22380. Owned<IFilePartMap> map;
  22381. bool variableFileName;
  22382. Owned<const IResolvedFile> datafile;
  22383. public:
  22384. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22385. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22386. {
  22387. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22388. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22389. if (!variableFileName)
  22390. {
  22391. OwnedRoxieString fname(helper->getFileName());
  22392. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22393. (helper->getFetchFlags() & FFdatafileoptional) != 0,
  22394. true, true,
  22395. _queryFactory.queryWorkUnit(), true));
  22396. if (datafile)
  22397. map.setown(datafile->getFileMap());
  22398. }
  22399. }
  22400. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22401. {
  22402. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22403. }
  22404. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22405. {
  22406. if (datafile)
  22407. addXrefFileInfo(reply, datafile);
  22408. else
  22409. {
  22410. // Temporarily resolve the file
  22411. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22412. if ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22413. {
  22414. OwnedRoxieString fileName(helper->getFileName());
  22415. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22416. if (temp)
  22417. addXrefFileInfo(reply, temp);
  22418. }
  22419. }
  22420. }
  22421. virtual const StatisticsMapping &queryStatsMapping() const
  22422. {
  22423. return diskStatistics;
  22424. }
  22425. };
  22426. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22427. {
  22428. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22429. }
  22430. // MORE - is there any point keeping this now?
  22431. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22432. {
  22433. public:
  22434. Owned<const IResolvedFile> indexfile;
  22435. Owned<const IResolvedFile> datafile;
  22436. StringAttr fileName;
  22437. StringAttr indexName;
  22438. Owned<IKeyArray> keySet;
  22439. Owned<IFileIOArray> files;
  22440. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22441. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22442. {
  22443. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22444. {
  22445. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22446. return; // ignore 'spills'
  22447. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22448. ThorActivityKind kind = getActivityKind(_graphNode);
  22449. if (kind != TAKdiskwrite && kind != TAKspillwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22450. {
  22451. fileName.set(queryNodeFileName(_graphNode, kind));
  22452. indexName.set(queryNodeIndexName(_graphNode, kind));
  22453. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22454. {
  22455. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22456. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22457. if (indexfile)
  22458. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  22459. }
  22460. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22461. {
  22462. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22463. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22464. if (datafile)
  22465. {
  22466. if (isLocal)
  22467. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22468. }
  22469. }
  22470. }
  22471. }
  22472. catch(IException *E)
  22473. {
  22474. StringBuffer errors;
  22475. E->errorMessage(errors);
  22476. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22477. E->Release();
  22478. }
  22479. }
  22480. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_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__); }
  22481. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22482. {
  22483. if (!allFilesDynamic)
  22484. {
  22485. if (datafile)
  22486. addXrefFileInfo(reply, datafile);
  22487. if (indexfile)
  22488. addXrefFileInfo(reply, indexfile);
  22489. }
  22490. else
  22491. {
  22492. Owned<const IResolvedFile> temp;
  22493. if (fileName.length())
  22494. {
  22495. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22496. if (temp)
  22497. addXrefFileInfo(reply, temp);
  22498. }
  22499. if (indexName.length())
  22500. {
  22501. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22502. if (temp)
  22503. addXrefFileInfo(reply, temp);
  22504. }
  22505. }
  22506. }
  22507. };
  22508. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22509. {
  22510. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22511. }
  22512. //=====================================================================================================
  22513. // Keyed joins...
  22514. //
  22515. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22516. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22517. // A separate thread (the caller's thread) is waiting on slave replies, and once it has all replies for a given LHS record or group of records, calls
  22518. // the transform and returns rows that are created.
  22519. // 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)
  22520. //
  22521. //=====================================================================================================
  22522. class CJoinGroup;
  22523. interface IJoinProcessor
  22524. {
  22525. virtual void processEOG() = 0;
  22526. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22527. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22528. virtual bool fireException(IException *E) = 0;
  22529. virtual void processCompletedGroups() = 0;
  22530. };
  22531. //------------------------------------------------------------------------------------------------------
  22532. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22533. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22534. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22535. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22536. // per-query limits etc (Note that the pointer array block is not though).
  22537. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22538. //
  22539. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22540. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22541. // initial count when created.
  22542. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22543. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22544. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22545. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22546. // remaining reference and the JoinGroup will be processed and destroyed.
  22547. //
  22548. //------------------------------------------------------------------------------------------------------
  22549. class CJoinGroup : public CInterface
  22550. {
  22551. protected:
  22552. const void *left; // LHS row
  22553. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22554. atomic_t endMarkersPending; // How many slave responses still waiting for
  22555. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22556. unsigned lastPartNo;
  22557. unsigned pos;
  22558. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22559. public:
  22560. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22561. {
  22562. return a->allocate(size, activityId);
  22563. }
  22564. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22565. {
  22566. ReleaseRoxieRow(ptr);
  22567. }
  22568. void operator delete(void *ptr)
  22569. {
  22570. ReleaseRoxieRow(ptr);
  22571. }
  22572. public:
  22573. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22574. {
  22575. #ifdef TRACE_JOINGROUPS
  22576. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22577. #endif
  22578. candidates = 0;
  22579. lastPartNo = 0;
  22580. pos = 0;
  22581. left = _left;
  22582. groupStart = _groupStart;
  22583. if (_groupStart)
  22584. {
  22585. atomic_inc(&_groupStart->endMarkersPending);
  22586. }
  22587. atomic_set(&endMarkersPending, 1);
  22588. }
  22589. ~CJoinGroup()
  22590. {
  22591. #ifdef TRACE_JOINGROUPS
  22592. DBGLOG("Destroying joinGroup %p", this);
  22593. #endif
  22594. if (left)
  22595. {
  22596. ReleaseRoxieRow(left);
  22597. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22598. rows.kill();
  22599. }
  22600. }
  22601. inline bool isHeadRecord() const
  22602. {
  22603. return left==NULL;
  22604. }
  22605. inline bool complete() const
  22606. {
  22607. return atomic_read(&endMarkersPending) == 0;
  22608. }
  22609. #ifdef TRACE_JOINGROUPS
  22610. inline void notePending(unsigned lineNo)
  22611. #else
  22612. inline void notePending()
  22613. #endif
  22614. {
  22615. assert(!complete());
  22616. atomic_inc(&endMarkersPending);
  22617. #ifdef TRACE_JOINGROUPS
  22618. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22619. #endif
  22620. }
  22621. inline bool inGroup(CJoinGroup *leader) const
  22622. {
  22623. return groupStart==leader;
  22624. }
  22625. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22626. {
  22627. // Single threaded by now
  22628. assert(complete());
  22629. return rows.item(idx);
  22630. }
  22631. #ifdef TRACE_JOINGROUPS
  22632. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22633. #else
  22634. bool noteEndReceived(unsigned candidateCount)
  22635. #endif
  22636. {
  22637. assert(!complete());
  22638. if (candidateCount)
  22639. {
  22640. candidates += candidateCount;
  22641. }
  22642. #ifdef TRACE_JOINGROUPS
  22643. 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);
  22644. #endif
  22645. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22646. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22647. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22648. CJoinGroup *localGroupStart = groupStart;
  22649. if (atomic_dec_and_test(&endMarkersPending))
  22650. {
  22651. if (localGroupStart)
  22652. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22653. else
  22654. return true;
  22655. }
  22656. else
  22657. return false;
  22658. }
  22659. inline const void *queryLeft() const
  22660. {
  22661. return left;
  22662. }
  22663. void addRightMatch(KeyedJoinHeader *right)
  22664. {
  22665. assert(!complete());
  22666. unsigned short partNo = right->partNo;
  22667. if (partNo != lastPartNo)
  22668. {
  22669. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22670. if (partNo > lastPartNo)
  22671. pos = rows.length();
  22672. while (pos>0)
  22673. {
  22674. if (rows.item(pos-1)->partNo <= partNo)
  22675. break;
  22676. pos--;
  22677. }
  22678. lastPartNo = partNo;
  22679. }
  22680. rows.add(right, pos);
  22681. pos++;
  22682. }
  22683. inline unsigned rowsSeen() const
  22684. {
  22685. assert(complete());
  22686. return rows.length();
  22687. }
  22688. inline unsigned candidateCount() const
  22689. {
  22690. assert(complete());
  22691. return candidates;
  22692. }
  22693. };
  22694. #ifdef TRACE_JOINGROUPS
  22695. #define notePending() notePending(__LINE__)
  22696. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22697. #endif
  22698. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22699. {
  22700. private:
  22701. SafeQueueOf<const void, true> ready;
  22702. public:
  22703. IHThorKeyedJoinArg &helper;
  22704. unsigned joinProcessed;
  22705. bool isFullKey;
  22706. bool eof;
  22707. bool isSimple;
  22708. bool allPulled;
  22709. ActivityTimeAccumulator totalCycles;
  22710. unsigned activityId;
  22711. RecordPullerThread &puller;
  22712. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22713. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22714. IJoinProcessor &processor;
  22715. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22716. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22717. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22718. : helper(_helper),
  22719. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22720. isFullKey(_isFullKey),
  22721. isSimple(_isSimple),
  22722. puller(_puller),
  22723. processor(_processor),
  22724. activityId(_activity.queryId())
  22725. {
  22726. joinProcessed = 0;
  22727. allPulled = false;
  22728. eof = false;
  22729. }
  22730. virtual void onCreate(IHThorArg *_colocalArg)
  22731. {
  22732. CRemoteResultAdaptor::onCreate(_colocalArg);
  22733. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22734. }
  22735. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22736. {
  22737. eof = false;
  22738. joinProcessed = 0;
  22739. totalCycles.totalCycles = 0;
  22740. allPulled = false;
  22741. assertex(ready.ordinality()==0);
  22742. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22743. }
  22744. virtual void reset()
  22745. {
  22746. CRemoteResultAdaptor::reset();
  22747. while (ready.ordinality())
  22748. {
  22749. const void *goer = ready.dequeue();
  22750. if (goer)
  22751. ReleaseRoxieRow(goer);
  22752. }
  22753. while (injected.ordinality())
  22754. {
  22755. const void *goer = injected.dequeue();
  22756. if (goer)
  22757. ReleaseRoxieRow(goer);
  22758. }
  22759. }
  22760. inline void addResult(const void *row)
  22761. {
  22762. ready.enqueue(row);
  22763. }
  22764. virtual unsigned __int64 queryTotalCycles() const
  22765. {
  22766. return totalCycles.totalCycles;
  22767. }
  22768. virtual const void *nextRow()
  22769. {
  22770. ActivityTimer t(totalCycles, timeActivities);
  22771. for (;;)
  22772. {
  22773. if (eof)
  22774. return NULL;
  22775. processSlaveResults();
  22776. if (ready.ordinality())
  22777. {
  22778. const void *result = ready.dequeue();
  22779. if (result)
  22780. joinProcessed++;
  22781. return result;
  22782. }
  22783. else
  22784. eof = true;
  22785. }
  22786. }
  22787. void gatherStats(CRuntimeStatisticCollection & merged) const
  22788. {
  22789. CRemoteResultAdaptor::gatherStats(merged);
  22790. if (ccdRecordAllocator)
  22791. ccdRecordAllocator->gatherStats(merged);
  22792. }
  22793. private:
  22794. void processSlaveResults()
  22795. {
  22796. while (!ready.ordinality())
  22797. {
  22798. KeyedJoinHeader *fetchedData;
  22799. if (isSimple)
  22800. {
  22801. while (!allPulled && !injected.ordinality())
  22802. {
  22803. if (!puller.pullRecords(1))
  22804. {
  22805. puller.done();
  22806. allPulled = true;
  22807. }
  22808. }
  22809. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22810. }
  22811. else
  22812. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22813. if (fetchedData)
  22814. {
  22815. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22816. if (fetchedData->partNo == (unsigned short) -1)
  22817. {
  22818. #ifdef TRACE_JOINGROUPS
  22819. CTXLOG("Got end for group %p", thisGroup);
  22820. #endif
  22821. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22822. ReleaseRoxieRow(fetchedData);
  22823. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22824. }
  22825. else
  22826. {
  22827. #ifdef TRACE_JOINGROUPS
  22828. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22829. #endif
  22830. thisGroup->addRightMatch(fetchedData);
  22831. if (isFullKey)
  22832. {
  22833. #ifdef TRACE_JOINGROUPS
  22834. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22835. #endif
  22836. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22837. }
  22838. }
  22839. }
  22840. else
  22841. break;
  22842. }
  22843. }
  22844. };
  22845. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22846. {
  22847. IHThorKeyedJoinArg &helper;
  22848. Owned<IKeyManager> tlk;
  22849. Linked<IKeyArray> keySet;
  22850. Linked<ITranslatorSet> translators;
  22851. CRemoteResultAdaptor remote;
  22852. RecordPullerThread puller;
  22853. IOutputMetaData *indexReadMeta;
  22854. IJoinProcessor *joinHandler;
  22855. bool variableIndexFileName;
  22856. bool indexReadInputRecordVariable;
  22857. bool isLocal;
  22858. Owned<IEngineRowAllocator> indexReadAllocator;
  22859. Owned<const IResolvedFile> varFileInfo;
  22860. IFinalRoxieInput *indexReadInput;
  22861. unsigned indexReadIdx = 0;
  22862. IIndexReadActivityInfo *rootIndex;
  22863. public:
  22864. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22865. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22866. helper((IHThorKeyedJoinArg &)basehelper),
  22867. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  22868. translators(_translators),
  22869. keySet(_keySet),
  22870. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22871. indexReadMeta(_indexReadMeta),
  22872. joinHandler(_joinHandler),
  22873. puller(false),
  22874. isLocal(_isLocal)
  22875. {
  22876. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22877. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22878. indexReadInput = NULL;
  22879. rootIndex = NULL;
  22880. }
  22881. virtual const IResolvedFile *queryVarFileInfo() const
  22882. {
  22883. return varFileInfo;
  22884. }
  22885. virtual void onCreate(IHThorArg *_colocalParent)
  22886. {
  22887. CRoxieServerActivity::onCreate(_colocalParent);
  22888. remote.onCreate(_colocalParent);
  22889. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22890. }
  22891. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22892. {
  22893. if (!idx)
  22894. puller.setInput(this, _sourceIdx, _in);
  22895. else if (idx==1)
  22896. {
  22897. indexReadInput = _in;
  22898. indexReadIdx = _sourceIdx;
  22899. }
  22900. else
  22901. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22902. }
  22903. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22904. {
  22905. puller.connectInputStreams(ctx, consumerOrdered);
  22906. //No rows are read from indexReadInput, so no need to extract the streams
  22907. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22908. }
  22909. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22910. {
  22911. switch (idx)
  22912. {
  22913. case 0:
  22914. return puller.queryInput();
  22915. case 1:
  22916. return indexReadInput;
  22917. default:
  22918. return NULL;
  22919. }
  22920. }
  22921. virtual void serializeExtra(MemoryBuffer &out)
  22922. {
  22923. if (helper.getJoinFlags() & JFindexfromactivity)
  22924. {
  22925. assertex(rootIndex);
  22926. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22927. indexId.serialize(out);
  22928. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22929. MemoryBuffer tmp;
  22930. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22931. if (rootIndex->queryActivity()->queryVarFileInfo())
  22932. {
  22933. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22934. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  22935. }
  22936. unsigned ctxlen = tmp.length();
  22937. out.append(ctxlen).append(tmp);
  22938. }
  22939. }
  22940. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22941. {
  22942. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22943. if (indexReadInput)
  22944. {
  22945. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  22946. rootIndex = indexReadInput->queryIndexReadActivity();
  22947. if (!rootIndex)
  22948. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  22949. }
  22950. remote.onStart(parentExtractSize, parentExtract);
  22951. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22952. if (rootIndex)
  22953. {
  22954. varFileInfo.setown(rootIndex->getVarFileInfo());
  22955. translators.setown(rootIndex->getTranslators());
  22956. keySet.setown(rootIndex->getKeySet());
  22957. }
  22958. else if (variableIndexFileName)
  22959. {
  22960. OwnedRoxieString indexFileName(helper.getIndexFileName());
  22961. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  22962. if (varFileInfo)
  22963. {
  22964. unsigned expectedCrc = helper.getIndexFormatCrc();
  22965. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  22966. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  22967. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  22968. }
  22969. }
  22970. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  22971. }
  22972. virtual void stop()
  22973. {
  22974. puller.stop();
  22975. CRoxieServerActivity::stop();
  22976. }
  22977. virtual void reset()
  22978. {
  22979. CRoxieServerActivity::reset();
  22980. puller.reset();
  22981. if (varFileInfo)
  22982. {
  22983. keySet.clear();
  22984. varFileInfo.clear();
  22985. }
  22986. }
  22987. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22988. {
  22989. if (idx==(unsigned)-1)
  22990. idx = 0;
  22991. return idx ? NULL : &remote;
  22992. }
  22993. virtual void processRow(const void *row)
  22994. {
  22995. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  22996. // called from front puller thread
  22997. // buffer up an IndexRead request
  22998. if (keySet && helper.leftCanMatch(row))
  22999. {
  23000. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  23001. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  23002. OwnedConstRoxieRow extracted;
  23003. if (indexReadSize)
  23004. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  23005. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  23006. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23007. {
  23008. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23009. if (thisBase)
  23010. {
  23011. unsigned fileNo = 0;
  23012. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23013. try
  23014. {
  23015. tlk->setKey(thisKey);
  23016. if (!thisKey->isTopLevelKey())
  23017. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23018. else
  23019. tlk->setLayoutTranslator(nullptr);
  23020. helper.createSegmentMonitors(tlk, extracted);
  23021. if (rootIndex)
  23022. rootIndex->mergeSegmentMonitors(tlk);
  23023. tlk->finishSegmentMonitors();
  23024. tlk->reset();
  23025. for (;;)
  23026. {
  23027. typedef const void * cvp;
  23028. if (thisKey->isTopLevelKey())
  23029. {
  23030. bool locallySorted = !thisKey->isFullySorted();
  23031. while (locallySorted || tlk->lookup(false))
  23032. {
  23033. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23034. if (locallySorted || slavePart)
  23035. {
  23036. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23037. *outputBuffer++ = jg;
  23038. if (indexReadInputRecordVariable)
  23039. {
  23040. *(unsigned *) outputBuffer = indexReadSize;
  23041. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  23042. }
  23043. jg->notePending();
  23044. memcpy(outputBuffer, extracted, indexReadSize);
  23045. if (!slavePart)
  23046. {
  23047. for (unsigned i = 1; i < numChannels; i++)
  23048. jg->notePending();
  23049. }
  23050. if (locallySorted)
  23051. break;
  23052. }
  23053. }
  23054. }
  23055. else
  23056. {
  23057. // MORE - this code seems to be duplicated in half keyed
  23058. unsigned accepted = 0;
  23059. unsigned rejected = 0;
  23060. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  23061. jg->notePending();
  23062. unsigned candidateCount = 0;
  23063. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23064. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23065. while (tlk->lookup(true))
  23066. {
  23067. candidateCount++;
  23068. indexRecordsRead++;
  23069. KLBlobProviderAdapter adapter(tlk);
  23070. const byte *indexRow = tlk->queryKeyBuffer();
  23071. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23072. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23073. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23074. {
  23075. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23076. rhs->fpos = fpos;
  23077. rhs->thisGroup = jg;
  23078. rhs->partNo = partNo;
  23079. result->append(rhs);
  23080. }
  23081. else
  23082. {
  23083. rejected++;
  23084. postFiltered++;
  23085. }
  23086. }
  23087. // output an end marker for the matches to this group
  23088. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23089. endMarker->fpos = (offset_t) candidateCount;
  23090. endMarker->thisGroup = jg;
  23091. endMarker->partNo = (unsigned short) -1;
  23092. result->append(endMarker);
  23093. remote.injectResult(result.getClear());
  23094. if (accepted)
  23095. noteStatistic(StNumIndexAccepted, accepted);
  23096. if (rejected)
  23097. noteStatistic(StNumIndexRejected, rejected);
  23098. }
  23099. if (++fileNo < thisBase->numParts())
  23100. {
  23101. thisKey = thisBase->queryPart(fileNo);
  23102. tlk->setKey(thisKey);
  23103. if (!thisKey->isTopLevelKey())
  23104. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23105. else
  23106. tlk->setLayoutTranslator(nullptr);
  23107. tlk->reset();
  23108. }
  23109. else
  23110. break;
  23111. }
  23112. tlk->releaseSegmentMonitors();
  23113. tlk->setKey(NULL);
  23114. }
  23115. catch (...)
  23116. {
  23117. tlk->releaseSegmentMonitors();
  23118. tlk->setKey(NULL);
  23119. throw;
  23120. }
  23121. }
  23122. }
  23123. joinHandler->noteEndReceived(jg, 0);
  23124. }
  23125. else
  23126. {
  23127. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23128. }
  23129. }
  23130. void processGroup(const ConstPointerArray &)
  23131. {
  23132. throwUnexpected();
  23133. }
  23134. virtual void processEOG()
  23135. {
  23136. joinHandler->processEOG();
  23137. }
  23138. virtual void processDone()
  23139. {
  23140. // called from puller thread
  23141. remote.flush();
  23142. remote.senddone();
  23143. }
  23144. virtual void onLimitExceeded(bool isKeyed)
  23145. {
  23146. if (traceLevel > 4)
  23147. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23148. if (isKeyed)
  23149. throwUnexpected();
  23150. helper.onLimitExceeded();
  23151. }
  23152. virtual const void *createLimitFailRow(bool isKeyed)
  23153. {
  23154. throwUnexpected();
  23155. }
  23156. virtual bool fireException(IException *e)
  23157. {
  23158. // called from puller thread on failure
  23159. remote.fireException(LINK(e));
  23160. return joinHandler->fireException(e);
  23161. }
  23162. virtual const void *nextRow()
  23163. {
  23164. throwUnexpected(); // I am nobody's input
  23165. }
  23166. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23167. {
  23168. CRoxieServerActivity::gatherStats(merged);
  23169. remote.gatherStats(merged);
  23170. if (indexReadAllocator)
  23171. indexReadAllocator->gatherStats(merged);
  23172. }
  23173. };
  23174. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23175. {
  23176. protected:
  23177. IHThorKeyedJoinArg &helper;
  23178. KeyedJoinRemoteAdaptor remote;
  23179. RecordPullerThread puller;
  23180. OwnedConstRoxieRow defaultRight;
  23181. Owned<IEngineRowAllocator> defaultRightAllocator;
  23182. unsigned joinFlags;
  23183. unsigned atMost;
  23184. unsigned atmostsTriggered;
  23185. unsigned abortLimit;
  23186. unsigned keepLimit;
  23187. bool limitFail;
  23188. bool limitOnFail;
  23189. bool preserveGroups;
  23190. bool cloneLeft;
  23191. bool isSimple;
  23192. bool isLocal;
  23193. ThorActivityKind activityKind;
  23194. CJoinGroup *groupStart;
  23195. CriticalSection groupsCrit;
  23196. QueueOf<CJoinGroup, false> groups;
  23197. IFinalRoxieInput *indexReadInput;
  23198. unsigned indexReadIdx = 0;
  23199. Owned<IStrandJunction> indexReadJunction;
  23200. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23201. IIndexReadActivityInfo *rootIndex;
  23202. void createDefaultRight()
  23203. {
  23204. if (!defaultRight)
  23205. {
  23206. if (!defaultRightAllocator)
  23207. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23208. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23209. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23210. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23211. }
  23212. }
  23213. public:
  23214. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23215. , bool isFull, bool _isSimple, bool _isLocal)
  23216. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23217. helper((IHThorKeyedJoinArg &)basehelper),
  23218. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23219. joinFlags(_joinFlags),
  23220. preserveGroups(meta.isGrouped()),
  23221. puller(false),
  23222. isSimple(_isSimple),
  23223. isLocal(_isLocal),
  23224. abortLimit(0),
  23225. keepLimit(0),
  23226. atMost(0),
  23227. limitFail(false),
  23228. limitOnFail(false),
  23229. cloneLeft(false)
  23230. {
  23231. groupStart = NULL;
  23232. activityKind = _factory->getKind();
  23233. indexReadInput = NULL;
  23234. rootIndex = NULL;
  23235. atmostsTriggered = 0;
  23236. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23237. }
  23238. virtual void onCreate(IHThorArg *_colocalParent)
  23239. {
  23240. CRoxieServerActivity::onCreate(_colocalParent);
  23241. remote.onCreate(_colocalParent);
  23242. }
  23243. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23244. {
  23245. if (!idx)
  23246. puller.setInput(this, _sourceIdx, _in);
  23247. else if (idx==1)
  23248. {
  23249. indexReadInput = _in;
  23250. indexReadIdx = _sourceIdx;
  23251. }
  23252. else
  23253. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23254. }
  23255. virtual void connectInputStreams(bool consumerOrdered)
  23256. {
  23257. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23258. puller.connectInputStreams(ctx, consumerOrdered);
  23259. if (indexReadInput)
  23260. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23261. }
  23262. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23263. {
  23264. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23265. if (indexReadInput)
  23266. {
  23267. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23268. rootIndex = indexReadInput->queryIndexReadActivity();
  23269. if (!rootIndex)
  23270. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23271. }
  23272. remote.onStart(parentExtractSize, parentExtract);
  23273. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23274. atmostsTriggered = 0;
  23275. atMost = helper.getJoinLimit();
  23276. if (atMost == 0) atMost = (unsigned)-1;
  23277. abortLimit = helper.getMatchAbortLimit();
  23278. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23279. keepLimit = helper.getKeepLimit();
  23280. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23281. getLimitType(joinFlags, limitFail, limitOnFail);
  23282. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23283. if ((joinFlags & JFleftouter) || limitOnFail)
  23284. createDefaultRight();
  23285. }
  23286. virtual void stop()
  23287. {
  23288. puller.stop();
  23289. if (indexReadStream)
  23290. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23291. CRoxieServerActivity::stop();
  23292. }
  23293. virtual unsigned __int64 queryLocalCycles() const
  23294. {
  23295. __int64 localCycles = remote.totalCycles.totalCycles;
  23296. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23297. if (localCycles < 0)
  23298. localCycles = 0;
  23299. return localCycles;
  23300. }
  23301. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23302. {
  23303. CRoxieServerActivity::gatherStats(merged);
  23304. remote.gatherStats(merged);
  23305. }
  23306. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23307. {
  23308. if (idx==0)
  23309. return puller.queryInput();
  23310. else if (idx==1)
  23311. return indexReadInput;
  23312. else
  23313. return NULL;
  23314. }
  23315. virtual void reset()
  23316. {
  23317. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23318. remote.totalCycles.totalCycles = 0;
  23319. processed = remote.joinProcessed;
  23320. remote.joinProcessed = 0;
  23321. defaultRight.clear();
  23322. if (indexReadInput)
  23323. indexReadInput->reset();
  23324. if (atmostsTriggered)
  23325. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23326. CRoxieServerActivity::reset();
  23327. puller.reset();
  23328. while (groups.ordinality())
  23329. {
  23330. ::Release(groups.dequeue());
  23331. }
  23332. }
  23333. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23334. {
  23335. if (idx==(unsigned)-1)
  23336. idx = 0;
  23337. return idx ? NULL : &remote;
  23338. }
  23339. virtual CJoinGroup *createJoinGroup(const void *row)
  23340. {
  23341. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23342. CriticalBlock c(groupsCrit);
  23343. if (preserveGroups && !groupStart)
  23344. {
  23345. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23346. groups.enqueue(groupStart);
  23347. }
  23348. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23349. groups.enqueue(jg);
  23350. return jg;
  23351. }
  23352. void endGroup()
  23353. {
  23354. CriticalBlock c(groupsCrit);
  23355. if (groupStart)
  23356. noteEndReceived(groupStart, 0);
  23357. groupStart = NULL;
  23358. }
  23359. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23360. {
  23361. if (jg->noteEndReceived(candidateCount))
  23362. processCompletedGroups();
  23363. }
  23364. void processCompletedGroups()
  23365. {
  23366. CriticalBlock c(groupsCrit);
  23367. while (groups.ordinality())
  23368. {
  23369. if (!groups.head()->complete())
  23370. break;
  23371. Owned<CJoinGroup> head = groups.dequeue();
  23372. if (preserveGroups)
  23373. {
  23374. assert(head->isHeadRecord());
  23375. assert(groups.head()->inGroup(head));
  23376. unsigned joinGroupSize = 0;
  23377. while (groups.ordinality() && groups.head()->inGroup(head))
  23378. {
  23379. Owned<CJoinGroup> finger = groups.dequeue();
  23380. joinGroupSize += doJoinGroup(finger);
  23381. }
  23382. if (joinGroupSize)
  23383. remote.addResult(NULL);
  23384. }
  23385. else
  23386. doJoinGroup(head);
  23387. }
  23388. }
  23389. void failLimit(const void * left)
  23390. {
  23391. helper.onMatchAbortLimitExceeded();
  23392. CommonXmlWriter xmlwrite(0);
  23393. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23394. {
  23395. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23396. }
  23397. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23398. }
  23399. virtual bool needsAllocator() const { return true; }
  23400. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23401. {
  23402. if (cloneLeft && !except)
  23403. {
  23404. LinkRoxieRow(left);
  23405. remote.addResult((void *) left);
  23406. return 1;
  23407. }
  23408. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23409. unsigned outSize;
  23410. try
  23411. {
  23412. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23413. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned)fpos_or_count, group) :
  23414. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23415. }
  23416. catch (IException *E)
  23417. {
  23418. throw makeWrappedException(E);
  23419. }
  23420. if (outSize)
  23421. {
  23422. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23423. remote.addResult(shrunk);
  23424. return 1;
  23425. }
  23426. else
  23427. return 0;
  23428. }
  23429. unsigned doJoinGroup(CJoinGroup *jg)
  23430. {
  23431. unsigned matched = jg->rowsSeen();
  23432. unsigned added = 0;
  23433. const void *left = jg->queryLeft();
  23434. if (jg->candidateCount() > abortLimit)
  23435. {
  23436. if (limitFail)
  23437. failLimit(left);
  23438. if (ctx->queryDebugContext())
  23439. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23440. if (limitOnFail)
  23441. {
  23442. Owned<IException> except;
  23443. try
  23444. {
  23445. failLimit(left);
  23446. }
  23447. catch(IException * e)
  23448. {
  23449. except.setown(e);
  23450. }
  23451. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23452. }
  23453. }
  23454. else if (!matched || jg->candidateCount() > atMost)
  23455. {
  23456. if (jg->candidateCount() > atMost)
  23457. atmostsTriggered++;
  23458. switch (joinFlags & JFtypemask)
  23459. {
  23460. case JFleftouter:
  23461. case JFleftonly:
  23462. switch (activityKind)
  23463. {
  23464. case TAKkeyedjoin:
  23465. case TAKkeyeddenormalizegroup:
  23466. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23467. break;
  23468. case TAKkeyeddenormalize:
  23469. LinkRoxieRow(left);
  23470. remote.addResult((void *) left);
  23471. added++;
  23472. break;
  23473. }
  23474. break;
  23475. }
  23476. }
  23477. else if (!(joinFlags & JFexclude))
  23478. {
  23479. unsigned idx = 0;
  23480. switch (activityKind)
  23481. {
  23482. case TAKkeyedjoin:
  23483. while (idx < matched)
  23484. {
  23485. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23486. added += doTransform(left, &rhs->rhsdata, 0, NULL, NULL, idx+1);
  23487. if (added==keepLimit)
  23488. break;
  23489. idx++;
  23490. }
  23491. break;
  23492. case TAKkeyeddenormalize:
  23493. {
  23494. OwnedConstRoxieRow newLeft;
  23495. newLeft.set(left);
  23496. unsigned rowSize = 0;
  23497. unsigned rightAdded = 0;
  23498. while (idx < matched)
  23499. {
  23500. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23501. try
  23502. {
  23503. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23504. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23505. if (transformedSize)
  23506. {
  23507. rowSize = transformedSize;
  23508. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23509. rightAdded++;
  23510. if (rightAdded==keepLimit)
  23511. break;
  23512. }
  23513. idx++;
  23514. }
  23515. catch (IException *E)
  23516. {
  23517. throw makeWrappedException(E);
  23518. }
  23519. }
  23520. if (rowSize)
  23521. {
  23522. remote.addResult(newLeft.getClear());
  23523. added++;
  23524. }
  23525. }
  23526. break;
  23527. case TAKkeyeddenormalizegroup:
  23528. {
  23529. ConstPointerArray extractedRows;
  23530. while (idx < matched && idx < keepLimit)
  23531. {
  23532. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23533. extractedRows.append((void *) &rhs->rhsdata);
  23534. idx++;
  23535. }
  23536. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23537. }
  23538. break;
  23539. }
  23540. }
  23541. return added;
  23542. }
  23543. virtual void processDone()
  23544. {
  23545. // called from puller thread
  23546. remote.flush();
  23547. remote.senddone();
  23548. }
  23549. virtual void onLimitExceeded(bool isKeyed)
  23550. {
  23551. if (traceLevel > 4)
  23552. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23553. if (isKeyed)
  23554. throwUnexpected();
  23555. helper.onLimitExceeded();
  23556. }
  23557. virtual const void *createLimitFailRow(bool isKeyed)
  23558. {
  23559. throwUnexpected();
  23560. }
  23561. virtual bool fireException(IException *e)
  23562. {
  23563. // called from puller thread on failure
  23564. return remote.fireException(e);
  23565. }
  23566. virtual const void *nextRow()
  23567. {
  23568. throwUnexpected(); // I am nobody's input
  23569. }
  23570. };
  23571. #ifdef _MSC_VER
  23572. #pragma warning ( push )
  23573. #pragma warning ( disable: 4355 )
  23574. #endif
  23575. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23576. {
  23577. CRoxieServerFullKeyedJoinHead head;
  23578. Owned<IEngineRowAllocator> fetchInputAllocator;
  23579. Linked<IFilePartMap> map;
  23580. bool variableFetchFileName;
  23581. Owned<const IResolvedFile> varFetchFileInfo;
  23582. CachedOutputMetaData fetchInputFields;
  23583. public:
  23584. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, ITranslatorSet *_keyTranslators, IOutputMetaData *_indexReadMeta,
  23585. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23586. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23587. head(_ctx, _factory, _probeManager, _headId, _key, _keyTranslators, _indexReadMeta, this, _isLocal),
  23588. map(_map)
  23589. {
  23590. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23591. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23592. }
  23593. virtual const IResolvedFile *queryVarFileInfo() const
  23594. {
  23595. return varFetchFileInfo;
  23596. }
  23597. virtual void onCreate(IHThorArg *_colocalParent)
  23598. {
  23599. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23600. head.onCreate(_colocalParent);
  23601. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23602. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23603. }
  23604. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23605. {
  23606. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23607. if (variableFetchFileName)
  23608. {
  23609. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23610. OwnedRoxieString fname(helper.getFileName());
  23611. varFetchFileInfo.setown(resolveLFNFlat(fname, isFetchOpt));
  23612. if (varFetchFileInfo)
  23613. {
  23614. // Note - we don't need to do any translation on the disk part of full-keyed joins
  23615. map.setown(varFetchFileInfo->getFileMap());
  23616. }
  23617. }
  23618. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23619. }
  23620. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23621. {
  23622. head.setInput(idx, _sourceIdx, _in);
  23623. }
  23624. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23625. {
  23626. connectInputStreams(consumerOrdered);
  23627. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23628. }
  23629. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23630. {
  23631. return head.queryInput(idx);
  23632. }
  23633. virtual void processRow(const void *_rhs)
  23634. {
  23635. // called from puller thread
  23636. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23637. CJoinGroup *jg = rhs->thisGroup;
  23638. if (rhs->partNo != (unsigned short) -1)
  23639. {
  23640. unsigned partNo = map->mapOffset(rhs->fpos);
  23641. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23642. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23643. if (fetchInputFields.isVariableSize())
  23644. {
  23645. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23646. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23647. ReleaseRoxieRow(rhs);
  23648. jg->notePending();
  23649. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23650. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23651. }
  23652. else
  23653. {
  23654. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23655. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23656. ReleaseRoxieRow(rhs);
  23657. jg->notePending();
  23658. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23659. }
  23660. }
  23661. else
  23662. {
  23663. unsigned candidateCount = (unsigned) rhs->fpos;
  23664. // CTXLOG("Full keyed join - all results back from index");
  23665. ReleaseRoxieRow(rhs);
  23666. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23667. }
  23668. }
  23669. virtual void processEOG()
  23670. {
  23671. // called from front puller thread
  23672. if (preserveGroups)
  23673. endGroup();
  23674. }
  23675. void processGroup(const ConstPointerArray &)
  23676. {
  23677. throwUnexpected();
  23678. }
  23679. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23680. {
  23681. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23682. if (fetchInputAllocator)
  23683. fetchInputAllocator->gatherStats(merged);
  23684. }
  23685. };
  23686. #ifdef _MSC_VER
  23687. #pragma warning ( pop )
  23688. #endif
  23689. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23690. {
  23691. IOutputMetaData *indexReadMeta;
  23692. Owned<IEngineRowAllocator> indexReadAllocator;
  23693. Owned<IKeyManager> tlk;
  23694. bool variableIndexFileName;
  23695. bool indexReadInputRecordVariable;
  23696. Owned<const IResolvedFile> varFileInfo;
  23697. Linked<ITranslatorSet> translators;
  23698. Linked<IKeyArray> keySet;
  23699. Owned<IOutputMetaData> joinPrefixedMeta;
  23700. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23701. public:
  23702. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators,
  23703. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23704. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23705. indexReadMeta(_indexReadMeta),
  23706. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors())),
  23707. keySet(_keySet),
  23708. translators(_translators)
  23709. {
  23710. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23711. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23712. }
  23713. virtual void serializeExtra(MemoryBuffer &out)
  23714. {
  23715. if (helper.getJoinFlags() & JFindexfromactivity)
  23716. {
  23717. assertex(rootIndex);
  23718. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23719. indexId.serialize(out);
  23720. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23721. MemoryBuffer tmp;
  23722. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23723. if (rootIndex->queryActivity()->queryVarFileInfo())
  23724. {
  23725. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23726. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23727. }
  23728. unsigned ctxlen = tmp.length();
  23729. out.append(ctxlen).append(tmp);
  23730. }
  23731. }
  23732. virtual void onCreate(IHThorArg *_colocalParent)
  23733. {
  23734. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23735. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23736. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23737. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23738. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23739. }
  23740. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23741. {
  23742. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23743. if (rootIndex)
  23744. {
  23745. varFileInfo.setown(rootIndex->getVarFileInfo());
  23746. translators.setown(rootIndex->getTranslators());
  23747. keySet.setown(rootIndex->getKeySet());
  23748. }
  23749. else if (variableIndexFileName)
  23750. {
  23751. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23752. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23753. if (varFileInfo)
  23754. {
  23755. unsigned expectedCrc = helper.getIndexFormatCrc();
  23756. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23757. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23758. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23759. }
  23760. }
  23761. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23762. }
  23763. virtual const IResolvedFile *queryVarFileInfo() const
  23764. {
  23765. return varFileInfo;
  23766. }
  23767. virtual void reset()
  23768. {
  23769. CRoxieServerKeyedJoinBase::reset();
  23770. if (varFileInfo)
  23771. {
  23772. keySet.clear();
  23773. varFileInfo.clear();
  23774. }
  23775. }
  23776. virtual void processRow(const void *row)
  23777. {
  23778. // called from front puller thread
  23779. // buffer up an IndexRead request
  23780. if (keySet && helper.leftCanMatch(row))
  23781. {
  23782. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23783. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23784. OwnedConstRoxieRow extracted;
  23785. if (indexReadRecordSize)
  23786. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23787. CJoinGroup *jg = createJoinGroup(row);
  23788. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23789. {
  23790. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23791. if (thisBase)
  23792. {
  23793. unsigned fileNo = 0;
  23794. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23795. tlk->setKey(thisKey);
  23796. if (thisKey && !thisKey->isTopLevelKey())
  23797. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23798. else
  23799. tlk->setLayoutTranslator(nullptr);
  23800. helper.createSegmentMonitors(tlk, extracted);
  23801. if (rootIndex)
  23802. rootIndex->mergeSegmentMonitors(tlk);
  23803. tlk->finishSegmentMonitors();
  23804. try
  23805. {
  23806. tlk->reset();
  23807. for (;;)
  23808. {
  23809. typedef const void * cvp;
  23810. if (thisKey && thisKey->isTopLevelKey())
  23811. {
  23812. bool locallySorted = (!thisKey->isFullySorted());
  23813. while (locallySorted || tlk->lookup(false))
  23814. {
  23815. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23816. if (locallySorted || slavePart)
  23817. {
  23818. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23819. *outputBuffer++ = jg;
  23820. if (indexReadInputRecordVariable)
  23821. {
  23822. *(unsigned *) outputBuffer = indexReadRecordSize;
  23823. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23824. }
  23825. jg->notePending();
  23826. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23827. if (!slavePart)
  23828. {
  23829. for (unsigned i = 1; i < numChannels; i++)
  23830. jg->notePending();
  23831. }
  23832. if (locallySorted)
  23833. break;
  23834. }
  23835. }
  23836. }
  23837. else
  23838. {
  23839. unsigned accepted = 0;
  23840. unsigned rejected = 0;
  23841. Owned<CRowArrayMessageResult> result;
  23842. if (!isSimple)
  23843. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  23844. // MORE - This code seems to be duplicated in keyedJoinHead
  23845. jg->notePending();
  23846. unsigned candidateCount = 0;
  23847. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23848. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23849. while (tlk->lookup(true))
  23850. {
  23851. candidateCount++;
  23852. indexRecordsRead++;
  23853. KLBlobProviderAdapter adapter(tlk);
  23854. const byte *indexRow = tlk->queryKeyBuffer();
  23855. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23856. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23857. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23858. {
  23859. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23860. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23861. accepted++;
  23862. KLBlobProviderAdapter adapter(tlk);
  23863. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, &adapter);
  23864. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23865. rec->fpos = fpos;
  23866. rec->thisGroup = jg;
  23867. rec->partNo = partNo;
  23868. if (isSimple)
  23869. remote.injected.enqueue(rec);
  23870. else
  23871. result->append(rec);
  23872. }
  23873. else
  23874. {
  23875. rejected++;
  23876. postFiltered++;
  23877. }
  23878. }
  23879. // output an end marker for the matches to this group
  23880. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23881. rec->fpos = (offset_t) candidateCount;
  23882. rec->thisGroup = jg;
  23883. rec->partNo = (unsigned short) -1;
  23884. if (isSimple)
  23885. remote.injected.enqueue(rec);
  23886. else
  23887. {
  23888. result->append(rec);
  23889. remote.injectResult(result.getClear());
  23890. }
  23891. if (accepted)
  23892. noteStatistic(StNumIndexAccepted, accepted);
  23893. if (rejected)
  23894. noteStatistic(StNumIndexRejected, rejected);
  23895. }
  23896. if (++fileNo < thisBase->numParts())
  23897. {
  23898. thisKey = thisBase->queryPart(fileNo);
  23899. tlk->setKey(thisKey);
  23900. if (thisKey && !thisKey->isTopLevelKey())
  23901. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23902. else
  23903. tlk->setLayoutTranslator(nullptr);
  23904. tlk->reset();
  23905. }
  23906. else
  23907. break;
  23908. }
  23909. tlk->releaseSegmentMonitors();
  23910. tlk->setKey(NULL);
  23911. }
  23912. catch (...)
  23913. {
  23914. tlk->releaseSegmentMonitors();
  23915. tlk->setKey(NULL);
  23916. throw;
  23917. }
  23918. }
  23919. }
  23920. noteEndReceived(jg, 0);
  23921. }
  23922. else
  23923. {
  23924. noteEndReceived(createJoinGroup(row), 0);
  23925. }
  23926. }
  23927. virtual void processEOG()
  23928. {
  23929. // called from front puller thread
  23930. if (preserveGroups)
  23931. endGroup();
  23932. }
  23933. void processGroup(const ConstPointerArray &)
  23934. {
  23935. throwUnexpected();
  23936. }
  23937. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23938. {
  23939. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23940. if (indexReadAllocator)
  23941. indexReadAllocator->gatherStats(merged);
  23942. if (joinFieldsAllocator)
  23943. joinFieldsAllocator->gatherStats(merged);
  23944. }
  23945. };
  23946. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  23947. {
  23948. Owned<const IResolvedFile> indexfile;
  23949. Owned<const IResolvedFile> datafile;
  23950. Owned<IKeyArray> keySet;
  23951. Owned<ITranslatorSet> keyTranslators; // For the indexes
  23952. RemoteActivityId headId;
  23953. RemoteActivityId tailId;
  23954. IOutputMetaData *indexReadMeta;
  23955. Owned<IFilePartMap> map;
  23956. Owned<ITranslatorSet> translators; // for the disk files on local full keyed joins
  23957. Owned<IFileIOArray> files;
  23958. unsigned joinFlags;
  23959. bool isHalfKeyed;
  23960. bool isLocal;
  23961. bool variableFetchFileName;
  23962. bool variableIndexFileName;
  23963. bool isSimple;
  23964. public:
  23965. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  23966. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  23967. {
  23968. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  23969. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  23970. isSimple = isLocal;
  23971. rtlDataAttr indexLayoutMeta;
  23972. size32_t indexLayoutSize = 0;
  23973. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  23974. assertex(indexLayoutSize== 0);
  23975. joinFlags = helper->getJoinFlags();
  23976. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23977. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23978. if (!variableIndexFileName)
  23979. {
  23980. bool isOpt = (joinFlags & JFindexoptional) != 0;
  23981. OwnedRoxieString indexFileName(helper->getIndexFileName());
  23982. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  23983. if (indexfile)
  23984. {
  23985. unsigned expectedCrc = helper->getIndexFormatCrc();
  23986. unsigned projectedCrc = helper->getProjectedIndexFormatCrc();
  23987. keyTranslators.setown(indexfile->getTranslators(projectedCrc, helper->queryProjectedIndexRecordSize(), expectedCrc, helper->queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23988. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  23989. }
  23990. }
  23991. if (keySet && keySet->length()==1 && !isSimple)
  23992. {
  23993. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  23994. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  23995. isSimple = true;
  23996. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  23997. }
  23998. if (!simpleLocalKeyedJoins)
  23999. isSimple = false;
  24000. isHalfKeyed = !helper->diskAccessRequired();
  24001. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  24002. if (!isHalfKeyed && !variableFetchFileName)
  24003. {
  24004. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  24005. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  24006. if (datafile)
  24007. {
  24008. if (isLocal) // Not sure this works
  24009. {
  24010. unsigned expectedCrc = helper->getDiskFormatCrc();
  24011. unsigned projectedCrc = helper->getProjectedFormatCrc();
  24012. translators.setown(datafile->getTranslators(expectedCrc, helper->queryProjectedDiskRecordSize(), projectedCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  24013. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  24014. }
  24015. else
  24016. map.setown(datafile->getFileMap());
  24017. }
  24018. }
  24019. }
  24020. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24021. {
  24022. if (isHalfKeyed)
  24023. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  24024. headId, keySet, keyTranslators, indexReadMeta, joinFlags, isSimple, isLocal);
  24025. else
  24026. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  24027. headId, keySet, keyTranslators, indexReadMeta,
  24028. tailId, map, joinFlags, isLocal); // MORE - not sure local variant actually works - should be using files not map, for example?
  24029. }
  24030. virtual const StatisticsMapping &queryStatsMapping() const
  24031. {
  24032. return keyedJoinStatistics;
  24033. }
  24034. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  24035. {
  24036. if (datafile)
  24037. addXrefFileInfo(reply, datafile);
  24038. if (indexfile)
  24039. addXrefFileInfo(reply, indexfile);
  24040. }
  24041. };
  24042. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  24043. {
  24044. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  24045. }
  24046. //=================================================================================
  24047. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  24048. {
  24049. protected:
  24050. Owned<ISoapCallHelper> soaphelper;
  24051. IHThorSoapActionArg & helper;
  24052. StringBuffer authToken;
  24053. bool eof;
  24054. CriticalSection crit;
  24055. ClientCertificate *pClientCert;
  24056. public:
  24057. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  24058. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24059. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  24060. {
  24061. eof = false;
  24062. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  24063. pClientCert = &clientCert;
  24064. else
  24065. pClientCert = NULL;
  24066. }
  24067. // ISoapCallRowProvider
  24068. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  24069. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  24070. virtual const void * getNextRow() { return NULL; };
  24071. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  24072. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24073. {
  24074. eof = false;
  24075. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  24076. authToken.append(ctx->queryAuthToken());
  24077. }
  24078. virtual void reset()
  24079. {
  24080. // MORE - Shouldn't we make sure thread is stopped etc???
  24081. soaphelper.clear();
  24082. CRoxieServerActivity::reset();
  24083. }
  24084. // IRoxieAbortMonitor
  24085. virtual void checkForAbort() { checkAbort(); }
  24086. };
  24087. //---------------------------------------------------------------------------
  24088. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  24089. {
  24090. IHThorSoapCallArg & callHelper;
  24091. public:
  24092. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24093. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24094. {
  24095. }
  24096. virtual IHThorSoapCallArg * queryCallHelper()
  24097. {
  24098. return &callHelper;
  24099. }
  24100. virtual bool needsAllocator() const { return true; }
  24101. virtual const void *nextRow()
  24102. {
  24103. ActivityTimer t(totalCycles, timeActivities);
  24104. if(eof) return NULL;
  24105. if (soaphelper == NULL)
  24106. {
  24107. if (factory->getKind()==TAKhttp_rowdataset)
  24108. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24109. else
  24110. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24111. soaphelper->start();
  24112. }
  24113. OwnedConstRoxieRow ret = soaphelper->getRow();
  24114. if (!ret)
  24115. {
  24116. eof = true;
  24117. return NULL;
  24118. }
  24119. ++processed;
  24120. return ret.getClear();
  24121. }
  24122. };
  24123. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  24124. {
  24125. public:
  24126. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24127. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24128. {
  24129. }
  24130. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24131. {
  24132. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24133. }
  24134. virtual const StatisticsMapping &queryStatsMapping() const
  24135. {
  24136. return soapStatistics;
  24137. }
  24138. };
  24139. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24140. {
  24141. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24142. }
  24143. //---------------------------------------------------------------------------
  24144. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  24145. {
  24146. public:
  24147. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24148. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24149. {}
  24150. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24151. {
  24152. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  24153. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24154. soaphelper->start();
  24155. soaphelper->waitUntilDone();
  24156. IException *e = soaphelper->getError();
  24157. soaphelper.clear();
  24158. if (e)
  24159. throw e;
  24160. }
  24161. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24162. {
  24163. return NULL;
  24164. }
  24165. virtual const void *nextRow()
  24166. {
  24167. throwUnexpected(); // I am nobody's input
  24168. }
  24169. };
  24170. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24171. {
  24172. bool isRoot;
  24173. public:
  24174. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24175. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24176. {
  24177. }
  24178. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24179. {
  24180. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24181. }
  24182. virtual bool isSink() const
  24183. {
  24184. return isRoot;
  24185. }
  24186. virtual const StatisticsMapping &queryStatsMapping() const
  24187. {
  24188. return soapStatistics;
  24189. }
  24190. };
  24191. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24192. {
  24193. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24194. }
  24195. //---------------------------------------------------------------------------
  24196. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24197. {
  24198. IHThorSoapCallArg & callHelper;
  24199. public:
  24200. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24201. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24202. {
  24203. }
  24204. virtual IHThorSoapCallArg * queryCallHelper()
  24205. {
  24206. return &callHelper;
  24207. }
  24208. virtual const void *getNextRow()
  24209. {
  24210. CriticalBlock b(crit); // MORE - why ?
  24211. return inputStream->ungroupedNextRow();
  24212. }
  24213. virtual bool needsAllocator() const { return true; }
  24214. virtual const void *nextRow()
  24215. {
  24216. ActivityTimer t(totalCycles, timeActivities);
  24217. if(eof) return NULL;
  24218. if (soaphelper == NULL)
  24219. {
  24220. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24221. soaphelper->start();
  24222. }
  24223. OwnedConstRoxieRow ret = soaphelper->getRow();
  24224. if (!ret)
  24225. {
  24226. eof = true;
  24227. return NULL;
  24228. }
  24229. ++processed;
  24230. return ret.getClear();
  24231. }
  24232. };
  24233. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24234. {
  24235. public:
  24236. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24237. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24238. {
  24239. }
  24240. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24241. {
  24242. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24243. }
  24244. virtual const StatisticsMapping &queryStatsMapping() const
  24245. {
  24246. return soapStatistics;
  24247. }
  24248. };
  24249. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24250. {
  24251. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24252. }
  24253. //---------------------------------------------------------------------------
  24254. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  24255. {
  24256. public:
  24257. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24258. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24259. {}
  24260. virtual const void *getNextRow()
  24261. {
  24262. CriticalBlock b(crit); // MORE - Why?
  24263. const void *nextrec = inputStream->ungroupedNextRow();
  24264. if (nextrec)
  24265. processed++;
  24266. return nextrec;
  24267. }
  24268. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24269. {
  24270. try
  24271. {
  24272. start(parentExtractSize, parentExtract, false);
  24273. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24274. soaphelper->start();
  24275. soaphelper->waitUntilDone();
  24276. IException *e = soaphelper->getError();
  24277. soaphelper.clear();
  24278. if (e)
  24279. throw e;
  24280. stop();
  24281. }
  24282. catch (IException *E)
  24283. {
  24284. ctx->notifyAbort(E);
  24285. abort();
  24286. throw;
  24287. }
  24288. catch(...)
  24289. {
  24290. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24291. ctx->notifyAbort(E);
  24292. abort();
  24293. throw;
  24294. }
  24295. }
  24296. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24297. {
  24298. return NULL;
  24299. }
  24300. virtual const void *nextRow()
  24301. {
  24302. throwUnexpected(); // I am nobody's input
  24303. }
  24304. };
  24305. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24306. {
  24307. bool isRoot;
  24308. public:
  24309. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24310. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24311. {
  24312. }
  24313. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24314. {
  24315. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24316. }
  24317. virtual bool isSink() const
  24318. {
  24319. return isRoot;
  24320. }
  24321. virtual const StatisticsMapping &queryStatsMapping() const
  24322. {
  24323. return soapStatistics;
  24324. }
  24325. };
  24326. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24327. {
  24328. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24329. }
  24330. //=====================================================================================================
  24331. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24332. {
  24333. IArrayOf<IGraphResult> results;
  24334. CriticalSection cs;
  24335. IGraphResult & select(unsigned idx)
  24336. {
  24337. CriticalBlock procedure(cs);
  24338. if (idx >= results.ordinality())
  24339. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24340. return results.item(idx);
  24341. }
  24342. public:
  24343. IMPLEMENT_IINTERFACE
  24344. void clear()
  24345. {
  24346. CriticalBlock procedure(cs);
  24347. results.kill();
  24348. }
  24349. virtual IEngineRowStream * createIterator(unsigned id)
  24350. {
  24351. return select(id).createIterator();
  24352. }
  24353. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24354. {
  24355. select(id).getLinkedResult(count, ret);
  24356. }
  24357. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24358. {
  24359. select(id).getLinkedResult(count, ret);
  24360. }
  24361. virtual const void * getLinkedRowResult(unsigned id)
  24362. {
  24363. return select(id).getLinkedRowResult();
  24364. }
  24365. void setResult(unsigned id, IGraphResult * result)
  24366. {
  24367. CriticalBlock procedure(cs);
  24368. if (results.ordinality() <= id)
  24369. {
  24370. while (results.ordinality() < id)
  24371. results.append(*new CGraphResult);
  24372. results.append(*LINK(result));
  24373. }
  24374. else
  24375. results.replace(*LINK(result), id);
  24376. }
  24377. void appendResult(IGraphResult * result)
  24378. {
  24379. CriticalBlock procedure(cs);
  24380. results.append(*LINK(result));
  24381. }
  24382. };
  24383. //===================================================================================================================
  24384. class CPseudoArg : implements CThorSinkArgOf<IHThorArg>
  24385. {
  24386. };
  24387. class CPseudoActivity : public CRoxieServerActivity
  24388. {
  24389. public:
  24390. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24391. virtual const void *nextRow()
  24392. {
  24393. throwUnexpected(); // I am nobody's input
  24394. }
  24395. };
  24396. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24397. {
  24398. protected:
  24399. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24400. {
  24401. SpinLock abortLock;
  24402. bool aborted;
  24403. Owned<IException> exception;
  24404. public:
  24405. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24406. {
  24407. aborted = false;
  24408. }
  24409. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24410. virtual void notifyAbort(IException *E)
  24411. {
  24412. if (QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24413. {
  24414. SpinBlock b(abortLock);
  24415. if (!aborted)
  24416. {
  24417. aborted = true;
  24418. exception.set(E);
  24419. }
  24420. }
  24421. }
  24422. virtual void checkAbort()
  24423. {
  24424. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24425. {
  24426. SpinBlock b(abortLock);
  24427. if (!exception)
  24428. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24429. throw exception.getLink();
  24430. }
  24431. IndirectSlaveContext::checkAbort();
  24432. }
  24433. virtual ICodeContext *queryCodeContext()
  24434. {
  24435. return codeContext;
  24436. }
  24437. void setCodeContext(ICodeContext * _codeContext)
  24438. {
  24439. codeContext = _codeContext;
  24440. }
  24441. void setLoopCounter(unsigned _loopCounter)
  24442. {
  24443. loopCounter = _loopCounter;
  24444. }
  24445. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24446. {
  24447. childGraphs.setValue(id, childGraph);
  24448. }
  24449. virtual IActivityGraph * queryChildGraph(unsigned id)
  24450. {
  24451. if (queryTraceLevel() > 10)
  24452. CTXLOG("resolveChildGraph %d", id);
  24453. IActivityGraph *childGraph = childGraphs.getValue(id);
  24454. assertex(childGraph);
  24455. return childGraph;
  24456. }
  24457. // MORE should really redirect the other log context ones too (though mostly doesn't matter). Really should refactor to have a queryLogContext() method in IRoxieSlaveContext I think
  24458. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24459. {
  24460. logctx.getLogPrefix(ret);
  24461. if (loopCounter)
  24462. ret.appendf("{%u}", loopCounter);
  24463. return ret;
  24464. }
  24465. protected:
  24466. const IRoxieContextLogger &logctx;
  24467. unsigned loopCounter;
  24468. ICodeContext * codeContext;
  24469. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24470. } graphSlaveContext;
  24471. class ActivityGraphCodeContext : public IndirectCodeContext
  24472. {
  24473. public:
  24474. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24475. {
  24476. if ((unsigned) activityId == container->queryId())
  24477. return container;
  24478. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24479. if (match)
  24480. return match->queryLocalGraph();
  24481. return IndirectCodeContext::resolveLocalQuery(activityId);
  24482. }
  24483. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24484. {
  24485. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24486. return LINK(match->queryChildGraph());
  24487. }
  24488. virtual unsigned getGraphLoopCounter() const
  24489. {
  24490. return container->queryLoopCounter(); // only called if value is valid
  24491. }
  24492. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24493. {
  24494. slaveContext = _slaveContext;
  24495. container = _container;
  24496. }
  24497. protected:
  24498. IRoxieSlaveContext * slaveContext;
  24499. CActivityGraph * container;
  24500. } graphCodeContext;
  24501. class SinkThread : public CInterface, implements IThreaded
  24502. {
  24503. public:
  24504. SinkThread(IActivityGraph &_parent, IRoxieServerActivity &_sink)
  24505. : thread("SinkThread", this), parent(_parent), sink(_sink)
  24506. {}
  24507. virtual void threadmain() override
  24508. {
  24509. try
  24510. {
  24511. sink.execute(parentExtractSize, parentExtract);
  24512. }
  24513. catch (IException *E)
  24514. {
  24515. parent.noteException(E);
  24516. throw;
  24517. }
  24518. }
  24519. void start(unsigned _parentExtractSize, const byte * _parentExtract)
  24520. {
  24521. parentExtract = _parentExtract;
  24522. parentExtractSize = _parentExtractSize;
  24523. thread.start();
  24524. }
  24525. inline void join()
  24526. {
  24527. thread.join(INFINITE);
  24528. }
  24529. private:
  24530. CThreadedPersistent thread;
  24531. IActivityGraph &parent;
  24532. IRoxieServerActivity &sink;
  24533. const byte * parentExtract = nullptr;
  24534. unsigned parentExtractSize = 0;
  24535. };
  24536. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24537. IArrayOf<IRoxieServerActivity> activities;
  24538. IArrayOf<IRoxieProbe> probes;
  24539. CIArrayOf<SinkThread> threads;
  24540. IRoxieServerActivityCopyArray sinks;
  24541. StringAttr graphName;
  24542. Owned<CGraphResults> results;
  24543. CGraphResults graphLoopResults;
  24544. const ActivityArray & graphDefinition;
  24545. CriticalSection evaluateCrit;
  24546. IProbeManager *probeManager;
  24547. IRoxieServerActivity *parentActivity;
  24548. unsigned id;
  24549. unsigned loopCounter;
  24550. public:
  24551. IMPLEMENT_IINTERFACE;
  24552. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24553. : parentActivity(_parentActivity), probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
  24554. {
  24555. id = x.getLibraryGraphId();
  24556. if (!id)
  24557. id = _id;
  24558. loopCounter = 0;
  24559. graphSlaveContext.setCodeContext(&graphCodeContext);
  24560. graphCodeContext.setContainer(&graphSlaveContext, this);
  24561. }
  24562. ~CActivityGraph()
  24563. {
  24564. if (probeManager)
  24565. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24566. }
  24567. virtual const char *queryName() const
  24568. {
  24569. return graphName.get();
  24570. }
  24571. void createGraph(IRoxieSlaveContext *_ctx)
  24572. {
  24573. if (graphDefinition.isMultiInstance())
  24574. {
  24575. graphCodeContext.set(_ctx->queryCodeContext());
  24576. _ctx = &graphSlaveContext;
  24577. }
  24578. ForEachItemIn(idx, graphDefinition)
  24579. {
  24580. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24581. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24582. activities.append(activity);
  24583. if (donor.isSink())
  24584. {
  24585. sinks.append(activity);
  24586. if (probeManager)
  24587. probeManager->noteSink(&activity);
  24588. }
  24589. }
  24590. ForEachItemIn(idx1, graphDefinition)
  24591. {
  24592. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24593. IRoxieServerActivity &activity = activities.item(idx1);
  24594. unsigned inputidx = 0;
  24595. for (;;)
  24596. {
  24597. unsigned outputidx;
  24598. unsigned source = donor.getInput(inputidx, outputidx);
  24599. if (source==(unsigned) -1)
  24600. break;
  24601. connectInput(idx1, inputidx, source, outputidx, 0);
  24602. inputidx++;
  24603. }
  24604. IntArray &dependencies = donor.queryDependencies();
  24605. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24606. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24607. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24608. ForEachItemIn(idx2, dependencies)
  24609. {
  24610. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24611. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24612. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24613. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24614. if (probeManager)
  24615. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24616. }
  24617. }
  24618. ForEachItemIn(idx2, sinks)
  24619. {
  24620. IRoxieServerActivity &sink = sinks.item(idx2);
  24621. sink.connectInputStreams(true);
  24622. }
  24623. }
  24624. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24625. {
  24626. IRoxieServerActivity &targetActivity = activities.item(target);
  24627. IRoxieServerActivity &sourceActivity = activities.item(source);
  24628. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24629. if (probeManager)
  24630. {
  24631. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24632. probes.append(*LINK(inputProbe));
  24633. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24634. }
  24635. targetActivity.setInput(targetIdx, sourceIdx, output);
  24636. }
  24637. virtual void onCreate(IHThorArg *_colocalParent)
  24638. {
  24639. ForEachItemIn(idx, activities)
  24640. {
  24641. IRoxieServerActivity *activity = &activities.item(idx);
  24642. if (activity)
  24643. activity->onCreate(_colocalParent);
  24644. }
  24645. }
  24646. virtual void abort()
  24647. {
  24648. ForEachItemIn(idx, sinks)
  24649. {
  24650. IRoxieServerActivity &sink = sinks.item(idx);
  24651. sink.abort();
  24652. }
  24653. }
  24654. virtual void reset()
  24655. {
  24656. ForEachItemIn(idx, sinks)
  24657. {
  24658. IRoxieServerActivity &sink = sinks.item(idx);
  24659. sink.reset();
  24660. }
  24661. }
  24662. Linked<IException> exception;
  24663. CriticalSection eCrit;
  24664. virtual void noteException(IException *E)
  24665. {
  24666. CriticalBlock b(eCrit);
  24667. if (!exception)
  24668. {
  24669. if (graphSlaveContext.queryDebugContext())
  24670. {
  24671. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24672. }
  24673. exception.set(E);
  24674. }
  24675. }
  24676. virtual void checkAbort()
  24677. {
  24678. CriticalBlock b(eCrit);
  24679. if (exception)
  24680. throw exception.getLink();
  24681. }
  24682. virtual void execute()
  24683. {
  24684. results.setown(new CGraphResults);
  24685. doExecute(0, NULL);
  24686. }
  24687. //New child query code...
  24688. virtual IThorChildGraph * queryChildGraph()
  24689. {
  24690. return this;
  24691. }
  24692. virtual IEclGraphResults * queryLocalGraph()
  24693. {
  24694. return this;
  24695. }
  24696. virtual IRoxieServerChildGraph * queryLoopGraph()
  24697. {
  24698. return this;
  24699. }
  24700. inline unsigned queryId() const
  24701. {
  24702. return id;
  24703. }
  24704. inline unsigned queryLoopCounter() const
  24705. {
  24706. return loopCounter;
  24707. }
  24708. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24709. {
  24710. if (sinks.ordinality()==1)
  24711. sinks.item(0).execute(parentExtractSize, parentExtract);
  24712. #ifdef PARALLEL_EXECUTE
  24713. else if (!probeManager && !graphDefinition.isSequential())
  24714. {
  24715. #ifdef PARALLEL_PERSISTANT_THREADS
  24716. if (!threads.ordinality())
  24717. {
  24718. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24719. {
  24720. threads.append(*new SinkThread(*this, sinks.item(i)));
  24721. }
  24722. }
  24723. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24724. threads.item(i).start(parentExtractSize, parentExtract);
  24725. sinks.item(sinks.ordinality()-1).execute(parentExtractSize, parentExtract);
  24726. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24727. threads.item(i).join();
  24728. #else
  24729. class casyncfor: public CAsyncFor
  24730. {
  24731. public:
  24732. IActivityGraph &parent;
  24733. unsigned parentExtractSize;
  24734. const byte * parentExtract;
  24735. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24736. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24737. void Do(unsigned i)
  24738. {
  24739. try
  24740. {
  24741. sinks.item(i).execute(parentExtractSize, parentExtract);
  24742. }
  24743. catch (IException *E)
  24744. {
  24745. parent.noteException(E);
  24746. throw;
  24747. }
  24748. }
  24749. private:
  24750. IRoxieServerActivityCopyArray &sinks;
  24751. } afor(sinks, *this, parentExtractSize, parentExtract);
  24752. afor.For(sinks.ordinality(), sinks.ordinality());
  24753. #endif
  24754. }
  24755. #endif
  24756. else
  24757. {
  24758. ForEachItemIn(idx, sinks)
  24759. {
  24760. IRoxieServerActivity &sink = sinks.item(idx);
  24761. sink.execute(parentExtractSize, parentExtract);
  24762. }
  24763. }
  24764. }
  24765. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24766. {
  24767. CriticalBlock block(evaluateCrit);
  24768. results.setown(new CGraphResults);
  24769. try
  24770. {
  24771. doExecute(parentExtractSize, parentExtract);
  24772. }
  24773. catch (...)
  24774. {
  24775. DBGLOG("Exception thrown in child query - cleaning up");
  24776. reset();
  24777. throw;
  24778. }
  24779. reset();
  24780. return results.getClear();
  24781. }
  24782. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  24783. {
  24784. if (id && statsBuilder)
  24785. {
  24786. statsBuilder->beginSubGraphScope(parentActivity->querySubgraphId());
  24787. statsBuilder->beginActivityScope(parentActivity->queryId());
  24788. statsBuilder->beginChildGraphScope(id);
  24789. }
  24790. ForEachItemIn(i, activities)
  24791. activities.item(i).gatherStatistics(statsBuilder);
  24792. if (id && statsBuilder)
  24793. {
  24794. statsBuilder->endScope();
  24795. statsBuilder->endScope();
  24796. statsBuilder->endScope();
  24797. }
  24798. }
  24799. //interface IRoxieServerChildGraph
  24800. virtual void beforeExecute()
  24801. {
  24802. results.setown(new CGraphResults);
  24803. }
  24804. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24805. {
  24806. IFinalRoxieInput * ret = selectOutput(id);
  24807. ret->start(parentExtractSize, parentExtract, paused);
  24808. return ret;
  24809. }
  24810. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24811. {
  24812. ForEachItemIn(i, sinks)
  24813. {
  24814. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24815. if (ret)
  24816. return ret;
  24817. }
  24818. throwUnexpected();
  24819. return NULL;
  24820. }
  24821. virtual void setInputResult(unsigned id, IGraphResult * result)
  24822. {
  24823. results->setResult(id, result);
  24824. }
  24825. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24826. {
  24827. ForEachItemIn(i, activities)
  24828. {
  24829. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24830. return true;
  24831. }
  24832. return false;
  24833. }
  24834. virtual void stopUnusedOutputs()
  24835. {
  24836. //Hmm not sure how to do this...
  24837. }
  24838. virtual void afterExecute()
  24839. {
  24840. ForEachItemIn(i, sinks)
  24841. {
  24842. sinks.item(i).stop();
  24843. }
  24844. if (graphSlaveContext.queryDebugContext())
  24845. {
  24846. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24847. }
  24848. reset();
  24849. }
  24850. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24851. {
  24852. doExecute(parentExtractSize, parentExtract);
  24853. return LINK(results);
  24854. }
  24855. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24856. {
  24857. results->getLinkedResult(count, ret, id);
  24858. }
  24859. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24860. {
  24861. results->getLinkedResult(count, ret, id);
  24862. }
  24863. virtual const void * getLinkedRowResult(unsigned id)
  24864. {
  24865. return results->getLinkedRowResult(id);
  24866. }
  24867. virtual void setResult(unsigned id, IGraphResult * result)
  24868. {
  24869. results->setResult(id, result);
  24870. }
  24871. virtual IEngineRowStream * createResultIterator(unsigned id)
  24872. {
  24873. return results->createIterator(id);
  24874. }
  24875. virtual void setGraphLoopResult(IGraphResult * result)
  24876. {
  24877. graphLoopResults.appendResult(result);
  24878. }
  24879. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24880. {
  24881. try
  24882. {
  24883. return graphLoopResults.createIterator(id);
  24884. }
  24885. catch (IException * e)
  24886. {
  24887. e->Release();
  24888. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24889. }
  24890. }
  24891. virtual void clearGraphLoopResults()
  24892. {
  24893. graphLoopResults.clear();
  24894. }
  24895. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24896. {
  24897. doExecute(parentExtractSize, parentExtract);
  24898. }
  24899. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24900. {
  24901. graphLoopResults.setResult(id, result);
  24902. }
  24903. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24904. {
  24905. return graphLoopResults.createIterator(id);
  24906. }
  24907. virtual void getProbeResponse(IPropertyTree *query)
  24908. {
  24909. if (probeManager)
  24910. probeManager->getProbeResponse(query);
  24911. }
  24912. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24913. {
  24914. throwUnexpected();
  24915. }
  24916. virtual CGraphIterationInfo *selectGraphLoopOutput()
  24917. {
  24918. return NULL;
  24919. }
  24920. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  24921. {
  24922. throwUnexpected();
  24923. }
  24924. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  24925. {
  24926. throwUnexpected();
  24927. }
  24928. };
  24929. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  24930. {
  24931. public:
  24932. IMPLEMENT_IINTERFACE;
  24933. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  24934. : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel), parentActivity(_parentActivity)
  24935. {
  24936. }
  24937. virtual void abort() override { throwUnexpected(); }
  24938. virtual void reset() override { throwUnexpected(); }
  24939. virtual void execute() override { throwUnexpected(); }
  24940. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  24941. virtual void onCreate(IHThorArg *_colocalArg) override
  24942. {
  24943. colocalArg = _colocalArg;
  24944. }
  24945. virtual void noteException(IException *E) override { throwUnexpected(); }
  24946. virtual void checkAbort() override { throwUnexpected(); }
  24947. virtual IThorChildGraph * queryChildGraph() override { return this; }
  24948. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  24949. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  24950. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override { throwUnexpected(); }
  24951. virtual const char *queryName() const override { throwUnexpected(); }
  24952. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  24953. {
  24954. CriticalBlock b(graphCrit);
  24955. ForEachItemIn(i, stack)
  24956. stack.item(i).gatherStatistics(statsBuilder);
  24957. }
  24958. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract) override
  24959. {
  24960. Owned<CActivityGraph> realGraph;
  24961. {
  24962. CriticalBlock b(graphCrit);
  24963. if (stack.length())
  24964. realGraph.setown(&stack.popGet());
  24965. }
  24966. if (!realGraph)
  24967. {
  24968. realGraph.setown(new CActivityGraph(ctx, graphName, id, parentActivity, graphDefinition, NULL, logctx));
  24969. realGraph->createGraph(ctx);
  24970. realGraph->onCreate(colocalArg);
  24971. }
  24972. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  24973. {
  24974. CriticalBlock b(graphCrit);
  24975. stack.append(*realGraph.getClear());
  24976. }
  24977. return results.getClear();
  24978. }
  24979. protected:
  24980. IRoxieSlaveContext *ctx;
  24981. IRoxieServerActivity *parentActivity;
  24982. StringAttr graphName;
  24983. unsigned id;
  24984. ActivityArray &graphDefinition;
  24985. const IRoxieContextLogger &logctx;
  24986. unsigned numParallel;
  24987. IHThorArg *colocalArg = nullptr;
  24988. mutable CriticalSection graphCrit;
  24989. CIArrayOf<CActivityGraph> stack;
  24990. };
  24991. class CIterationActivityGraph : public CActivityGraph
  24992. {
  24993. IHThorArg * colocalParent;
  24994. unsigned fixedParentExtractSize;
  24995. const byte * fixedParentExtract;
  24996. unsigned graphOutputActivityIndex;
  24997. public:
  24998. CIterationActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager,
  24999. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  25000. : CActivityGraph(_ctx, _graphName, _id, _parentActivity, x, _probeManager, _logctx)
  25001. {
  25002. graphOutputActivityIndex = 0;
  25003. loopCounter = _loopCounter;
  25004. colocalParent = _colocalParent;
  25005. graphSlaveContext.setLoopCounter(loopCounter);
  25006. graphCodeContext.set(_ctx->queryCodeContext());
  25007. fixedParentExtractSize = parentExtractSize;
  25008. fixedParentExtract = parentExtract;
  25009. }
  25010. void createIterationGraph(IRoxieSlaveContext *_ctx)
  25011. {
  25012. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  25013. ForEachItemIn(idx1, graphDefinition)
  25014. activities.append(*LINK(pseudoActivity));
  25015. graphOutputActivityIndex = queryGraphOutputIndex();
  25016. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  25017. }
  25018. unsigned queryGraphOutputIndex() const
  25019. {
  25020. ForEachItemIn(i, graphDefinition)
  25021. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  25022. return i;
  25023. throwUnexpected();
  25024. }
  25025. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  25026. {
  25027. //Check to see if already created
  25028. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  25029. if (prevActivity.queryId() != 0)
  25030. {
  25031. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  25032. return;
  25033. }
  25034. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  25035. IRoxieServerActivity * activity = NULL;
  25036. if (donor.isGraphInvariant())
  25037. {
  25038. ThorActivityKind kind = donor.getKind();
  25039. switch (kind)
  25040. {
  25041. case TAKif:
  25042. case TAKchildif:
  25043. case TAKcase:
  25044. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  25045. {
  25046. Owned<IHThorArg> helper = &donor.getHelper();
  25047. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  25048. helper->onStart(fixedParentExtract, NULL);
  25049. unsigned branch;
  25050. switch (kind)
  25051. {
  25052. case TAKif: case TAKchildif:
  25053. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  25054. break;
  25055. case TAKcase: case TAKchildcase:
  25056. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  25057. if (branch >= donor.numInputs())
  25058. branch = donor.numInputs() - 1;
  25059. break;
  25060. default:
  25061. throwUnexpected();
  25062. }
  25063. helper.clear();
  25064. unsigned outputidx;
  25065. unsigned source = donor.getInput(branch, outputidx);
  25066. if (source ==(unsigned) -1)
  25067. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  25068. else
  25069. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  25070. activities.replace(*activity, whichActivity);
  25071. activity->onCreate(colocalParent);
  25072. if (source ==(unsigned) -1)
  25073. return;
  25074. recursiveCreateGraph(_ctx, source);
  25075. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  25076. break;
  25077. }
  25078. }
  25079. }
  25080. if (!activity)
  25081. {
  25082. activity = donor.createActivity(&graphSlaveContext, probeManager);
  25083. activities.replace(*activity, whichActivity);
  25084. activity->onCreate(colocalParent);
  25085. activity->resetOutputsUsed();
  25086. unsigned inputidx = 0;
  25087. for (;;)
  25088. {
  25089. unsigned outputidx;
  25090. unsigned source = donor.getInput(inputidx, outputidx);
  25091. if (source==(unsigned) -1)
  25092. break;
  25093. recursiveCreateGraph(_ctx, source);
  25094. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  25095. inputidx++;
  25096. }
  25097. }
  25098. IntArray &dependencies = donor.queryDependencies();
  25099. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  25100. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  25101. ForEachItemIn(idx2, dependencies)
  25102. {
  25103. unsigned input = dependencies.item(idx2);
  25104. recursiveCreateGraph(_ctx, input);
  25105. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  25106. }
  25107. }
  25108. virtual CGraphIterationInfo *selectGraphLoopOutput()
  25109. {
  25110. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  25111. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  25112. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  25113. }
  25114. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  25115. {
  25116. ForEachItemIn(i, activities)
  25117. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  25118. }
  25119. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  25120. {
  25121. ForEachItemIn(i, activities)
  25122. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  25123. }
  25124. };
  25125. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  25126. {
  25127. StringAttr graphName;
  25128. ActivityArray & graphDefinition;
  25129. IProbeManager *probeManager;
  25130. unsigned id;
  25131. IRoxieSlaveContext * ctx;
  25132. IHThorArg * colocalParent;
  25133. IRoxieServerActivity *parentActivity;
  25134. public:
  25135. IMPLEMENT_IINTERFACE;
  25136. CDelayedActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager)
  25137. : probeManager(_probeManager), parentActivity(_parentActivity), graphDefinition(x)
  25138. {
  25139. graphName.set(_graphName);
  25140. id = _id;
  25141. ctx = NULL;
  25142. colocalParent = NULL;
  25143. }
  25144. virtual const char *queryName() const override { return graphName.get(); }
  25145. virtual void abort() override { throwUnexpected(); }
  25146. virtual void reset() override { }
  25147. virtual void execute() override { throwUnexpected(); }
  25148. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  25149. virtual void noteException(IException *E) override { throwUnexpected(); }
  25150. virtual void checkAbort() override { throwUnexpected(); }
  25151. virtual IThorChildGraph * queryChildGraph() override { throwUnexpected(); }
  25152. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25153. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25154. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override { }
  25155. virtual void onCreate(IHThorArg *_colocalParent) override
  25156. {
  25157. colocalParent = _colocalParent;
  25158. }
  25159. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override
  25160. {
  25161. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, parentActivity, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  25162. ret->createIterationGraph(ctx);
  25163. return ret.getClear();
  25164. }
  25165. };
  25166. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  25167. {
  25168. if (childFactories.isDelayed())
  25169. {
  25170. assertex(numParallel==1);
  25171. return new CDelayedActivityGraph(_graphName, id, parentActivity, childFactories, _probeManager);
  25172. }
  25173. else
  25174. {
  25175. if (numParallel==1 || _probeManager != nullptr)
  25176. {
  25177. Owned<IProbeManager> childProbe;
  25178. if (_probeManager)
  25179. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  25180. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, parentActivity, childFactories, childProbe, _logctx);
  25181. ret->createGraph(ctx);
  25182. if (_probeManager)
  25183. _probeManager->endChildGraph(childProbe, parentActivity);
  25184. return ret.getClear();
  25185. }
  25186. else
  25187. return new CProxyActivityGraph(ctx, _graphName, id, parentActivity, childFactories, _logctx, numParallel);
  25188. }
  25189. }
  25190. //================================================================================================================
  25191. #ifdef _USE_CPPUNIT
  25192. #include "unittests.hpp"
  25193. // 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...
  25194. #if _MSC_VER==1200
  25195. #undef protected
  25196. #endif
  25197. static const char *sortAlgorithm;
  25198. class TestMetaData : public CInterface, implements IOutputMetaData
  25199. {
  25200. public:
  25201. IMPLEMENT_IINTERFACE;
  25202. virtual size32_t getRecordSize(const void *) { return 10; }
  25203. virtual size32_t getMinRecordSize() const { return 10; }
  25204. virtual size32_t getFixedSize() const { return 10; }
  25205. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25206. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25207. virtual unsigned getMetaFlags() { return 0; }
  25208. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  25209. virtual void destruct(byte * self) {}
  25210. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25211. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25212. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  25213. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25214. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25215. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25216. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  25217. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25218. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25219. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); }
  25220. } testMeta;
  25221. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25222. {
  25223. char const * const *input;
  25224. IRoxieSlaveContext *ctx;
  25225. unsigned endSeen;
  25226. bool eof;
  25227. unsigned count;
  25228. ActivityTimeAccumulator totalCycles;
  25229. size32_t recordSize;
  25230. unsigned activityId;
  25231. public:
  25232. enum { STATEreset, STATEstarted, STATEstopped } state;
  25233. bool allRead;
  25234. unsigned repeat;
  25235. IMPLEMENT_IINTERFACE;
  25236. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  25237. {
  25238. ctx = _ctx;
  25239. input = _input;
  25240. count = 0;
  25241. eof = false;
  25242. allRead = false;
  25243. endSeen = 0;
  25244. recordSize = testMeta.getFixedSize();
  25245. state = STATEreset;
  25246. activityId = 1;
  25247. repeat = 0;
  25248. }
  25249. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25250. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25251. {
  25252. ASSERT(state == STATEreset);
  25253. }
  25254. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25255. {
  25256. ASSERT(state == STATEreset);
  25257. state = STATEstarted;
  25258. }
  25259. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25260. {
  25261. streams.append(this);
  25262. return NULL;
  25263. }
  25264. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25265. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25266. virtual IRoxieServerActivity *queryActivity()
  25267. {
  25268. throwUnexpected();
  25269. }
  25270. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25271. {
  25272. throwUnexpected();
  25273. }
  25274. virtual void stop()
  25275. {
  25276. state = STATEstopped;
  25277. }
  25278. virtual void reset()
  25279. {
  25280. ASSERT(state == STATEstopped);
  25281. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25282. }
  25283. virtual void resetEOF()
  25284. {
  25285. throwUnexpected();
  25286. }
  25287. virtual void checkAbort() {}
  25288. virtual unsigned queryId() const { return activityId; };
  25289. virtual const void *nextRow()
  25290. {
  25291. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  25292. ASSERT(state == STATEstarted);
  25293. ASSERT(allRead || !eof);
  25294. if (eof)
  25295. return NULL;
  25296. again:
  25297. const char *nextSource = input[count++];
  25298. if (nextSource)
  25299. {
  25300. endSeen = 0;
  25301. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25302. memset(ret, 0, recordSize);
  25303. strncpy((char *) ret, nextSource, recordSize);
  25304. return ret;
  25305. }
  25306. else if (repeat)
  25307. {
  25308. repeat--;
  25309. count = 0;
  25310. goto again;
  25311. }
  25312. else
  25313. {
  25314. endSeen++;
  25315. if (endSeen==2)
  25316. eof = true;
  25317. return NULL;
  25318. }
  25319. }
  25320. virtual bool nextGroup(ConstPointerArray & group)
  25321. {
  25322. const void * next;
  25323. while ((next = nextRow()) != NULL)
  25324. group.append(next);
  25325. if (group.ordinality())
  25326. return true;
  25327. return false;
  25328. }
  25329. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  25330. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  25331. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25332. {
  25333. return NULL;
  25334. }
  25335. };
  25336. struct SortActivityTest : public CThorSortArg {
  25337. public:
  25338. struct CompareClass : public ICompare {
  25339. virtual int docompare(const void * _left, const void * _right) const {
  25340. return memcmp(_left, _right, 5);
  25341. }
  25342. } compare;
  25343. virtual ICompare * queryCompare() { return &compare; }
  25344. virtual IOutputMetaData * queryOutputMeta()
  25345. {
  25346. return &testMeta;
  25347. }
  25348. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25349. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25350. };
  25351. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25352. struct MergeActivityTest : public CThorMergeArg {
  25353. static bool isDedup;
  25354. public:
  25355. struct CompareClass : public ICompare {
  25356. virtual int docompare(const void * _left, const void * _right) const {
  25357. return memcmp(_left, _right, 5);
  25358. }
  25359. } compare;
  25360. virtual ICompare * queryCompare() { return &compare; }
  25361. virtual IOutputMetaData * queryOutputMeta()
  25362. {
  25363. return &testMeta;
  25364. }
  25365. virtual bool dedup() { return isDedup; }
  25366. };
  25367. bool MergeActivityTest::isDedup = false;
  25368. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25369. struct SplitActivityTest : public CThorSplitArg {
  25370. public:
  25371. virtual unsigned numBranches() { return 2; }
  25372. virtual IOutputMetaData * queryOutputMeta()
  25373. {
  25374. return &testMeta;
  25375. }
  25376. };
  25377. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25378. class CcdServerTest : public CppUnit::TestFixture
  25379. {
  25380. CPPUNIT_TEST_SUITE(CcdServerTest);
  25381. CPPUNIT_TEST(testSetup);
  25382. CPPUNIT_TEST(testHeapSort);
  25383. CPPUNIT_TEST(testQuickSort);
  25384. CPPUNIT_TEST(testMerge);
  25385. CPPUNIT_TEST(testMergeDedup);
  25386. CPPUNIT_TEST(testMiscellaneous);
  25387. CPPUNIT_TEST(testSplitter);
  25388. CPPUNIT_TEST(testCleanup);
  25389. CPPUNIT_TEST_SUITE_END();
  25390. protected:
  25391. SlaveContextLogger logctx;
  25392. Owned<const IQueryDll> queryDll;
  25393. Owned<IRoxiePackage> package;
  25394. Owned<IPropertyTree> stateInfo;
  25395. Owned<IQueryFactory> queryFactory;
  25396. Owned<IRoxieSlaveContext> ctx;
  25397. void testSetup()
  25398. {
  25399. selfTestMode = true;
  25400. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25401. }
  25402. void testCleanup()
  25403. {
  25404. roxiemem::releaseRoxieHeap();
  25405. }
  25406. void init()
  25407. {
  25408. package.setown(createRoxiePackage(NULL, NULL));
  25409. queryDll.setown(createExeQueryDll("roxie"));
  25410. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25411. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25412. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25413. queryActiveTimer()->reset();
  25414. }
  25415. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25416. {
  25417. testActivity(activity, input, NULL, output);
  25418. }
  25419. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25420. {
  25421. TestInput in(ctx, input);
  25422. TestInput in2(ctx, input2);
  25423. activity->setInput(0, 0, &in);
  25424. if (input2)
  25425. activity->setInput(1, 0, &in2);
  25426. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25427. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25428. IOutputMetaData *meta = out->queryOutputMeta();
  25429. void *buf = alloca(meta->getFixedSize());
  25430. for (unsigned iteration = 0; iteration < 8; iteration++)
  25431. {
  25432. // 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)
  25433. // This should be true whether we read all, some, or none of the data.
  25434. // Should not matter if an activity is not started
  25435. if (iteration % 4 == 0)
  25436. activity->onCreate(NULL);
  25437. unsigned count = 0;
  25438. if (iteration % 4 != 3)
  25439. {
  25440. activity->start(0, NULL, false);
  25441. ASSERT(in.state == TestInput::STATEstarted);
  25442. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25443. for (;;)
  25444. {
  25445. const void *next = outStream->nextRow();
  25446. if (!next)
  25447. {
  25448. ASSERT(output[count++] == NULL);
  25449. next = outStream->nextRow();
  25450. if (!next)
  25451. {
  25452. ASSERT(output[count++] == NULL);
  25453. break;
  25454. }
  25455. }
  25456. ASSERT(output[count] != NULL);
  25457. unsigned outsize = meta->getRecordSize(next);
  25458. memset(buf, 0, outsize);
  25459. strncpy((char *) buf, output[count++], outsize);
  25460. ASSERT(memcmp(next, buf, outsize) == 0);
  25461. ReleaseRoxieRow(next);
  25462. if (iteration % 4 == 2)
  25463. break;
  25464. }
  25465. if (iteration % 4 != 2)
  25466. {
  25467. // Check that reading after end is harmless
  25468. in.allRead = true;
  25469. const void *next = outStream->nextRow();
  25470. ASSERT(next == NULL);
  25471. }
  25472. }
  25473. activity->stop();
  25474. ASSERT(in.state == TestInput::STATEstopped);
  25475. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25476. activity->reset();
  25477. ASSERT(in.state == TestInput::STATEreset);
  25478. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25479. ctx->queryRowManager().reportLeaks();
  25480. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25481. }
  25482. }
  25483. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25484. {
  25485. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25486. TestInput in(ctx, input);
  25487. in.repeat = repeat;
  25488. activity->setInput(0, 0, &in);
  25489. ArrayOf<IFinalRoxieInput *> out;
  25490. for (unsigned i = 0; i < numOutputs; i++)
  25491. {
  25492. out.append(activity->queryOutput(i));
  25493. }
  25494. activity->onCreate(NULL);
  25495. class casyncfor: public CAsyncFor
  25496. {
  25497. public:
  25498. casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
  25499. : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
  25500. {}
  25501. void Do(unsigned i)
  25502. {
  25503. IFinalRoxieInput *out = outputs.item(i);
  25504. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25505. out->start(0, NULL, false);
  25506. IOutputMetaData *meta = out->queryOutputMeta();
  25507. void *buf = alloca(meta->getFixedSize());
  25508. unsigned count = 0;
  25509. unsigned repeats = repeat;
  25510. for (;;)
  25511. {
  25512. const void *next = outStream->nextRow();
  25513. if (!next)
  25514. {
  25515. ASSERT(repeats==0);
  25516. ASSERT(output[count] == NULL);
  25517. count++;
  25518. next = outStream->nextRow();
  25519. if (!next)
  25520. {
  25521. ASSERT(output[count] == NULL);
  25522. count++;
  25523. break;
  25524. }
  25525. }
  25526. if (output[count] == NULL && repeats)
  25527. {
  25528. repeats--;
  25529. count = 0;
  25530. }
  25531. ASSERT(output[count] != NULL);
  25532. unsigned outsize = meta->getRecordSize(next);
  25533. memset(buf, 0, outsize);
  25534. strncpy((char *) buf, output[count++], outsize);
  25535. ASSERT(memcmp(next, buf, outsize) == 0);
  25536. ReleaseRoxieRow(next);
  25537. }
  25538. outStream->stop();
  25539. }
  25540. private:
  25541. IRoxieServerActivity *activity;
  25542. ArrayOf<IFinalRoxieInput *> &outputs;
  25543. char const * const *input;
  25544. char const * const *output;
  25545. unsigned repeat;
  25546. CcdServerTest *parent;
  25547. } afor(this, activity, out, input, output, repeat);
  25548. afor.For(numOutputs, numOutputs);
  25549. ASSERT(in.state == TestInput::STATEstopped);
  25550. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25551. {
  25552. out.item(i2)->reset();
  25553. }
  25554. ASSERT(in.state == TestInput::STATEreset);
  25555. ctx->queryRowManager().reportLeaks();
  25556. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25557. }
  25558. static int compareFunc(const void *l, const void *r)
  25559. {
  25560. return strcmp(*(char **) l, *(char **) r);
  25561. }
  25562. void testSort(unsigned type)
  25563. {
  25564. init();
  25565. sortAlgorithm = NULL;
  25566. if (type==2)
  25567. sortAlgorithm = "heapSort";
  25568. else
  25569. sortAlgorithm = "quickSort";
  25570. DBGLOG("Testing %s activity", sortAlgorithm);
  25571. Owned<IPropertyTree> dummyNode = createPTree("node");
  25572. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25573. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25574. const char * test[] = { NULL, NULL };
  25575. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25576. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25577. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25578. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25579. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25580. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25581. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25582. testActivity(activity, test, test);
  25583. testActivity(activity, test12345, test12345);
  25584. testActivity(activity, test54321, test12345);
  25585. testActivity(activity, test11111, test11111);
  25586. testActivity(activity, test11111_12345, test11111_12345);
  25587. testActivity(activity, test11111_54321, test11111_12345);
  25588. testActivity(activity, test54321_54321, test12345_12345);
  25589. // A few larger tests
  25590. char *input[2002];
  25591. char *output[2002];
  25592. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25593. unsigned i;
  25594. // identical
  25595. for (i=0; i<2000; i++)
  25596. {
  25597. input[i] = new char[11];
  25598. output[i] = new char[11];
  25599. sprintf(input[i], "1");
  25600. sprintf(output[i], "1");
  25601. }
  25602. testActivity(activity, input, output);
  25603. // Ascending
  25604. for (i=0; i<2000; i++)
  25605. {
  25606. sprintf(input[i], "%04d", i);
  25607. sprintf(output[i], "%04d", i);
  25608. }
  25609. testActivity(activity, input, output);
  25610. // Almost sorted
  25611. for (i=0; i<20; i++)
  25612. {
  25613. unsigned h = i*100;
  25614. sprintf(input[h], "%04d", 1900-h);
  25615. }
  25616. testActivity(activity, input, output);
  25617. // Descending
  25618. for (i=0; i<2000; i++)
  25619. {
  25620. sprintf(input[i], "%04d", 1999-i);
  25621. sprintf(output[i], "%04d", i);
  25622. }
  25623. testActivity(activity, input, output);
  25624. // Random
  25625. for (i=0; i<2000; i++)
  25626. {
  25627. unsigned r = fastRand() % 1500;
  25628. sprintf(input[i], "%04d", r);
  25629. sprintf(output[i], "%04d", r);
  25630. }
  25631. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25632. testActivity(activity, input, output);
  25633. unsigned __int64 us = factory->queryLocalTimeNs();
  25634. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25635. factory->resetNodeProgressInfo();
  25636. if (type)
  25637. {
  25638. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25639. // All sort identical
  25640. for (i=0; i<2000; i++)
  25641. {
  25642. sprintf(input[i], "1 %d", i);
  25643. sprintf(output[i], "1 %d", i);
  25644. }
  25645. testActivity(activity, input, output);
  25646. // Already sorted
  25647. for (i=0; i<2000; i++)
  25648. {
  25649. sprintf(input[i], "%04d %d", i / 10, i);
  25650. sprintf(output[i], "%04d %d", i / 10, i);
  25651. }
  25652. testActivity(activity, input, output);
  25653. // Reverse order
  25654. for (i=0; i<2000; i++)
  25655. {
  25656. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25657. sprintf(output[i], "%04d %d", i / 10, i%10);
  25658. }
  25659. testActivity(activity, input, output);
  25660. }
  25661. for (i=0; i<2000; i++)
  25662. {
  25663. delete [] input[i];
  25664. delete [] output[i];
  25665. }
  25666. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25667. }
  25668. void testQuickSort()
  25669. {
  25670. testSort(0);
  25671. }
  25672. void testHeapSort()
  25673. {
  25674. testSort(2);
  25675. }
  25676. void testMerge()
  25677. {
  25678. DBGLOG("testMerge");
  25679. init();
  25680. Owned<IPropertyTree> splitterNode = createPTree();
  25681. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25682. factory->setInput(0,0,0);
  25683. factory->setInput(1,0,0);
  25684. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25685. const char * test[] = { NULL, NULL };
  25686. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25687. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25688. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25689. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25690. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25691. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25692. 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 };
  25693. testActivity(activity, test, test, test);
  25694. testActivity(activity, test12345, test, test12345);
  25695. testActivity(activity, test, test12345, test12345);
  25696. testActivity(activity, test12345, test12345, test1122334455);
  25697. testActivity(activity, test11111, test, test11111);
  25698. testActivity(activity, test, test11111, test11111);
  25699. testActivity(activity, test11111, test11111, test1111111111);
  25700. testActivity(activity, test11111_12345, test, test1111112345);
  25701. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25702. // Should really test WHICH side gets kept...
  25703. // Should test with more than 2 inputs...
  25704. DBGLOG("testMerge done");
  25705. }
  25706. void testMergeDedup()
  25707. {
  25708. DBGLOG("testMergeDedup");
  25709. init();
  25710. MergeActivityTest::isDedup = true;
  25711. Owned<IPropertyTree> splitterNode = createPTree();
  25712. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25713. factory->setInput(0,0,0);
  25714. factory->setInput(1,0,0);
  25715. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25716. const char * test[] = { NULL, NULL };
  25717. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25718. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25719. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25720. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25721. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25722. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25723. testActivity(activity, test, test11111, test11111);
  25724. testActivity(activity, test, test, test);
  25725. testActivity(activity, test12345, test, test12345);
  25726. testActivity(activity, test, test12345, test12345);
  25727. testActivity(activity, test12345, test12345, test12345);
  25728. testActivity(activity, test11111_12345, test, test1111112345);
  25729. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25730. // Should really test WHICH side gets kept...
  25731. // Should test with more than 2 inputs...
  25732. DBGLOG("testMergeDedup done");
  25733. }
  25734. void doTestSplitter(unsigned numOutputs)
  25735. {
  25736. DBGLOG("testSplit %d", numOutputs);
  25737. init();
  25738. Owned<IPropertyTree> splitterNode = createPTree();
  25739. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25740. factory->setInput(0,0,0);
  25741. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25742. const char * test[] = { NULL, NULL };
  25743. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25744. unsigned start = msTick();
  25745. testSplitActivity(factory, test, test, numOutputs, 0);
  25746. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25747. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25748. unsigned elapsed = msTick() - start;
  25749. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25750. }
  25751. void testSplitter()
  25752. {
  25753. doTestSplitter(1);
  25754. doTestSplitter(2);
  25755. doTestSplitter(3);
  25756. doTestSplitter(10);
  25757. }
  25758. void testMiscellaneous()
  25759. {
  25760. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25761. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25762. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25763. ASSERT(sizeof(CJoinGroup) <= 120);
  25764. }
  25765. };
  25766. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25767. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25768. #endif